使用 Tweepy 访问 Twitter Stream API

Stream API 可实时访问推文。可以根据关键字,语言,位置等过滤流。这是一个跟踪 tweepy 一词的简单示例:

#set up a new class using tweepy.StreamListener

class SimpleListener(tweepy.StreamListener):
    def on_status(self, status): 
        #code to run each time the stream receives a status
        print(status.text)

    def on_direct_message(self, status): 
        #code to run each time the stream receives a direct message
        print(status.text)
    
    def on_data(self, status):
        #code to run each time you receive some data (direct message, delete, profile update, status,...)
        print(status.text)

    def on_error(self, staus_code):
        #code to run each time an error is received
        if status_code == 420:
            return False
        else:
            return True

#initialize the stream

tweepy_listener = SimpleListener()
tweepy_stream = tweepy.Stream(auth = api.auth, listener=tweepy_listener())
tweepy_stream.filter(track=['tweepy'])

你可以通过更改 track 参数来跟踪不同的关键字。

<to add: examples of filtering based on locations, languages, etc.>

你可以使用 userstream() 而不是过滤器来跟踪应用于你帐户的数据。

api.userstream(async=True)