使用 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)