Tweepy 转发机器人不断循环

Tweepy retweet bot keeps looping

所以我已经在 Twitter 机器人上工作了一段时间,但我 运行 遇到了问题。每次我包含 api.retweet() 函数时,它都会运行我的函数两次。要阻止它,我所要做的就是将其注释掉。每次运行两次都会导致错误并终止我的程序。

我用除设置之外的尝试修复了那部分,但它仍然回复了两次,并尝试点赞两次。我不明白为什么它会这样做。如果我把它拿出来,它就会完全修复。

我把打印标签告诉我循环是怎么发生的,它进入了on_data函数(tweepy提供的检查是否收到数据),然后它进入我的check_data我的功能来检查我想过滤掉的短语和标签的数据)然后它进入我的retweetlike 功能。在完成这些之后,它会继续返回到我的 on_data 的末尾。如果没有转发,就到此为止。如果有一个,那么在结束之前它会再做一次。

流媒体 class:

class LEDStreamListener(tweepy.StreamListener):
    def on_data(self, raw_data):
        # with open("tweets.json", "w") as write_file:
            # write_file.write(raw_data)
        print('at the top boi')

        data = json.loads(raw_data)
        usr = data['user']['screen_name']

        tweet_id = data['id']

        if len(data['entities']['hashtags']) != 0:
            tag = data['entities']['hashtags'][0]['text']

        else:
            tag = ''

        data_check(usr, tweet_id, tag, counter)

        print('here in on_data now')

数据校验功能:

def data_check(twitter_user, tweet, tag, count):
    print('Entering data_check')

    if tag == 'HUNTER_LED_OFF':
        requests.get('http://192.168.1.172/off')
        retweet_tweet(tweet)
        api.update_status('I turned the led off for you', tweet)
        print('off')
        return

    elif tag == 'HUNTER_LED_ON':
        requests.get('http://192.168.1.172/on')
        retweet_tweet(tweet)
        api.update_status('I turned the led on for you', tweet)
        print('on')
        return

    elif tag == 'led_test':
        retweet_tweet(tweet)
        api.update_status('Nice test bro *highfives* keep up the good work', tweet)
        print('tested')
        return

    elif twitter_user == 'realDonaldTrump':
        print('Make America Great Again!')
        return

    else:
        return

转发功能:

def retweet_tweet(tweet_id):
    try:
        print('re-tweeting')
        api.retweet(tweet_id)
        api.create_favorite(tweet_id)
        print('done re-tweeting')
    except tweepy.TweepError as e:
        print(e)

收到的启用转推的推文的控制台输出

at the top boi

Entering data_check
re-tweeting
done re-tweeting
off
here in on_data now
at the top boi
Entering data_check
re-tweeting
[{'code': 327, 'message': 'You have already retweeted this Tweet.'}]
off(this is me editing this just says the state of the command it did to my robot)
here in on_data now

转推功能中没有转推行的控制台日志

at the top boi
Entering data_check
re-tweeting
done re-tweeting
off(this is me editing this just says the state of the command it did to my robot)
here in on_data now

好吧,让我们先说我对自己很生气,而且目前还没有为此与我的大脑说话。不确定我是否会原谅这个人。基本上,如果你 运行 进入这个错误,那是因为当你根据它的标签重新发布推文时,你会在你的页面上创建一个 post,上面有标签。绊倒机器人做事。为了修复它,我只是设置了一个变量 text = data['text'] 然后在我的 if 语句中,我检查了现在存储在我刚刚创建的变量中的 json 文件的文本部分是否以 'RT' 开头。通过说 if tag = '(your hashtag)' and not text.startswith('RT') 我在查看 json 文件时注意到他们都这样做了。