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

1

6

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.

Aurelea answered 23/8, 2019 at 23:7 Comment(0)
D
9

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)
Degree answered 24/8, 2019 at 11:56 Comment(1)
This would be my chosen solution, as well - drop anything that isn't generated by the specific account.Tufts

© 2022 - 2024 — McMap. All rights reserved.