开发者社区> 问答> 正文

我的reddit机器人一遍又一遍地回复相同的评论及其本身

因此,我是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部分”中,我不知道出什么问题了,但它会自我注释。抱歉,我知道这是一个愚蠢的问题,可能之前已经解决过,但我找不到...

再次抱歉,在此先感谢您的帮助!

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 23:52:40 884 0
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)
    

    回答来源:stackoverflow

    2020-03-24 23:52:49
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
下一代服务机器人的应用和创新 立即下载
机器人的小脑SLAMWARE - 机器人自主定位导航系统 立即下载
AIOps的核心技术之一:任务机器人如何在金融运维 运营中落地 立即下载