代码之家  ›  专栏  ›  技术社区  ›  Oğuzhan Esen

向reddit bot添加回复计数器

  •  0
  • Oğuzhan Esen  · 技术社区  · 6 年前

    我有一个机器人,可以对包含特定关键词的评论/回复做出响应。为了防止人们滥发bot,我想添加一个计数器,以便当计数器达到某个数字时(例如,每个评论线程5次),我希望bot停止在该线程中响应。我想这样做的方法是添加一个计数器,每次bot响应一个注释线程时将其增加1。代码如下:

    import praw
    import config
    import os
    
    Black_list = []
    Counter = 0
    
    def bot_giris():
        r = praw.Reddit(username = config.username,
                    password = config.password,
                    client_id = config.client_id,
                    client_secret = config.client_secret,
                    user_agent = "Reddit bot")
    
    
        return r
    
    def bot_calis(r, comments_replied_to):
        subreddit = r.subreddit('gereksiz')
        for comment in subreddit.comments(limit=10):
            if 'Something' in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():
                print ("String found: " + comment.id)
                print(20*"-")
                print ("Comment author: ", comment.author)
                print(20*"-")
                comment.reply("Something else")
                Counter += 1
                print ("Responded: " + comment.id)
                print(20*"-")
    
                comments_replied_to.append(comment.id)
    
                with open ("comments_replied_to.txt", "a") as f:
                    f.write(comment.id + "\n")
    
    
        time.sleep(10)
    
    def get_saved_comments():
        if not os.path.isfile("comments_replied_to.txt"):
            comments_replied_to = []
        else:
            with open("comments_replied_to.txt", "r") as f:
                comments_replied_to = f.read()
                comments_replied_to = list(comments_replied_to)
                comments_replied_to = list(filter(None, comments_replied_to))
    
        return comments_replied_to
    
    r = bot_giris()
    comments_replied_to = get_saved_comments()
    
    
    while True:
        bot_calis(r, comments_replied_to)
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Joel    6 年前

    你好像忘了初始化 counter 写入变量 counter = 0 .

        2
  •  0
  •   clownbaby    6 年前

    您可以尝试添加一个冷却时间,例如,忽略所有回复5分钟,然后重新开始响应。像这样的:

    last = time.time()
    
    def bot_calis(r, comments_replied_to):
      subreddit = r.subreddit('gereksiz')
      for comment in subreddit.comments(limit=10):
        if 'Something' in comment.body and comment.id not in comments_replied_to and comment.author != r.user.me():
          ...
          if Counter >= 5:
            # 5 minute cool down
            # or, just return here
            if time.time() - last > 5 * 60 * 1000:
              Counter = 0
            else:
              return
          last = time.time()
          Counter += 1
          comment.reply("Something else")
          ...