Search code examples
pythontwittertweepy

401 Unauthorized error when posting tweets using Tweepy


I am using tweepy to post tweets including media, for a bot project. Since mid-june the bot has stopped working, and I realized it’s due to an update of the twitter APIs.

I upgraded tweepy in my conda environment to version 4.14.0. I updated my script to used API v1.1 to upload media, and API v2 to post the tweet. I regenerated the consumer key, consumer secret, access token and access token secret.

I am getting a 401 Unauthorized error when trying to post the tweet with API v2. The credentials are correct since API v1.1 succeeds in uploading the media pior to tweet posting.

My app is registered under a project and has read and write permissions.

I search the twitter developer forum, found some similar errors but no solution. I posted a message there but didn't get any answer.

Here is my python code:

"""Script to test tweet posting of s2coastalbot.
"""

# third party imports
import tweepy

# authenticate twitter account
consumer_key = "XXX"
consumer_secret = "XXX"
access_token = "XXX"
access_token_secret = "XXX"
auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
apiv1 = tweepy.API(auth)
apiv2 = tweepy.Client(consumer_key, consumer_secret, access_token, access_token_secret)

# post tweet
file_path = "media.png"
media = apiv1.media_upload(filename=file_path)
apiv2.create_tweet(text="test", media_ids=[media.media_id], user_auth=True) # returns: "tweepy.errors.Unauthorized: 401 Unauthorized"


Solution

  • I was passing the wrong arguments to Client(). Without using a bearer_token, I needed to pass my credentials using keyword arguments. The following syntax works:

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