0

So, I was making a twitterbot, for that I was using tweepy library using python. For that I added credentials like the access toke etc but. get the error 401 unauthorized from tweepy library.

I've added the code below:

import tweepy

TWITTER_API_KEY = "xxxxx"
TWITTER_API_SECRET = "xxxxx"
TWITTER_ACCESS_TOKEN = "xxxxx"
TWITTER_ACCESS_TOKEN_SECRET = "xxxxx"

consumer_key = TWITTER_API_KEY
consumer_secret_key = TWITTER_API_SECRET
access_token = TWITTER_ACCESS_TOKEN
access_token_secret = TWITTER_ACCESS_TOKEN_SECRET

auth = tweepy.OAuthHandler(consumer_key, consumer_secret_key)
auth.set_access_token(access_token, access_token_secret)
stream = tweepy.Stream(auth, tweepy.StreamListener)
api = tweepy.API(auth)

api.update_status("Hello World!")

Error is as given below:

Traceback (most recent call last):
  File "c:\Users\New\ThoughtfulGPT\main.py", line 50, in <module>
    tweets = client.get_users_mentions(id = 1683711485820936192)
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 1369, in get_users_mentions
    return self._make_request(
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 129, in _make_request
    response = self.request(method, route, params=request_params,
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 98, in request
    raise Unauthorized(response)
tweepy.errors.Unauthorized: 401 Unauthorized
Unauthorized

Note that I have wrote only about the authentification part and not the full code

I was trying to get the program to tweet the "Hello World" But I got an error 401 from tweepy library

  • Check your API keys, error while copy pasting, extra spaces, etc. Check if these API keys have enough permissions to tweet. Check these and reset the tokens and regenerate if none works. It seems like your code is correct. – Satyajit Jul 26 '23 at 07:55

1 Answers1

0

After recent updates of the twitter APIs, tweet creation is possible only with the newest API v2, which is called through tweepy's Client class and create_tweet method.

You can try replacing the corresponding lines in your code with:

apiv2 = tweepy.Client(
    consumer_key=consumer_key, 
    consumer_secret=consumer_secret, 
    access_token=access_token, 
    access_token_secret=access_token_secret,
)

apiv2.create_tweet(text="Hello World!", user_auth=True)

See this answer.

If you still have an 401 unauthorized error, check also on the Twitter Developer platform that your project has API v2 access with read/write permissions.

tvoirand
  • 347
  • 1
  • 3
  • 12