Hello,
I’ve been trying to implement the Oauth 2 workflow to my twitter bot script in python using the tweepy library and then tweet something. I’m not quite sure what I’m doing wrong but I keep getting a tweepy.errors.Unauthorized: 401 error when I try to tweet something via the Client object as you can see on the screenshot.
. My code is pasted below. Some help would be greatly appreciated!
import os
import tweepy
# define twitter app credentials
client_id = 'xxxx'
client_secret = 'xxxx'
consumer_key = 'xxxx'
consumer_secret = 'xxxx'
callback_uri = 'xxxx'
# This allows us to use a plain HTTP callback
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
# step 1 authenticate app
oauth2_user_handler = tweepy.OAuth2UserHandler(client_id=client_id,
redirect_uri=callback_uri,
scope=['tweet.read', 'tweet.write', 'users.read'])
print(oauth2_user_handler.get_authorization_url())
authorization_response = input('Paste redirect url here: ')
# fetch access token
access_token = oauth2_user_handler.fetch_token(authorization_response)
# initialize client with consumer and access tokens
client = tweepy.Client(consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token["access_token"])
# create tweet
response = client.create_tweet(text="This Tweet was Tweeted using Tweepy and Twitter API v2!")
print(f"https://twitter.com/user/status/{response.data['id']}")
Hi,
It’s taken me days to figure out how to use tweepy and OAuth2 but your post really helped. You solved my problem with client = tweepy.Client(access_token["access_token"]) so I hope this will solve yours!
For me, I had to add client_secret to the OAuth2UserHandler and add user_auth=False to the create_tweet part. user_auth=False means that it uses OAuth1.0a, not 2.0 (it made me take out the tweepy link to post but you can look in the Client.create_tweet documentation for tweepy).
Also, I had to add “Read and Write” permissions for OAuth1 even though I’m not using OAuth1.
In the below edit the keys are in a separate hidtet library. Consumer keys aren’t used.
import hidtet
import tweepy
# define twitter app credentials
client_id = hidtet.client_id
client_secret = hidtet.client_secret
#consumer_key = hidtet.consumer_key
#consumer_secret = hidtet.consumer_secret
redirect_uri = hidtet.redirect_uri
# step 1 authenticate app
oauth2_user_handler = tweepy.OAuth2UserHandler(client_id=client_id,
redirect_uri=redirect_uri,
scope=['tweet.read', 'tweet.write', 'users.read'])
client_secret=client_secret)
print(oauth2_user_handler.get_authorization_url())
authorization_response = input('Paste redirect url here: ')
# fetch access token
access_token = oauth2_user_handler.fetch_token(authorization_response)
# initialize client with consumer and access tokens
client = tweepy.Client(access_token["access_token"])
# create tweet
response = client.create_tweet(text="This Tweet was Tweeted using Tweepy and Twitter API v2!",user_auth=False)
print(f"https://twitter.com/user/status/{response.data['id']}")
1 Like