Search code examples
pythontwitterstreamtweepy

How to stream tweets from a specified user (only stream when the tweet is published by this user) using tweepy


I tried the following codes:

    class MyListener(StreamListener):
        def on_data(self, data):
            print(data)
            return True

    listener = MyListener()
    auth = OAuthHandler(config.API_KEY, config.API_SECRET)
    auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)
    stream = Stream(auth, listener)
    stream.filter(follow=['<user_id>'])  # assume this user is a celebrity

What I got when running this code, is many spam-tweets or retweets by other users. (assume this <user id> is a celebrity, who has millions of followers. The followers are sharing the tweets all the time)


But I want to stream the original tweets published only by this specific <user id>. How can I implement this? Thanks in advance.


Solution

  • The official documentation says that using the follow parameter you get :

    • Tweets created by the user.
    • Tweets which are retweeted by the user.
    • Replies to any Tweet created by the user.
    • Retweets of any Tweet created by the user.
    • Manual replies, created without pressing a reply button (e.g. “@twitterapi I agree”).

    So you just have to skip tweets not posted by the specified user :

    def on_status(self, status):
        if status.user.id_str != '<user_id>':
            return
        print(status.text)