Search code examples
pythonpython-3.xrandomredditpraw

Reddit bot: random reply to comments


This reddit bot is designed to reply using a random answer to the comments in the subreddit when the keyword '!randomhelloworld' is called. It replies, but always displays the same comment, unless I stop and re-run the project. How can I tweak the code so that it always displays a random comment?

import praw
import random


random_answer = ['hello world 1', 'hello world 2', 'hello world 3']
QUESTIONS = ["!randomhelloworld"]
random_item = random.choice(random_answer)

def main():
    reddit = praw.Reddit(
        user_agent="johndoe",
        client_id="johndoe",
        client_secret="johndoe",
        username="johndoe",
        password="johndoe",
    )

    subreddit = reddit.subreddit("sandboxtest")
    for comment in subreddit.stream.comments():
            process_comment(comment)


def process_comment(comment):
    for question_phrase in QUESTIONS:
        if question_phrase in comment.body.lower():
         comment.reply (random_item)
        break


if __name__ == "__main__":
    main()


Solution

  • Looks like the issue is at this point of code

    random_item = random.choice(random_answer)
    .
    .
    .
    if question_phrase in comment.body.lower():
         comment.reply(random_item)
    

    You are assigning the randomized value to a variable at the beginning and using it in the below function. Hence, it is always returning the same value.

    You could change it this way and try.

    if question_phrase in comment.body.lower():
        comment.reply(random.choice(random_answer))