0

How can I test the Tweepy authentication using API v2?

My code below fails to post due to authentication however, is there any other way to test the authentication without invoking posting a Tweet (client.create_tweet) ?

import tweepy

bearer_token = "hidden"

consumer_key = "hidden"
consumer_secret = "hidden"

access_token = "hidden"
access_token_secret = "hidden"

client = tweepy.Client(bearer_token=bearer_token)

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

client.create_tweet(text="My first tweet")
wovano
  • 4,543
  • 5
  • 22
  • 49
Andre
  • 598
  • 1
  • 7
  • 18

2 Answers2

2

You can use any of the methods listed in the documentation here.

I would suggest you to use some read method like get_user:

user = client.get_user('twitter')
print(user.name)

About your authentication itself, the problem is that you have to choose between:

  • Using the bearer token of your application to get an OAuth 2 "App-Only" authentication. You will have, basically, the same possibilies as an unregistered user on the website.

  • Using an account's tokens to get an OAuth 1.0a "User Context" authentication. You will then be able to act in the behalf of the user who possesses the tokens that you are using.

But you are trying to do both successively.

Mickaël Martinez
  • 1,794
  • 2
  • 7
  • 20
  • Thanks! But it seems you have an error in the code. I fixed it by adding this: client.get_user(username='twitter') – Andre Sep 11 '22 at 09:49
  • Do I need API v2 "Elevated" access to run the code above? – Andre Sep 11 '22 at 09:55
  • @Andre It was indeed a typo, sorry! And you don’t need an Elevated access to run this code since it calls an endpoint from the V2 of the Twitter API. – Mickaël Martinez Sep 11 '22 at 13:44
0

I put the bearer token with the other parameters in tweepy.Client, it's not separated and works every time:

import tweepy

client = tweepy.Client(bearer_token="YOUR_BEARER_KEY",
                       consumer_key="YOUR_CONSUMER_KEY",
                       consumer_secret="YOUR_CONSUMER_SECRET",
                       access_token="YOUR_ACCESS_TOKEN",
                       access_token_secret="YOUR_ACCESS_TOKEN_SECRET")

You can also add wait_on_rate_limit=True to limit your rates in case your not handling them properly.

For a simple test similar to Mickaël's Answer which prints a twitter username to its respective id:

user_get = client.get_user(username='a_twitter_username_here')
user_id = user_get.data.id
print(user_id)

If this does not work then try regenerating your keys and tokens if you can. This method does not need elevated access.

bytro
  • 61
  • 6