skip to Main Content

I’m building a Twitter bot using Tweepy. When I’m testing it, I try to Retweet a test mention that I did, but I get an unauthorized 401 error. When getting timeline informations or just printing the mention ID/content, everything is fine, but when I try to retweet it, it raises 401:

I also changed my app permissions to write and read the first time I got the error.

import tweepy

consumer_key = '##########'
consumer_secret = '#######'
acess_token = '##'
acess_token_secret = '#'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(acess_token, acess_token_secret)

api = tweepy.API(auth)

mentions = api.mentions_timeline()
for mention in mentions:
    api.retweet(mention.id)
Traceback (most recent call last):
  File "C:UsersLorenzodesktoptwitter-botopen-source-divulgator-botapp.py", line 15, in <module>
    api.retweet(mention.id)
  File "C:UsersLorenzoDesktoptwitter-botopen-source-divulgator-botvenvlibsite-packagestweepyapi.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:UsersLorenzoDesktoptwitter-botopen-source-divulgator-botvenvlibsite-packagestweepyapi.py", line 993, in retweet
    return self.request(
  File "C:UsersLorenzoDesktoptwitter-botopen-source-divulgator-botvenvlibsite-packagestweepyapi.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized

3

Answers


  1. Chosen as BEST ANSWER

    Doing what @Harmon758 said, I was able to run the code doing a simple regeneration on my credentials in the twitter developers site.


  2. Since this is a common question and the solution is usually to grant the write permission and regenerate and use new credentials, like in this case, I’ve added an FAQ to Tweepy’s documentation with a section answering this question.

    Login or Signup to reply.
  3. To expand on the answers above and provide additional guidance.

    Step 1 – First verify that you are using OAuthHandler and not AppAuthHandler.

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    

    Step 2 – Within Twitter’s Developer portal navigate to your project and verify that the App’s permissions are set to either Read and write or Read and write and Direct message as displayed in the image below.

    enter image description here

    Step 3 – You must regenerate new API Key and Secret and Access Token and Secret. Once the new keys are generated, make sure to update it either in your settings or code.

    enter image description here

    Additional References

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search