【问题标题】:Reddit bot: random reply to commentsReddit 机器人:随机回复评论
【发布时间】:2020-06-30 12:00:32
【问题描述】:

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

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

【问题讨论】:

    标签: python python-3.x random reddit praw


    【解决方案1】:

    看来问题出在这段代码

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

    【讨论】:

      【解决方案2】:

      当您启动程序时,您将随机选择一次分配给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()
      

      【讨论】:

        猜你喜欢
        • 2021-08-28
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        • 2021-09-11
        • 1970-01-01
        相关资源
        最近更新 更多