因此,我是python的新手,并制作了一个简单的reddit bot来回复评论。今天早上它运行良好,但是现在它一次又一次地回复相同的评论,甚至是评论本身。我找不到如何使用较差的谷歌搜索技能来解决此问题的方法...所以,我来了。代码是这个
import praw
import time
import config
REPLY_MESSAGE = "Di Molto indeed"
def authenticate():
print("Authenticating...")
reddit = praw.Reddit(client_id = config.client_id,
client_secret = config.client_secret,
username = config.username,
password = config.password,
user_agent = 'FuriousVanezianLad by /u/FuriousVanezianLad')
print("Authenticated as {}".format(reddit.user.me()))
return reddit
def main():
reddit = authenticate()
while True:
run_bot(reddit)
def run_bot(reddit):
print("Obtaining 25 comments...")
for comment in reddit.subreddit('test').comments(limit=25):
if "Di Molto" in comment.body:
print('String with "Di Molto" found in comment {}',format(comment.id))
comment.reply(REPLY_MESSAGE)
print("Replied to comment " + comment.id)
print("Sleeping for 10 seconds...")
time.sleep(10)
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print("Interrupted")
我将这段代码从Bboe的更新中带到了“如何制作Reddit Bot-Busterroni的第1部分”中,我不知道出了什么问题,但它会自我注释。抱歉,我知道这是一个愚蠢的问题,可能之前已经解决过,但我找不到...
再次抱歉,在此先感谢您的帮助!
问题在于您要一遍又一遍地获取最新的25条评论,并且没有新的评论被进行(或者以缓慢的速度进行),因此您最终不得不重复处理相同的评论。
我建议改为使用流,这是PRAW功能。流在发布时获取新项目(在这种情况下为评论)。这样,您不会多次处理同一条评论。另外,在回复之前,请先检查您是否发表了评论。这是使用流并检查是否进行注释的代码的修改后的版本:
def run_bot(reddit):
me = reddit.user.me()
try:
for comment in reddit.subreddit('test').stream.comments(skip_existing=True):
if "Di Molto" in comment.body and comment.author != me:
print('String with "Di Molto" found in comment {}',format(comment.id))
comment.reply(REPLY_MESSAGE)
print("Replied to comment " + comment.id)
except Exception as e:
print("Got exception: {}".format(e))
print("Sleeping for 10 seconds...")
time.sleep(10)