我正在使用以下代码流式传输接收到的 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。