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

使用Tweepy开发Twitter机器人遭遇401 Unauthorized授权错误求助

解决Tweepy调用Twitter API返回401 Unauthorized错误

问题场景

使用Python的Tweepy库开发Twitter机器人,已配置TWITTER_API_KEY、TWITTER_API_SECRET、TWITTER_ACCESS_TOKEN、TWITTER_ACCESS_TOKEN_SECRET等授权凭证,调用api.update_status("Hello World!")尝试发布推文时触发401 Unauthorized错误。

相关代码

import tweepy

TWITTER_API_KEY = "xxxxx"
TWITTER_API_SECRET = "xxxxx"
TWITTER_ACCESS_TOKEN = "xxxxx"
TWITTER_ACCESS_TOKEN_SECRET = "xxxxx"

consumer_key = TWITTER_API_KEY
consumer_secret_key = TWITTER_API_SECRET
access_token = TWITTER_ACCESS_TOKEN
access_token_secret = TWITTER_ACCESS_TOKEN_SECRET

auth = tweepy.OAuthHandler(consumer_key, consumer_secret_key)
auth.set_access_token(access_token, access_token_secret)
stream = tweepy.Stream(auth, tweepy.StreamListener)
api = tweepy.API(auth)

api.update_status("Hello World!")

报错信息

Traceback (most recent call last):
  File "c:\Users\New\ThoughtfulGPT\main.py", line 50, in <module>
    tweets = client.get_users_mentions(id = 1683711485820936192)
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 1369, in get_users_mentions
    return self._make_request(
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 129, in _make_request
    response = self.request(method, route, params=request_params,
  File "C:\Users\New\AppData\Local\Programs\Python\Python39\lib\site-packages\tweepy\client.py", line 98, in request
    raise Unauthorized(response)
tweepy.errors.Unauthorized: 401 Unauthorized
Unauthorized

解决方案

  • 验证凭证准确性
    核对TWITTER_API_KEY、TWITTER_API_SECRET、TWITTER_ACCESS_TOKEN、TWITTER_ACCESS_TOKEN_SECRET是否完全匹配Twitter开发者平台上的凭证,注意不要包含多余空格、大小写错误,且这些凭证需属于当前使用的开发者账号。

  • 确认API权限配置
    登录Twitter开发者平台,检查对应项目的权限设置:需确保账号拥有读/写权限(默认可能为只读),且已启用必要的API端点(比如v1.1的statuses/update)。

  • 区分Tweepy的API版本
    报错中出现client.get_users_mentions,说明代码可能混用了Tweepy的v1.1 API(tweepy.API)和v2 API(tweepy.Client)。两者认证方式不同:

    • v1.1 API使用OAuth 1.0a凭证(即你配置的四个密钥)
    • v2 API需要Bearer Token,若同时使用两者需分别配置对应认证信息。
  • 移除冗余代码
    代码中初始化的tweepy.Stream未实际使用,虽不直接导致认证错误,但建议移除避免潜在干扰。

  • 修正后的示例代码

import tweepy

# 替换为你的有效凭证
TWITTER_API_KEY = "你的API_KEY"
TWITTER_API_SECRET = "你的API_SECRET"
TWITTER_ACCESS_TOKEN = "你的ACCESS_TOKEN"
TWITTER_ACCESS_TOKEN_SECRET = "你的ACCESS_TOKEN_SECRET"

# 初始化v1.1 API认证
auth = tweepy.OAuthHandler(TWITTER_API_KEY, TWITTER_API_SECRET)
auth.set_access_token(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)

api = tweepy.API(auth)

# 尝试发布推文并捕获异常
try:
    status = api.update_status("Hello World!")
    print(f"推文发布成功,ID: {status.id}")
except tweepy.errors.Unauthorized:
    print("认证失败,请检查凭证和权限")
except Exception as e:
    print(f"发布失败: {str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:53:11