Home > Mobile >  Post tweets using tweepy and Twitter API V2
Post tweets using tweepy and Twitter API V2

Time:11-23

I need my Twitter app to tweet some information, but something is going wrong. First, I created an app and tried this code to test credentials:

auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET")
auth.set_access_token("ACCESS_TOKEN", "ACCESS_SECRET")
api = tweepy.API(auth)
try:
    api.verify_credentials()
    print("Authentication Successful")
except:
    print("Authentication Error")

And got "Authentication Error". Then I tried to write a tweet directly using

client = tweepy.Client(bearer_token, consumer_key, consumer_secret, access_token, access_token_secret)
client.create_tweet(text="********")

And now I got "tweepy.errors.Forbidden: 403 Forbidden" What should I do?

CodePudding user response:

It's impossible to determine what exactly is happening in the first instance, since you're suppressing the actual error and printing that on any exception. You'll need to provide the full traceback for anyone to know what's going on with it.

However, if you have Essential access to the Twitter API, you won't be able to use Twitter API v1.1, and you'll encounter a 403 Forbidden error. See the FAQ section about that in Tweepy's documentation for more information.

For the latter error, make sure your app has the write permission.
See the FAQ section about that in Tweepy's documentation for more information.

CodePudding user response:

Do you want to post a tweet via V2? here is the solution I just answered to myself!

Install tweepy, then do as I do to tweet "Yeah boy! I did it".

!pip3 install tweepy --upgrade # to install and upgrade tweepy if you didn't.

Then make your BEARER, CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, and ACCESS_SECRET ready. If you don't know how to find them you should check Developer Platform -> Developer Portal -> Projects & Apps -> click on your project -> then look for "Keys and tokens"

import tweepy

client = tweepy.Client(bearer_token=BEARER, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, access_token=ACCESS_KEY, access_token_secret=ACCESS_SECRET)

client.create_tweet(text="Yeah boy! I did it")

This worked for me 100% tested. I still don't know if I can quote or reply to a tweet with V2 or not.

  • Related