如何使用 tweepy 使用 OAuth 2.0 (Twitter API v2) 创建推文

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

我尝试在 OAuth 2.0 而不是 OAuth 1.0a 下使用 tweepy 创建推文。换句话说,我正在寻找与以下代码等效的 OAuth 2.0。

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

按照 Twitter 在 OAuth 2.0 Making requests on behalf of users and tweepy's guide on OAuth 2.0 Authorization Code Flow with PKCE (User Context) 上的指南,我能够获得一个访问令牌,而不是 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)

似乎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在另一个论坛上有描述。

找到解决方案。

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