【问题标题】:Getting mentions and DMs through twitter stream API 1.1? (Using twython)通过 twitter 流 API 1.1 获得提及和 DM? (使用 twython)
【发布时间】:2013-06-19 02:47:12
【问题描述】:

我正在使用 twython(python 的 Twitter API 库)连接到流 API,但我似乎只获得了可能被单词过滤的公共 Twitter 流。有没有办法获取经过身份验证的用户时间线或@提及的实时流?

我一直在循环通过延迟调用 REST API 来获得这些提及,但 twitter 不喜欢我提出这么多请求。

Twython 文档对我没有多大帮助,官方 twitter 文档也没有。

如果有另一个 python 库可以比 twython 更好地用于流式传输(用于 Twitter API v1.1)。非常感谢您的建议...谢谢。

【问题讨论】:

    标签: python twitter streaming twython


    【解决方案1】:

    没有办法直接发送消息。

    但是,有一种方法可以流式传输用户时间线。在此处查看 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()
    

    requests (https://github.com/kennethreitz/requests) 的新版本发布之前,您的关注者的推文将落后一个帖子。不过,这应该会很快修复! :)

    【讨论】:

    【解决方案2】:

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

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

    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']
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-19
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 2013-06-14
      • 2019-05-04
      • 2015-06-12
      相关资源
      最近更新 更多