Reddit 机器人:随机回复评论

Reddit bot: random reply to comments

此 reddit 机器人设计为在调用关键字 '!randomhelloworld' 时使用随机答案回复 subreddit 中的评论。它会回复,但总是显示相同的评论,除非我停止并重新 运行 该项目。我如何调整代码以使其始终显示随机评论?

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()

当您启动您的程序时,您将随机选择分配给 random_item 一次。然后你只是用它来 return 每个请求。要在每次请求时做出新的随机选择,请将随机选择移至请求。

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():
          random_item = random.choice(random_answer)
          comment.reply (random_item)
        break


if __name__ == "__main__":
    main()

看起来问题出在代码的这一点

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

您在开始时将随机值分配给一个变量,并在下面的函数中使用它。因此,它总是返回相同的值。

你可以改成这样试试

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