Data_Science_110
Data_Science_110

Reputation: 41

Twitter Streaming API: only show tweets directed at a user and tweets from a user

I use the Twitter streaming API to retrieve the tweets that a certain user writes. To do so, I use

stream.filter(follow=['user_id'])

However, I do not only get the tweets of this user ID, but I guess also replies, retweets (?), I am not quite sure what all these tweets are that I get, but actually I only want to get those tweets which this single user writes. Is there a way I can exclude the other messages?

Also, I want to get all tweets that are directed at this person, so all tweets where this account is mentioned. Consequently, I would use. However, here I have the same problem as I get quite some tweets that do not only meet this criterion.

stream.filter(track=["@screen_name"])

I read that I might implement something like

def on_status(self, status):
    if status.retweeted_status:
        return
    print(status)

but I do not even know what exactly the code delivers me neither what I have to exclude, so I would be really thankful if you could help me with my problem.

Upvotes: 1

Views: 323

Answers (1)

Ethan Chen
Ethan Chen

Reputation: 680

Here's an example in which you can stream statuses posted by @elonmusk using the start_twitter_stream function:

from tweepy import API, OAuthHandler, Stream, errors
import os


TARGET_SCREEN_NAME = 'elonmusk'

class TweetListener(Stream):

    def on_status(self, status):
        if status.user.screen_name == TARGET_SCREEN_NAME:
            print(status.text)


def get_twitter_auth():
    auth = OAuthHandler(
        os.environ['TWITTER_CONSUMER_KEY'],
        os.environ['TWITTER_CONSUMER_SECRET'])
    auth.set_access_token(
        os.environ['TWITTER_ACCESS_KEY'],
        os.environ['TWITTER_ACCESS_SECRET'])
    print('Authenticated with Twitter API')
    return API(auth)

def get_user_id(screen_name):
    api = get_twitter_auth()
    try:
        user = api.get_user(screen_name=username)
        return user.id_str
    except errors.Forbidden:
        print(f'@{TARGET_SCREEN_NAME} has been suspended')
        return None

def start_twitter_stream():
    target_user_id = get_user_id(TARGET_SCREEN_NAME)
    if target_user_id is None: return
    stream = TweetListener(
        os.environ['TWITTER_CONSUMER_KEY'],
        os.environ['TWITTER_CONSUMER_SECRET'],
        os.environ['TWITTER_ACCESS_KEY'],
        os.environ['TWITTER_ACCESS_SECRET'])
    print(f'Started streaming from @{TARGET_SCREEN_NAME}')
    stream.filter(follow=[target_user_id])

References:

Upvotes: 1

Related Questions