tweepy.errors.Forbidden: 403 禁止在 Tweepy 中使用 Twitter API v2 功能?

tweepy.errors.Forbidden: 403 Forbidden using Twitter API v2 functions in Tweepy?

我刚开始使用 Tweepy,在尝试使用 v2 API 函数编写程序以发送推文时遇到了麻烦。目前,我反复收到此错误:

Traceback (most recent call last):
  File "C:\Users\xxxxxxxx\PycharmProjects\Twitter Bot\Twitter Bot.py", line 12, in <module>
    response = client.create_tweet(text='Hello!')
  File "C:\Users\xxxxxxxx\PycharmProjects\Twitter Bot\venv\lib\site-packages\tweepy\client.py", line 594, in create_tweet
    return self._make_request(
  File "C:\Users\xxxxxxxx\PycharmProjects\Twitter Bot\venv\lib\site-packages\tweepy\client.py", line 118, in _make_request
    response = self.request(method, route, params=request_params,
  File "C:\Users\xxxxxxxx\PycharmProjects\Twitter Bot\venv\lib\site-packages\tweepy\client.py", line 92, in request
    raise Forbidden(response)
tweepy.errors.Forbidden: 403 Forbidden

这是我当前的代码:

import tweepy
import config

client = tweepy.Client(
    consumer_key=config.api_key,
    consumer_secret=config.api_secret,
    access_token=config.access_token,
    access_token_secret=config.access_secret
)

response = client.create_tweet(text='Hello!')

print(response)

我已经尝试重新生成我的令牌和密钥几次,结果相似。我也曾尝试在线搜索遇到此错误的其他用户,但除了其他人错误使用 v1 函数外,没有找到任何其他用户。

有什么办法可以解决这个错误吗?

您很可能需要授予您的应用写入权限:

Why am I encountering a 401 Unauthorized error with API or 403 Forbidden error with Client?

If you’re using a method that performs an action on behalf of the authenticating user, e.g. API.update_status(), make sure your app has the write permission.

After giving it the write permission, make sure to regenerate and use new credentials to utilize it.

See Twitter’s API documentation on app permissions for more information.

https://tweepy.readthedocs.io/en/v4.6.0/faq.html#why-am-i-encountering-a-401-unauthorized-error-with-api-or-403-forbidden-error-with-client

通过包含 user_auth=True 参数向您的应用程序添加权限,使其看起来像这样:

import tweepy
import config

client = tweepy.Client(
    consumer_key=config.api_key,
    consumer_secret=config.api_secret,
    access_token=config.access_token,
    access_token_secret=config.access_secret,
    user_auth=True
)

response = client.create_tweet(text='Hello!')

print(response)