温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - My reddit bot replies to same comment and itself over and over
praw python python-3.x reddit windows

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

发布于 2020-05-25 16:33:56

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

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

查看更多

提问者
Himanshu Mishra
被浏览
9
jarhill0 2020-03-09 21:55

问题在于您要一遍又一遍地获取最新的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)