排除来自Twitter流-tweepy

问题描述

我正在使用tweepy从Twitter的流式API提取推文。然后,我使用它来自动回复用户

例如,如果我想从中获取实时推文,然后回复我使用的唐纳德·特朗普:

import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener

import json

class StdOutListener(StreamListener):
    def on_data(self,data):
        clean_data = json.loads(data)
        tweetId = clean_data["id"]
        tweet = "YOUR MESSAGE HERE"
        respondToTweet(tweet,tweetId)

def setUpAuth():
    auth = tweepy.OAuthHandler("consumer_token","consumer_secret")
    auth.set_access_token("access_token","Access_token_secret")
    api = tweepy.API(auth)
    return api,auth

def followStream():
    api,auth = setUpAuth()
    listener = StdOutListener()
    stream = Stream(auth,listener)
    stream.filter(follow=["25073877"],is_async=True)

def respondToTweet(tweet,tweetId):
    api,auth = setUpAuth()
    api.update_status(tweet,in_reply_to_status_id=tweetId,auto_populate_reply_Metadata=True)

if __name__ == "__main__":
    followStream()

如果运行上面的代码,您会注意到它的确回复了唐纳德·特朗普,但也回复了对他推文的所有新回复

我需要添加什么才能从流中排除对其推文的回复

在此先感谢您的帮助。

解决方法

  • 您可以添加条件以仅直接从follow id响应推文。
  • 这应该只允许对所关注的帐户做出响应。
  • 因此,在这种情况下,只有在跟随的帐户答复时,响应才是对tweetId的响应。
  • 对于多个用户,请使用in测试是否包含:
    • if user_id in [25073877,id2,id3,...]:
class StdOutListener(StreamListener):
    def on_data(self,data):
        clean_data = json.loads(data)
        tweetId = clean_data["id"]
        user_id = clean_data['user']['id']
        tweet = 'Trying to figure out this code to answer a question on SO,just ignore this'
        if user_id == 25073877:
            print('Tweeting a reply now')  # optional
            respondToTweet(tweet,tweetId)``