Howard
Howard

Reputation: 135

How to Create Tweet with OAuth 2.0 (Twitter API v2) using tweepy

I try to create a tweet using tweepy under OAuth 2.0 instead of OAuth 1.0a. In other words, I am looking for an OAuth 2.0 equivalent of the following code.

import tweepy
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
client = tweepy.Client(
    consumer_key=consumer_key, consumer_secret=consumer_secret,
    access_token=access_token, access_token_secret=access_token_secret
)
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']}")

Following Twitter's guide on OAuth 2.0 Making requests on behalf of users and tweepy's guide on OAuth 2.0 Authorization Code Flow with PKCE (User Context), I am able to obtain an access token, which is passed instead of the Bearer Token.

import tweepy

client_id = ""
redirect_uri = ""
client_secret = ""

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("--> ")

access_token = oauth2_user_handler.fetch_token(
    authorization_response
)


client = tweepy.Client(access_token)

It seems that Twitter's implementation of OAuth 2.0 is in unfinished as of Dec '21. However, in Feb '21, the steps to post Tweets on behalf of users under OAuth 2.0 was described in another forum.

Upvotes: 3

Views: 4480

Answers (1)

Howard
Howard

Reputation: 135

A solution is found.

client = tweepy.Client(access_token["access_token"])


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']}")

Upvotes: 3

Related Questions