Search code examples
pythonpython-3.xdiscord.pyprawasyncpraw

Praw & Discord.py: The bot keep sending the same meme. I want the bot to send different meme whenever it is asked


I am trying to create a listener for meme. The bot will respond to the message when it has "meme" in it. It has to send a meme. I am using Praw for that purpose.

This is the code I have written:

@nd.listen()
async def on_message(message):
    if message.author == nd.user:
        return
    
    def findCoindences(w):
        return re.compile(r'\b({0})\b'.format(w)).search
    content = message.content
    reaction = "👍"
    subreddit = reddit.subreddit("memes")
    for submission in subreddit.random():
        submission_link = submission.url
    
    if findCoindences('meme')(content.lower()):
        await message.reply(submission_link)
        await message.add_reaction(f"<{reaction}>")

Note: I have defined reddit already above some lines. That is not the cause I guess.


The problem:

Whenever I send meme in the chat it sends the same meme every time. I want it to be different but don't know where I am having this issue.

This is what it looks like: Ufff


Solution

  • There is no need for you to iterate over anything. Praw provides a method which allows you to grab a random submission from a subreddit.

    Documentation: random()

    Code:

    @nd.listen()
    async def on_message(message):
        if message.author == nd.user:
            return
        
        def findCoindences(w):
            return re.compile(r'\b({0})\b'.format(w)).search
        content = message.content
        reaction = "👍"
        
        if findCoindences('meme')(content.lower()):
            random_submission = reddit.subreddit('memes').random()
            await message.reply(random_submission.url)
            await message.add_reaction(f"<{reaction}>")
    

    Note: I have move the random_submission inside the If-statement because there is no need for you to look up a submission if the message doesn't say "meme". It would just waste rate limit.