how to listen for new tweets for an @mention using tweepy?

Viewed 1548

I am new to tweepy. And tried to implement an api which can listen the new tweets for a @mention or screen name.

tweets = api.user_timeline(screen_name=username)

But it is not listening the new tweets. Could you please help me to understand how it can be implemented so that whenever a tweet comes with '@mention'. the api should listen immediately

3 Answers

Creating a StreamListener

The on_data method of Tweepy’s StreamListener conveniently passes data from statuses to the on_status method. Create class MyStreamListener inheriting from StreamListener and overriding on_status.

import tweepy

override tweepy.StreamListener to add logic to on_status

class MyStreamListener(tweepy.StreamListener):

    def on_status(self, status):
        print(status.text)

Creating a Stream

Need an API to stream with the right credentials for authentications. Once we have an API and a status listener we can create our stream object.

myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth = api.auth, listener=myStreamListener)

start stream

myStream.filter(track=['python'])

myStream.filter(follow=["2211149702"])

Async stream

myStream.filter(track=['python'], is_async=True)

handling errors

class MyStreamListener(tweepy.StreamListener):

    def on_error(self, status_code):
        if status_code == 420:
            #returning False in on_error disconnects the stream
            return False

        # returning non-False reconnects the stream, with backoff.

Firstly, get their twitter user id using this.
Then, use this:

from tweepy import OAuthHandler
from tweepy import Stream
from tweepy import StreamListener

listener = StreamListener()
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=['1102105048253849600']) # user ID for random account
def on_data( self, status ):
    print("Entered on_data()")
    print(status.text, flush = True)
    return True
...
user = api.verify_credentials()
# this is just for getting user. without this also connection can be established
if user:
    print(user.id)
    print('started')
twitter_stream=Stream(auth,StdOutListener())
print('Stream created...')
twitter_stream.filter(follow=[user.id_str], is_async=True)
Related