Search code examples
pythontwittertweepy

on_direct_message is not listening the direct message streaming using tweepy


The on_direct_message never called when a message arrives. i have used python3.7 and latest tweepy library. i n twitter account it works fine but not working with the code snippet am using. But the code snippet is working well to listen tweets.

twitter_stream=Stream(auth,StdOutListener())
print('Stream created...')
twitter_stream.filter(follow=[user.id_str], is_async=True)

NB:Permission taken for read, write and direct message. And all access parameters are correct

The StdOutListener is:

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)

Solution

  • Direct Messages are not supported in the Twitter streaming API (they were a part of the User Streams API, which was removed in 2018 and replaced with the Account Activity API).

    To receive Direct Messages in realtime, you will need to implement a webhook handler for the Account Activity API. You could try the twitivity library, or look at this Python sample app. Tweepy does not have built-in support for this API.