【发布时间】:2021-12-30 15:51:51
【问题描述】:
我正在尝试制作一个发布推文的机器人。
由于我的开发人员帐户只是必不可少的,因此我仅限于 V2 API。起初,这是我用于发布推文的 github 示例:https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.py
consumer_key = "somekey"
consumer_secret = "somesecret"
payload = {"text": "Hello world!"}
request_token_url = "https://api.twitter.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
try:
fetch_response = oauth.fetch_request_token(request_token_url)
except ValueError:
print(
"There may have been an issue with the consumer_key or consumer_secret you entered."
)
resource_owner_key = fetch_response.get("oauth_token")
resource_owner_secret = fetch_response.get("oauth_token_secret")
print("Got OAuth token: %s" % resource_owner_key)
print("Got OAuth token secret: %s" % resource_owner_secret)
# Get authorization
base_authorization_url = "https://api.twitter.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier,
)
oauth_tokens = oauth.fetch_access_token(access_token_url)
access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_token_secret"]
print("Got OAuth token: %s" % access_token)
print("Got OAuth token: %s" % access_token_secret)
# Make the request
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=access_token,
resource_owner_secret=access_token_secret,
)
# Making the request
response = oauth.post(
"https://api.twitter.com/2/tweets",
json=payload,
)
if response.status_code != 201:
raise Exception(
"Request returned an error: {} {}".format(response.status_code, response.text)
)
print("Response code: {}".format(response.status_code))
# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
用户流程如下。看来必须使用 OAuth,因此,您必须获取一个 6 位数字并在终端中输入以获取访问令牌:
Got OAuth token: #######
Got OAuth token secret: #######
Please go here and authorize: https://api.twitter.com/oauth/authorize?oauth_token=####
Paste the PIN here: ######
Got OAuth token: ########################################
Got OAuth token: ###############################
这一切都在工作到最后一步:实际使用 JSON 发布推文。在那里,我收到以下错误:
Request returned an error: 403 {"title":"Forbidden","detail":"Forbidden","type":"about:blank","status":403}
我能做什么?我只是想使用 Twitter V2 API 发布一条推文,仅此而已。大多数教程使用旧的 V1 或 V1.1 api,这没有帮助。
编辑:似乎必须对身份验证进行只读操作:Twitter new API Essential access
【问题讨论】:
-
正如有人在这里写的,V2 权限似乎是只读的。这很奇怪:stackoverflow.com/questions/70482492/…
-
如果你想保持简单,我会使用 Tweepy Python 库
标签: python api twitter twitter-oauth tweets