Tweety对最新推文的回复进入循环

时间:2018-05-29 16:19:15

标签: python api twitter streaming tweepy

我有以下代码,我开始向用户发送流,当他发新推文时,我想按顺序对该推文做3回复。然而,机器人工作正常,它找到最新的推文,它开始像疯了一样随机回复,而不停止。我做错了什么?

class MyStreamListener(StreamListener):

    def on_data(self, data):
        ### here i get the statusid from json
        ### I have 3 replies in messages.txt which i want to reply 1 by 1 to the latest tweet (statusid)
        file = open("messages.txt", "r")
        content = file.readlines()
        for line in content:
            api.update_status(line, statusid)

    def on_error(self, status):
        print(status)

if __name__ == '__main__':
    listener = MyStreamListener()
    twitterStream = Stream(auth, listener)
    twitterStream.filter(follow=['xxxx'])

谢谢!

2 个答案:

答案 0 :(得分:0)

提示:您必须在答案开头提及用户才能正确回复。这是完整的代码:

import tweepy

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        file = open("messages.txt", "r")
        content = file.readlines()
        for line in content:
            print("answering @" + status.user.screen_name + " tweetID " + status.id_str + " with : " + line.rstrip())
            api.update_status(status="@" + status.user.screen_name + " " + line, in_reply_to_status_id=status.id)            

consumer_key = '***'
consumer_secret = '***'
access_token = '***'
access_token_secret = '***'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
myStream = tweepy.Stream(auth, MyStreamListener())
myStream.filter(follow=['xxx'])

答案 1 :(得分:0)

循环的原因是“关注”流将所有回复返回给关注的用户(以及该用户和由该用户转发的推文),因此您需要在继续回复行之前排除这些回复。参见Twitter Documentation.

例如,如果使用on_data()而不是on_status(),请先检查此from_creator(),然后再继续执行其他on_status()函数(请注意,on_status()返回删除等,这将在此函数中引发错误,因此请适当处理):

def from_creator(status):
    status = json.loads(status)
    if "retweeted_status" in status:
        return False
    elif status["in_reply_to_status_id"] != None:
        return False
    elif status["in_reply_to_screen_name"] != None:
        return False
    elif status["in_reply_to_user_id"] != None:
        return False
    else:
        # status is an origin Tweet by the followed user!
        return True

如果使用on_status(),它将是:

def from_creator(status):
    if hasattr(status, 'retweeted_status'):
        return False
    elif status.in_reply_to_status_id != None:
        return False
    elif status.in_reply_to_screen_name != None:
        return False
    elif status.in_reply_to_user_id != None:
        return False
    else:
        # status is an origin Tweet by the followed user!
        return True