通过twitter流API 1.1获得提及和DMs?(使用twython)

2024-10-01 13:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用twython(twitterapilibraryforpython)连接到流式API,但我似乎只得到了可能被单词过滤的公共twitter流。难道没有一种方法可以获得经过身份验证的用户时间轴或@notifications的实时流吗?在

我一直在通过对restapi的延迟调用来获得这些引用,但是twitter不喜欢我发出这么多请求。在

Twython文档对我没什么帮助,twitter官方文档也没有。在

如果有另一个python库可以比twython更好地用于流媒体(twitterapiv1.1)。我很感激你的建议。。。谢谢。在


Tags: 方法用户文档身份验证apirestapi官方流式
2条回答

没有办法流式传输直接消息。在

但是,有一种方法可以流式传输用户时间轴。查看Twitter上的文档:https://dev.twitter.com/docs/streaming-apis/streams/user

from twython import TwythonStreamer


class MyStreamer(TwythonStreamer):
    def on_success(self, data):
        if 'text' in data:
            print data['text'].encode('utf-8')
        # Want to disconnect after the first result?
        # self.disconnect()

    def on_error(self, status_code, data):
        print status_code, data

# Requires Authentication as of Twitter API v1.1
stream = MyStreamer(APP_KEY, APP_SECRET,
                    OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

stream.user()

但是,在requestshttps://github.com/kennethreitz/requests)的新版本发布之前,你的关注者的tweet将落后一个帖子。不过,这个问题应该很快就解决了!:)

在我的研究之初,我认为python-twitter是Python的twitter库。但最后,似乎Python Twitter Tools更受欢迎,而且还支持twitter流媒体。在

这有点棘手,流式API和restapi对于直接消息并不相等。这个小的示例脚本演示如何使用用户流获取直接消息:

import twitter # if this module does not 
               # contain OAuth or stream,
               # check if sixohsix' twitter
               # module is used! 
auth = twitter.OAuth(
    consumer_key='...',
    consumer_secret='...',
    token='...',
    token_secret='...'
)

stream = twitter.stream.TwitterStream(auth=auth, domain='userstream.twitter.com')

for msg in stream.user():
    if 'direct_message' in msg:
        print msg['direct_message']['text']

此脚本将打印所有新消息,而不是启动脚本之前已经收到的消息。在

相关问题 更多 >