Reddit机器人:随机回复评论

2024-05-23 17:50:14 发布

您现在位置:Python中文网/ 问答频道 /正文

此reddit bot设计用于在关键字出现时,使用随机答案回复子reddit中的注释!将调用randomhelloworld'。它会回复,但始终显示相同的注释,除非我停止并重新运行项目。如何调整代码,使其始终显示随机注释

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

Tags: answerinimporthelloworldmaincommentrandom
2条回答

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

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

启动程序时,将随机选择分配给random_item一次。然后您就可以使用它返回到每个请求。若要在每个请求中进行新的随机选择,请将随机选择向上移动到该请求

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

相关问题 更多 >