Streaming Twitter direct messages

2019-02-06 08:26发布

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.

3条回答
三岁会撩人
2楼-- · 2019-02-06 09:08

Another solution is to not override the on_data method. That is how I got your code example to work in my case.

The on_data method of tweepy.streaming.StreamListener object contains all the json data handling and calling of other methods, like on_direct_message, that you and I were expecting.

查看更多
够拽才男人
3楼-- · 2019-02-06 09:14

Here is a working version of the code in 2017

    from twitter import *
import os

import  oauth

#Create a new Twitter app first: https://apps.twitter.com/app/new


APP_KEY,APP_SECRET = 'H3kQtN5PQgRiA0ocRCCjqjt2P', '51UaJFdEally81B7ZXjGHkDoDKTYy430yd1Cb0St5Hb1BVcDfE'
# OAUTH_TOKEN, OAUTH_TOKEN_SECRET = '149655407-TyUPMYjQ8VyLNY5p7jq0aMy8PjtFtd7zkIpDh3ZA', 'IUVpiDpoVmdO75UaHOTinAv5TOsAQmddttNENh9ofYuWO'


MY_TWITTER_CREDS = os.path.expanduser('my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
    oauth_dance("crypto sentiments", APP_KEY, APP_SECRET,
                MY_TWITTER_CREDS)

oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)

auth = OAuth(
    consumer_key=APP_KEY,
    consumer_secret=APP_SECRET,
    token=oauth_token,
    token_secret=oauth_secret
)

twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com')
for msg in twitter_userstream.user():
    if 'direct_message' in msg:
        print (msg['direct_message']['text'])
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-06 09:21

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.

查看更多
登录 后发表回答