【问题标题】:How to Create Tweet with OAuth 2.0 (Twitter API v2) using tweepy如何使用 tweepy 使用 OAuth 2.0 (Twitter API v2) 创建推文
【发布时间】:2022-02-07 12:03:00
【问题描述】:

我尝试在 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']}")

按照OAuth 2.0 Making requests on behalf of users 上的 Twitter 指南和OAuth 2.0 Authorization Code Flow with PKCE (User Context) 上的 tweepy 指南,我能够获得一个访问令牌,它被传递而不是承载令牌。

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)

截至 21 年 12 月,Twitter's implementation of OAuth 2.0 is in unfinished 似乎。然而,在 21 年 2 月,the steps to post Tweets on behalf of users under OAuth 2.0 在另一个论坛中被描述。

【问题讨论】:

  • 谢谢你,@AndrewRyan。第二个链接使用 OAuth 1.0a。第一个链接是问题的早期阶段,OP 第一次遇到无法创建推文(只读)。如果 OP 选择使用 OAuth 1.0a,他们可以使用第二个链接中的解决方案。如果 OP 选择使用 OAuth 2.0,他们可能会遇到我面临的问题。

标签: python twitter tweepy


【解决方案1】:

找到了解决方案。

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

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2022-01-04
    • 2021-12-31
    • 2022-12-10
    • 2016-06-29
    • 1970-01-01
    • 2022-11-10
    • 2022-12-07
    • 2013-06-15
    相关资源
    最近更新 更多