此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()
答案 0 :(得分:3)
问题似乎在代码的这一点上
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))
答案 1 :(得分:1)
启动程序时,您一次将随机选择分配给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()