如何使用Tweepy获取用户最新推文ID?遇API权限错误求助
如何使用Tweepy获取用户最新推文ID
问题原因
你遇到的错误核心是:当前的Essential访问权限仅支持Twitter API v2接口,而你代码里用的tweepy.API是调用v1.1的user_timeline接口,这个接口需要Elevated权限才能访问。无需申请更高权限,直接切换到v2接口即可解决。
解决方案
改用Tweepy的Client类(对应API v2)实现,代码示例如下:
import tweepy import config # 初始化API v2客户端 client = tweepy.Client( bearer_token=config.BEARER_TOKEN, consumer_key=config.APP_KEY, consumer_secret=config.APP_SECRET, access_token=config.OAUTH_TOKEN, access_token_secret=config.OAUTH_TOKEN_SECRET ) # 验证连接并获取当前用户信息 user_info = client.get_me() print(f'Connected as @{user_info.data.screen_name}, ready to operate!') # 获取最新1条推文 tweets_response = client.get_users_tweets( id=user_info.data.id, max_results=1, tweet_fields=['id'] ) # 提取并打印最新推文ID if tweets_response.data: latest_tweet_id = tweets_response.data[0].id print(latest_tweet_id) else: print('该用户暂无发布推文')
关键说明
- 使用API v2需要在开发者后台获取Bearer Token,并添加到你的配置文件中
get_users_tweets是v2版本中替代v1.1user_timeline的接口- 通过
tweet_fields参数可以指定仅返回需要的字段(这里只请求id),减少返回数据量
内容的提问来源于stack exchange,提问作者Supun Maduranga
相关产品推荐
相关产品推荐

