在尝试通过Twitter获取用户的朋友时,Twitter API返回了401(未经授权)

时间:2014-04-23 14:46:33

标签: python twitter oauth twitter-oauth

我使用下面的代码,有一段时间像魅力一样工作,但最近在10次尝试中的9次我从twitter api收到错误

from twython import Twython, TwythonError                                                                             
from pymongo import Connection                                                                                        
import pika, time                                                                                                     

connection = Connection("host")
connection.admin.authenticate('admin', 'passwords')
db = connection['tweets']

consumer_key="key"
consumer_secret="secret"

access_token="token"
access_token_secret="secret_token"

t = Twython(app_key=consumer_key,
            app_secret=consumer_secret,
            oauth_token=access_token,
            oauth_token_secret=access_token_secret 
           )

Q ='download_friends'

r_connection = pika.BlockingConnection(pika.ConnectionParameters(
               'host'))
channel = r_connection.channel()
channel.queue_declare(queue= Q, 
                arguments={'x-message-ttl':600000})   


while 1:
    method_frame, header_frame, id = channel.basic_get(Q)
    if db.friends.find_one({"_id": id}) != None:
        print "Panic, user already exists"
        continue
    try:
        r = t.get_friends_list(user_id = id)
    except Exception as ex:
        print ex, id
    else:
        print id
        r['_id'] = id
        r['time'] = time.time()
        db.friends.save(r)

    time.sleep(121)
  

Twitter API返回401(未授权),发生错误   处理您的请求。

这是一个堆栈跟踪

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/twython/endpoints.py", line 290, in get_friends_list
    return self.get('friends/list', params=params)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 230, in get
    return self.request(endpoint, params=params, version=version)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 224, in request
    content = self._request(url, method=method, params=params, api_call=url)
  File "/usr/local/lib/python2.7/dist-packages/twython/api.py", line 194, in _request
    retry_after=response.headers.get('retry-after'))
twython.exceptions.TwythonAuthError: Twitter API returned a 401 (Unauthorized), An error occurred processing your request.

我剩下的1次尝试实际上是在吸引用户的朋友。

我已经搜索了一下并纠正了机器上的时间(因为他们说这个错误的最常见原因之一),但错误仍然存​​在。

还有最小的不工作的例子:

twitter = Twython('API key', 'API secret', oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()

print ACCESS_TOKEN

t = Twython('API key', access_token=ACCESS_TOKEN)
r = t.get_friends_list(user_id = 'id')

能够获得ACCESS_TOKEN,但仅此而已。

1 个答案:

答案 0 :(得分:2)

可能是,因为user_id有私人资料而你无法访问它的朋友?

我也想过,它在速率限制方面存在问题,但根据twitter api,它会返回429错误,如果达到限制

更新:

我没有经过测试,但发现了类似的情况:https://dev.twitter.com/discussions/4389