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

使用Tweepy调用Twitter API v2出现403 Forbidden错误求助

解决Twitter API v2 403 Forbidden(需关联Project的App密钥)问题

报错信息

raise Forbidden(response) tweepy.errors.Forbidden: 403 Forbidden 
When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

问题代码

import tweepy
import csv

#Autorización
bearer_token = ""
client = tweepy.Client(bearer_token=bearer_token)

#Get the user id
user=""
user_id= client.get_user(username=user).id

# Get all the tweets of a user 
paginator = tweepy.Paginator(
                                client.get_users_tweets,               # The method you want to use
                                user_id,                            # Some argument for this method
                                #end_time=datetime.datetime(2022, 3, 3, 19, 4, 49),
                                tweet_fields=["created_at", 
                                              "public_metrics",
                                              "possibly_sensitive",
                                              "attachments",
                                              "in_reply_to_user_id"],
                                max_results=100,                       # How many tweets per page
                                limit=40                                # How many pages to retrieve
                            )
data=[]
count=0

#Create a csv file to store the data
filename="@"+user+"_twitterdata.csv"
f = open(filename,'a', newline='')
writer = csv.writer(f)

#Store the data
for tweet in paginator.flatten(limit=40000): # Total number of tweets to retrieve
    count=count+1
    #Check if tha tweet has multimedia content
    if tweet.attachments!=None:media=True
    else:media=False
    #Check if tha tweet is a retweet
    Retweet=tweet.text[:2]=="RT"
    #Check if tha tweet is a repy
    Reply=tweet.in_reply_to_user_id!=None
    
    row=[tweet.id,
          tweet.created_at,
          tweet.public_metrics.get("retweet_count"),
          tweet.public_metrics.get("reply_count"),
          tweet.public_metrics.get("like_count"),
          tweet.public_metrics.get("quote_count"),
          tweet.public_metrics.get("impression_count"),
          tweet.possibly_sensitive,
          media, 
          #tweet.text.replace(",", "" ),
          Retweet,
          Reply
          #tweet.context_annotations
          ]
    writer.writerow(row)
    print("Retrieved ",count," tweets")

# Write the data and close file
writer = csv.writer(f)
f.close()

解决方案

核心问题排查

  • 确认App与Project的绑定关系
    登录Twitter开发者平台,进入你的App详情页,检查顶部是否显示所属Project。如果没有,需创建一个Project,然后将该App迁移至Project下(平台内有明确的迁移引导)。注意:Twitter API v2要求所有请求必须使用关联到Project的App的密钥,未绑定的旧App无法访问v2接口。

  • 验证Bearer Token的有效性
    确保代码中使用的bearer_token来自已绑定Project的App:进入该App的「Keys and Tokens」页面,重新生成Bearer Token并替换代码中的对应值,避免使用未绑定Project的旧Token。

  • 检查Project状态
    进入Project页面,确认Project信息完整(如使用场景描述),状态正常无限制。若Project存在信息缺失,补全后等待平台审核生效。

代码优化建议

  1. 添加异常处理
    获取用户ID时增加异常捕获,避免程序直接崩溃:

    try:
        user_id = client.get_user(username=user).id
    except tweepy.errors.TweepyException as e:
        print(f"获取用户ID失败: {e}")
        exit()
    
  2. 更可靠的Retweet判断逻辑
    替代基于文本前缀的判断,使用官方提供的referenced_tweets字段:

    Retweet = any(ref.type == 'retweeted' for ref in tweet.referenced_tweets) if tweet.referenced_tweets else False
    
  3. 安全的文件操作
    使用with语句自动管理文件资源,避免手动关闭文件时的潜在问题:

    filename = f"@{user}_twitterdata.csv"
    with open(filename, 'a', newline='') as f:
        writer = csv.writer(f)
        count = 0
        for tweet in paginator.flatten(limit=40000):
            count += 1
            # 原有数据处理逻辑
            writer.writerow(row)
            print(f"Retrieved {count} tweets")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 21:47:42