温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Reddit bot: random reply to comments
praw python python-3.x random reddit

python - Reddit Bot:随机回复评论

发布于 2020-06-03 17:31:48

此reddit机器人旨在在调用关键字'!randomhelloworld'对子 reddit中的评论使用随机答案进行回复它会答复,但始终显示相同的注释,除非我停止并重新运行该项目。如何调整代码,使其始终显示随机注释?

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

查看更多

提问者
P.Sav
被浏览
10
Raj 2020-03-19 19:01

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

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