在尝试获取Twitter用户好友时,Twitter API返回401(未授权)

2 投票
1 回答
3807 浏览
提问于 2025-04-18 03:56

我正在使用以下代码,之前运行得很好,但最近在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 个回答

3

是不是因为用户的个人资料是私密的,所以你无法访问他们的好友呢?

我也曾想过可能是因为请求次数限制的问题,但根据Twitter的API,如果超过限制,它会返回429错误。

更新:

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

撰写回答