如何修改Reddit Bot代码,使其触发后每次返回随机回复?
Hey there! I spot the problem with your bot immediately — you're picking the random reply only once when the program starts, instead of every time someone triggers the command. Let me break this down and show you how to fix it.
The Root Cause
Your line random_item = random.choice(random_answer) lives in the global scope, outside any function. That means when you launch your bot, it picks one random string from the list and stores it in random_item permanently. No matter how many times someone uses !randomhelloworld, it'll keep replying with that same first choice until you restart the bot.
The Fixed Code
Here's the adjusted version that will generate a new random reply every time the command is triggered:
import praw import random random_answer = ['hello world 1', 'hello world 2', 'hello world 3'] QUESTIONS = ["!randomhelloworld"] 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(): # Pick a new random reply EVERY time we trigger the command random_item = random.choice(random_answer) comment.reply(random_item) break if __name__ == "__main__": main()
Key Changes Explained
- I moved the
random_item = random.choice(random_answer)line inside theprocess_commentfunction, right before sending the reply. Now every time someone uses the!randomhelloworldcommand, the bot will pull a fresh random selection from your list. - The rest of your code stays intact — we're just ensuring the random choice happens at the right moment (when the command is actually used) instead of once at startup.
That should resolve the issue and make your bot reply with a different random "hello world" each time it's called!
内容的提问来源于stack exchange,提问作者SavPhill

