Search code examples
pythondiscord.pypraw

Command raised an exception: AttributeError: 'Command' object has no attribute 'subreddit' Discord.PY


@client.command()
async def reddit(ctx):
    memes_submissions = reddit.subreddit('memes').hot()
    post_to_pick = random.randint(1, 10)
    for i in range(0, post_to_pick):
        submission = next(x for x in memes_submissions if not x.stickied)

    await ctx.send(submission.url)

This is my code. When I type .reddit it should find a random hot meme from r/memes. Instead of giving me some fresh memes, It gives me an error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Command' object has no attribute 'subreddit'

As I understand the program doesn't know what subreddit is. But I think it should get the subreddit command from PRAW. This is how I defined reddit:

reddit = praw.Reddit(client_id="id",
                 client_secret="secret",
                 user_agent="MASTERBOT")

I'm thinking that It might be because of me writing or defining the user_agent wrong because I have no idea what that does. I have everything imported as they should be. In everyone the code seems working. Might It be a preblem with my Python? I am running it on 3.8.


Solution

  • The same issue happened again with your namespace - you called your command reddit even though you already created your reddit variable outside of the command.

    Try renaming it:

    reddit = praw.Reddit(client_id="id", ....)
    
    @client.command(name="reddit") # this is what the command will be in discord
    async def _reddit(ctx):
        memes_submissions = reddit.subreddit('memes').hot()
        post_to_pick = random.randint(1, 10)
        for i in range(0, post_to_pick):
            submission = next(x for x in memes_submissions if not x.stickied)
    
        await ctx.send(submission.url)
    

    You've already got your variable reddit defined here:

    reddit = praw.Reddit(...)
    

    So having a function defined like so:

    async def reddit(...):
    

    will shadow the variable you defined outside, and if you try to refer to reddit within the function, it'll actually be looking at async def reddit(...): instead of reddit = praw.Reddit(...), as it's the most recent definition of the variable.