流式传输Twitter直接消息

Anm*_*ggi 12 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 = ""
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()
Run Code Online (Sandbox Code Playgroud)

我可以打印我的名字以及"建立连接!" 信息.
但每当我从朋友的个人资料中向我自己的个人资料发送直接消息时,都不会调用任何方法.
虽然,每当我从我的个人资料中发推文时,它都会被程序正确打印.

我和我的朋友都在Twitter上互相关注,因此直接邮件权限应该没有任何问题.

这样做的正确方法是什么?

此外,如果它根本无法在Tweepy中完成,我准备使用任何其他Python库.

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

Anm*_*ggi 6

问题中提供的代码确实是正确的.
问题是我在将应用程序权限更改为" 读取,写入和指向消息 " 后忘记重新生成访问令牌和密钥.

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