Python 推特直接消息流

Python 推特直接消息流,python,twitter,tweepy,twitter-streaming-api,Python,Twitter,Tweepy,Twitter Streaming Api,我正在使用以下代码来流式传输我的Twitter帐户收到的直接消息-: 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 =

我正在使用以下代码来流式传输我的Twitter帐户收到的直接消息-:

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()
我可以打印我的姓名以及“已建立连接!”消息。
但每当我从朋友的个人资料向自己的个人资料发送直接消息时,都不会调用任何方法。
尽管如此,无论何时我从我的个人资料中发布一些东西,程序都会正确地打印出来

我和我的朋友都在Twitter上互相关注,所以直接消息权限应该不会有任何问题

正确的方法是什么

此外,如果它不能在Tweepy中完成,我准备使用任何其他Python库


我正在Windows 7上使用Tweepy 3.3.0和Python 3.4。

问题中提供的代码确实正确。
问题是,在将应用程序权限更改为“读、写和直接消息”后,我忘记了重新生成访问令牌和密码


注意:直接消息到达
on_data()
方法,而不是
on_direct_message()
方法。

另一个解决方案是不覆盖on_data方法。这就是我如何让您的代码示例在我的案例中工作的原因


tweepy.streaming.StreamListener对象的on_data方法包含您和我期望的所有json数据处理和其他方法调用,如on_direct_message

以下是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'])