将Python和OAuth2与Twitter流API一起使用

时间:2013-06-26 12:17:44

标签: python twitter twitter-oauth

Twitter v1 API现已不存在,所以我一直在尝试使用搜索和流媒体API来整理主题标签信息。 Search API是速率限制的,因此如果主题标签上有很多条目,您可能会错过一些。流媒体似乎是要走的路。

这里使用OAuth2是我的(匿名)代码:

import oauth2 as oauth
import json

consumer_key = "<consumer key from twitter developer site>"
consumer_secret = "<consumer secret>"
oauth_token = "<access token>"
oauth_token_secret = "<access token secret>"
consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
access_token = oauth.Token(key=oauth_token, secret=oauth_token_secret)
client = oauth.Client(consumer, access_token)

terms = json.dumps({'track' : 'twitter'})
stream_endpoint = "https://stream.twitter.com/1.1/statuses/filter.json"
response, data = client.request(stream_endpoint,"POST", body=terms, headers={'Content-Type':'application/json'})

我遇到的问题是这总是会返回以下消息:

>>>'No filter parameters found. Expect at least one parameter: follow track locations\r\n'

2 个答案:

答案 0 :(得分:0)

我认为您的错误是因为使用

上的JSON数据
terms = json.dumps({'track' : 'twitter'})

您应该像这样编写代码

terms = 'track=twitter'

答案 1 :(得分:0)

    USER = request.params.get('username', '00000')
    LIMIT = request.params.get('limit', '50')
    REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token'
    consumer_key    ='424245wfdsfa4'    
    consumer_secret ='afar234252523adsasd'

    if consumer_key is None or consumer_secret is None:
        print 'you need consumer_key & consumer_secret key'
        sys.exit(1)

    signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
    oauth_consumer             = oauth.Consumer(key=consumer_key, secret=consumer_secret)
    oauth_client               = oauth.Client(oauth_consumer)


    response, content = oauth_client.request(REQUEST_TOKEN_URL, 'POST')

    if response['status'] == '200':
        request_token = dict(parse_qsl(content))
    else:
        print 'Invalid response from Twitter requesting  token.........: %s' % response['status']

    endpoint = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' + USER + '&count=' + LIMIT
    response, content = oauth_client.request(endpoint, 'GET')
    url = response['content-location']
    f = urllib2.urlopen(url)
    response = f.read()
    return simplejson.loads(response)