我试图通过Python用Twitter API屏蔽一个用户账户,我的方法如下所示:
def block_user():
payload = {"target_user_id": "amazon"}
# Get request token
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)
# 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,
# I tried this, it didn't work
#oauth_callback='oob',
)
oauth_tokens = oauth.fetch_access_token(access_token_url)
access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_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/users/{}/blocking".format(id), json=payload
)
if response.status_code != 200:
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))
在终端中运行脚本时,我得到以下内容:
Got OAuth token: 9SL...BGo
Please go here and authorize: https://api.twitter.com/oauth/authorize?oauth_token=9SL...BGo
Paste the PIN here:
于是我进入URL,它要求我授权应用程序。我授权它,然后立即被重定向到Twitter API应用程序设置的重定向页面(在本例中为default.com)。我没有看到PIN码,也没有看到任何成功消息或任何东西,它只是立即重定向。使用传统搜索词找不到其他有这个问题的人。
有人有什么想法吗?
2条答案
按热度按时间bxjv4tth1#
我自己找到了答案,所以你需要在你的auth/request_token URL中添加以下URL参数,对我来说,这意味着修改这一行(代码块中的第三行):
改为:
我曾尝试在其他一些地方使用auth_callback = oob,包括我的OAuth1Session对象和身份验证URL。需要在request_token URL上。
oxcyiej72#
抱歉,我现在不能发表评论,所以我将在这里输入:
我真的推荐使用Twitter库:
Twitter python library