所以,我对python还是很陌生,做了一个简单的reddit机器人,它回复了评论。今天早上它运行良好,但现在它一遍又一遍地回复同样的评论,甚至是评论本身。我找不到如何通过不良的谷歌搜索技能来解决此问题的方法...所以,我来了。代码是这个
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的第一部分”我不知道出什么问题了,但它会自我说明。抱歉,我知道这是一个愚蠢的问题,可能之前已经解决过,但是我找不到它...
很抱歉,预先感谢您的帮助!
问题是您一次又一次地获取最新的25条评论,并且没有新的评论被进行(或者以缓慢的速度进行,因此您最终要重复处理相同的评论。) >
我建议改用流,这是PRAW的功能。流在发布时获取新项目(在这种情况下为评论)。这是使用流的代码的修改版本:
def run_bot(reddit):
try:
for comment in reddit.subreddit('test').stream.comments(skip_existing=True):
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)
except Exception as e:
print("Got exception: {}".format(e))
print("Sleeping for 10 seconds...")
time.sleep(10)