import tweepy
import os
api_key = os.getenv('TWI_API_KEY')
api_key_secret = os.getenv('TWI_API_KEY_SECRET')
bearer_token = os.getenv('TWI_BEARER_TOKEN')
access_token = os.getenv('TWI_ACCESS_TOKEN')
access_token_secret = os.getenv('TWI_ACCESS_TOKEN_SECRET')
client = tweepy.Client(bearer_token=bearer_token,
consumer_key=api_key,
consumer_secret=api_key_secret,
access_token=access_token,
access_token_secret=access_token_secret)
user_get = client.get_user(username='twitterusers')
user_id = user_get.data.id
print(user_id)
Above, is the code I’ve written so far in my attempt to create a Twitter bot that replies to a specific user’s most recent tweet, however I did not make it far as I receive the following error when attempting to use the Client.get_user() method to retrieve a user’s Twitter ID:
tweepy.errors.Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.
I went into the Twitter developer portal –> user authentication settings, and I made sure that the app permissions were set to ‘Read and write’.
I then tried regenerating all of my keys and tokens and made sure that there was no issue with the validity of the credentials themselves.
I further confirmed it’s not an issue with the keys or tokens when I found I was able to successfully tweet without receiving any errors using the following code.
import tweepy
import os
api_key = os.getenv('TWI_API_KEY')
api_key_secret = os.getenv('TWI_API_KEY_SECRET')
bearer_token = os.getenv('TWI_BEARER_TOKEN')
access_token = os.getenv('TWI_ACCESS_TOKEN')
access_token_secret = os.getenv('TWI_ACCESS_TOKEN_SECRET')
client = tweepy.Client(bearer_token=bearer_token,
consumer_key=api_key,
consumer_secret=api_key_secret,
access_token=access_token,
access_token_secret=access_token_secret)
response = client.create_tweet(text='Testing!')
print(response)
I tried changing the credentials passed to tweepy.Client(), first using the bearer_token only. Passing the bearer_token exclusively, as I have seen done in some examples, I received the same 403 Error as mentioned above.
Then I tried passing the consumer_key, consumer_secret, access_token, access_token_secret.
In this case, I receive the following 401 error:
tweepy.errors.Unauthorized: 401 Unauthorized
Unauthorized
In either case, I am unable to utilize Client.get_user()
2
Answers
The error is because of twitter policy change where in the free tier, there is no way for us to pull tweets, we can only do that if we have a basic subscription which is 100$ per month now.
Details can be found here: https://developer.twitter.com/en/products/twitter-api
According to twitter’s developer platform, the free API is:
Meaning you can only tweet. Actions like retrieving data from tweets, and interacting in any way with users (messages, likes, reposts etc) are only supported in the paid plans