admin管理员组

文章数量:1122832

So I've been following a tutorial for scripting your own Discord bot and am completely stumped when trying to make this script for fetching random memes from Discord via the bot. When I run my main script it doesn't throw any errors at all and just simply doesn't work or give any feedback in Pycharm's log.

My Main Script

import discord
from discord.ext import commands, tasks
import os
import asyncio
from itertools import cycle

bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())

bot_statuses = cycle(["Status One", "Hello from Jimbo", "Status Code 123"])

@tasks.loop(seconds=5)
async def change_bot_status():
    await bot.change_presence(activity=discord.Game(next(bot_statuses)))

@bot.event
async def on_ready():
    print("Bot ready!")
    change_bot_status.start()


with open("token.txt") as file:
    token = file.read()

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main():
    async with bot:
        await load()
        await bot.start(token)


asyncio.run(main())

My Reddit Script

import discord
from discord.ext import commands
from random import choice
import asyncpraw as praw


class Reddit(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reddit = praw.Reddit(client_id="REDACTED", client_secret="REDACTED", user_agent="script:randommeme:v1.0 (by u/REDACTED)")
        print(type(self.reddit))

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{__name__} is ready!")

    @commandsmand()
    async  def meme(self, ctx: commands.Context):

        subreddit = await self.reddit.subreddit("memes")
        posts_lists = []

        async for post in subreddit.hot(limit=40):
            if not post.over_18 and post.author is not None and any(post.url.endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".gif"]):
                author_name = post.author.name
                posts_lists.append((post.url, author_name))
            if post.author is None:
                posts_lists.append((post.url, "N/A"))

            if posts_lists:

                random_post = choice(posts_list)

                meme_embed = discord.Embed(title="Random Name", description="Fetches random meme from r/memes", color=discord.Color.random())
                meme_embed.set_author(name=f"Meme requested by {ctx.author.name}", icon_url=ctx.author.avatar)
                meme_embed.set_image(url=random_post[0])
                meme_embed.set_footer(text=f"Post created by {random_post[1]}.", icon_url=None)
                await ctx.send(embed=meme_embed)

            else:
                await ctx.send("Unable to fetch post, try again later.")


    def cog_unload(self):
        self.bot.loop.create_task(self.reddit.close())


async def setup(bot):
    await bot.add_cog(Reddit(bot))

I've tried placing some print statements throughout the script to get an idea where the issue is, and I think I've narrowed it down to the meme() function on line 18. I'm fairly new to coding so this is as far as I was able to get on my own.

So I've been following a tutorial for scripting your own Discord bot and am completely stumped when trying to make this script for fetching random memes from Discord via the bot. When I run my main script it doesn't throw any errors at all and just simply doesn't work or give any feedback in Pycharm's log.

My Main Script

import discord
from discord.ext import commands, tasks
import os
import asyncio
from itertools import cycle

bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())

bot_statuses = cycle(["Status One", "Hello from Jimbo", "Status Code 123"])

@tasks.loop(seconds=5)
async def change_bot_status():
    await bot.change_presence(activity=discord.Game(next(bot_statuses)))

@bot.event
async def on_ready():
    print("Bot ready!")
    change_bot_status.start()


with open("token.txt") as file:
    token = file.read()

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main():
    async with bot:
        await load()
        await bot.start(token)


asyncio.run(main())

My Reddit Script

import discord
from discord.ext import commands
from random import choice
import asyncpraw as praw


class Reddit(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reddit = praw.Reddit(client_id="REDACTED", client_secret="REDACTED", user_agent="script:randommeme:v1.0 (by u/REDACTED)")
        print(type(self.reddit))

    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{__name__} is ready!")

    @commands.command()
    async  def meme(self, ctx: commands.Context):

        subreddit = await self.reddit.subreddit("memes")
        posts_lists = []

        async for post in subreddit.hot(limit=40):
            if not post.over_18 and post.author is not None and any(post.url.endswith(ext) for ext in [".png", ".jpg", ".jpeg", ".gif"]):
                author_name = post.author.name
                posts_lists.append((post.url, author_name))
            if post.author is None:
                posts_lists.append((post.url, "N/A"))

            if posts_lists:

                random_post = choice(posts_list)

                meme_embed = discord.Embed(title="Random Name", description="Fetches random meme from r/memes", color=discord.Color.random())
                meme_embed.set_author(name=f"Meme requested by {ctx.author.name}", icon_url=ctx.author.avatar)
                meme_embed.set_image(url=random_post[0])
                meme_embed.set_footer(text=f"Post created by {random_post[1]}.", icon_url=None)
                await ctx.send(embed=meme_embed)

            else:
                await ctx.send("Unable to fetch post, try again later.")


    def cog_unload(self):
        self.bot.loop.create_task(self.reddit.close())


async def setup(bot):
    await bot.add_cog(Reddit(bot))

I've tried placing some print statements throughout the script to get an idea where the issue is, and I think I've narrowed it down to the meme() function on line 18. I'm fairly new to coding so this is as far as I was able to get on my own.

Share Improve this question asked Nov 22, 2024 at 20:49 MonxerMonxer 11 bronze badge 1
  • i'm bias cause i don't like async in general, but could you try without that?, could you share your log outputs? if you are just getting started with coding, i stronly recomend you don't execute code from pycharm, use the native terminal of whatever OS you are using – Jose Angel Sanchez Commented Nov 22, 2024 at 23:15
Add a comment  | 

1 Answer 1

Reset to default 0

So after troubleshooting a little more I was able to finally get it working. Turns out it was just some user-error on my part. In the reddit script I made three major errors, in my meme function I simply had an extra space between "def" and the function. Secondly I made some indention errors with the if statements inside the meme function. Then lastly I misspelled the "posts_lists" variable when assigning it to the "random_post" variable later in the same block of code

本文标签: pythonReddit API script for Discord bot not workingStack Overflow