You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Tweepy调用Twitter OAuth 2.0 PKCE用户上下文API报错排查

问题描述

我尝试使用Tweepy调用Twitter API,编写了如下代码:

oauth2_user_handler = tweepy.OAuth2UserHandler(
    client_id=client_id,
    redirect_uri=redirect_uri,
    scope=scopes,
    client_secret=client_secret,
)

auth_url = oauth2_user_handler.get_authorization_url()

print('Please authorize this application: {}'.format(auth_url))

verifier = input('Enter the authorization response URL:')
token = oauth2_user_handler.fetch_token(verifier)
client = tweepy.Client(access_token=token['access_token'])
user = client.get_me(user_auth=False)

运行最后一行时出现错误:

Authenticating with OAuth 2.0 Application-Only is forbidden for this endpoint. Supported authentication types are [OAuth 1.0a User Context, OAuth 2.0 User Context]

我查阅资料显示当前代码应该是获取OAuth 2.0用户上下文访问令牌的方式,但错误提示我用的是应用-only认证,参考Stack Overflow相关回答也没解决,请问我遗漏了什么?

解决方案

问题出在get_me方法的user_auth参数设置上:

  • 你设置了user_auth=False,这个参数会强制Tweepy使用应用级别的认证(即OAuth 2.0 Application-Only),但你获取的是用户上下文令牌,两者冲突导致报错。
  • 只需将user_auth=False改为user_auth=True,或者直接删除该参数(因为它的默认值就是True),就能让Tweepy正确使用你拿到的OAuth 2.0用户上下文令牌调用接口。

修改后的最后一行代码示例:

user = client.get_me()
# 或者显式指定参数
user = client.get_me(user_auth=True)

额外提醒:确认你申请的scopes包含读取用户信息的权限(比如'users.read'),权限不足也可能引发类似的认证相关问题。

内容的提问来源于stack exchange,提问作者asafd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 03:59:53