我有一个机器人,可以响应包含某些关键字的评论/回复。为了防止人们向该机器人发送垃圾邮件,我想添加一个计数器,以便当计数器达到某个数字(例如,每个注释线程5次)时,我希望该机器人停止在该线程中进行响应。我要执行此操作的方法是添加一个计数器,并在每次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)
答案 0 :(得分:0)
您似乎忘记了通过编写counter
来初始化counter = 0
变量。
答案 1 :(得分:0)
您可以尝试增加冷静时间,例如,忽略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")
...