Search code examples
pythontwittertweepytwitter-streaming-api

Streaming Twitter direct messages


I am using the following code to stream direct messages received by my Twitter account -:

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy import API

from tweepy.streaming import StreamListener

# These values are appropriately filled in the code
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

class StdOutListener( StreamListener ):

    def __init__( self ):
        self.tweetCount = 0

    def on_connect( self ):
        print("Connection established!!")

    def on_disconnect( self, notice ):
        print("Connection lost!! : ", notice)

    def on_data( self, status ):
        print("Entered on_data()")
        print(status, flush = True)
        return True

    def on_direct_message( self, status ):
        print("Entered on_direct_message()")
        try:
            print(status, flush = True)
            return True
        except BaseException as e:
            print("Failed on_direct_message()", str(e))

    def on_error( self, status ):
        print(status)

def main():

    try:
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.secure = True
        auth.set_access_token(access_token, access_token_secret)

        api = API(auth)

        # If the authentication was successful, you should
        # see the name of the account print out
        print(api.me().name)

        stream = Stream(auth, StdOutListener())

        stream.userstream()

    except BaseException as e:
        print("Error in main()", e)

if __name__ == '__main__':
    main()

I am able to get my name printed as well as the "Connection established!" message.
But whenever I send a direct message to my own profile from my friend's profile, no method is called.
Although, whenever I tweet something from my profile, it is printed correctly by the program.

Me and my friend both follow each other on Twitter, so there shouldn't be any problems with the direct message permissions.

What is the proper way to do it ?

Also, if it cannot be done in Tweepy at all, I am ready to use any other Python library.

I am using Tweepy 3.3.0 and Python 3.4 on Windows 7.


Solution

  • The code provided in the question is indeed correct.
    The problem was that I had forgotten to regenerate the access token and secret after changing my application permissions to "Read, write and direct messages".

    Note: The direct messages arrive in the on_data() method rather than the on_direct_message() method.