Search code examples
python-3.xchatbotdiscord.pypraw

Discord bot fetching a random submission from a subreddit using praw (Python3)


Hey so basically I want to make it so my discord bot sends out a random submission from r/animemes when the user types out the command. I am very new to Python (and coding in general) and don't quite know how to do this. The code i've written currently sends out all 50 submissions at the same time but it does not pick out 1.

Here's my code:

@commands.command(aliases=['Animeme'])
async def animeme(self, ctx):

    reddit = praw.Reddit.(client_id="XXXXX",
                         client_secret="XXXXX",
                         user_agent="XXXXX")

    limit = random.randint(0, 50)
    for submission in reddit.subreddit("animemes").hot(limit=limit):
        await ctx.send(submission.url)

Thank you for your help =)


Solution

  • The PRAW documentation shows how to get a random post from a subreddit:

    submission = reddit.subreddit("AskReddit").random()
    

    So, you can use this in your code as follows:

    reddit = praw.Reddit.(client_id="XXXXX",
                         client_secret="XXXXX",
                         user_agent="XXXXX")
    
    submission = reddit.subreddit("animemes").random()
    await ctx.send(submission.url)