如何授权 Tweepy 在 Twitter 上 post?

How do I authorize Tweepy to post on Twitter?

我正在尝试创建 Twitter post,但我一直收到 tweepy.errors.Unauthorized: 401 Unauthorized。所以我决定使用 api.verify_credentials() 来检查我是否能够连接,瞧:Authentication Successful。但即便如此,post还是没有授权。

如何授权 Tweepy post 到 Twitter?

import tweepy


def main():
    consumer_key = '...'
    consumer_secret = '...'
    access_token = '...'
    access_token_secret = '...'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    api = tweepy.API(auth)

    try:
        api.verify_credentials()
        print("Authentication Successful")
    except:
        print("Authentication Error")

    status = "Another day, another cup of #coffee"

    api.update_status(status)


if __name__ == "__main__":
    main()

这就是我得到的:

Authentication Successful
Traceback (most recent call last):
  File "/Users/arnon/Downloads/mail_read/post_tweet.py", line 34, in <module>
    main()
  File "/Users/arnon/Downloads/mail_read/post_tweet.py", line 30, in main
    api.update_status(status)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 1121, in update_status
    return self.request(
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/tweepy/api.py", line 257, in request
    raise Unauthorized(resp)
tweepy.errors.Unauthorized: 401 Unauthorized

检查密钥和令牌,确保它们是正确的。根据https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401, HTTP 401 Unauthorized 客户端错误状态响应代码表示请求尚未应用,因为它缺少目标资源的有效身份验证凭据。

这也可能有帮助: https://docs.tweepy.org/en/stable/auth_tutorial.html#oauth-1a-authentication

在 Twitter 社区中找到:

When creating your application, do not click the “create your access token” until you first click on Settings and change the Application Type to “Read, Write and Access direct messages”. After your Twitter application has been updated to “Read, Write and Access direct messages”, click on the Home tab, and “create your access token”. This should do the trick =)

来源:https://twittercommunity.com/t/error-401-unauthorized/367/13

我遇到了同样的问题,这就是我设法解决它的方法: 问题可能是您的访问令牌没有所需的权限。

分步解决方案

  1. 转到https://developer.twitter.com/en/portal/projects-and-apps
  2. 转到所需应用的密钥和令牌选项卡
  3. 检查您的应用程序的权限,检查它在“访问令牌和机密”下面写的内容
  4. 如果它只有读取权限,请转到您应用的“设置”选项卡
  5. 单击以设置用户身份验证设置
  6. 启用“OAuth 1.0a”并将应用程序权限更改为“读写和直接消息”
  7. 重新生成令牌