geduldig / TwitterAPI

Minimal python wrapper for Twitter's REST and Streaming APIs
936 stars 263 forks source link

Ways to check response status code when using TwitterPager #192

Closed 742617000027 closed 3 years ago

742617000027 commented 3 years ago

Hi! There doesn't seem to be a way to check the status code of a response when using TwitterPager, as far as I can see. I ran into this issue when requesting followers/ids of a user I was blocked by. As it seems, the only way around this for now would be to use try ... except, since the cursor attribute doesn't seem to be provided in responses made without TwitterPager. Am I missing something? Cheers!

>>> r = TwitterPager(api, 'followers/ids', {'user_id': USER_ID, 'count': 5000})
>>> next(r.get_iterator())

Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/TwitterAPI/TwitterPager.py", line 54, in get_iterator
    it = r.get_iterator()
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/TwitterAPI/TwitterAPI.py", line 269, in get_iterator
    raise TwitterRequestError(self.response.status_code, msg=self.response.text)
TwitterAPI.TwitterError.TwitterRequestError: ('{"request":"\\/1.1\\/followers\\/ids.json","error":"Not authorized."}',) (401): {"request":"\/1.1\/followers\/ids.json","error":"Not authorized."}
geduldig commented 3 years ago

That's right. You should catch both TwitterRequestError and TwitterConnectionError. You can also check for messages. Something like this...


try
  r = TwitterPager(api, 'search/tweets', {'q':'pizza', 'count':100})
  for item in r.get_iterator():
      if 'text' in item:
          print item['text']
      elif 'message' in item and item['code'] == 88:
          print 'SUSPEND, RATE LIMIT EXCEEDED: %s\n' % item['message']
          break
except TwitterRequestError as e:
  print(e.status_code)
  for msg in iter(e):
    print(msg)
except TwitterConnectionError as e:
  print(e)