You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Reddit Bot代码,使其触发后每次返回随机回复?

Fixing Your Reddit Bot's Random Reply Issue

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 the process_comment function, right before sending the reply. Now every time someone uses the !randomhelloworld command, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:59:07