我正在使用以下代码,有一段时间效果很好,但最近在 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 returned a 401 (Unauthorized), An error occurred processing your request.
这是堆栈跟踪
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 次尝试中,我实际上获得了用户的 friend 。
我在谷歌上搜索了一下并更正了机器上的时间(他们说这是导致此错误的最常见原因之一),但错误仍然存在。
还有一个最小的不工作的例子:
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 但仅此而已。
请您参考如下方法:
会不会是因为 user_id 有私有(private)资料而你不能访问它的 friend ?
我也认为,这是速率限制的问题,但根据 twitter api,如果达到限制,它会返回 429 错误
更新:
我没有测试过,但发现了类似的情况:https://dev.twitter.com/discussions/4389
