调用Twitter API的mentions_timeline接口报错453求助(已购Basic版)
解决Twitter API 453权限错误:实现提及回复功能
你遇到的453错误是因为api.mentions_timeline()属于Twitter API v1.1的statuses/mentions_timeline接口,而Basic访问层级不开放这个v1.1接口,仅支持大部分v2接口及少数受限v1.1接口。以下是基于Tweepy使用API v2实现提及回复的解决方案:
核心修改:切换到Twitter API v2
Tweepy提供了Client类来对接v2接口,Basic版完全支持v2的提及获取和推文回复接口。
完整示例代码
import tweepy # 替换为你的API密钥和令牌 API_KEY = "MY_API_KEY" API_SECRET_KEY = "MY_API_SECRET_KEY" ACCESS_TOKEN = "MY_ACCESS_TOKEN" ACCESS_TOKEN_SECRET = "MY_ACCESS_TOKEN_SECRET" # 初始化v2客户端 client = tweepy.Client( consumer_key=API_KEY, consumer_secret=API_SECRET_KEY, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET ) # 获取当前账号ID current_user_id = client.get_me().data.id # 获取最近的提及(默认返回100条,可通过max_results调整) mentions = client.get_users_mentions(id=current_user_id) # 遍历提及并回复 if mentions.data: for mention in mentions.data: print(f"{mention.id} - {mention.text}") # 回复提及,必须包含原作者@用户名 response = client.create_tweet( text=f"@{mention.author_id} 你好!已收到你的提及", in_reply_to_tweet_id=mention.id ) print(f"已回复推文ID: {response.data.id}") else: print("暂无提及内容")
关键补充说明
- 权限配置:确保你的开发者项目已激活Basic访问层级,且API密钥拥有
Read and Write权限(在开发者平台的项目设置中调整) - 分页处理:如果提及超过100条,需要通过分页令牌获取更多内容:
pagination_token = None while True: mentions = client.get_users_mentions( id=current_user_id, max_results=100, pagination_token=pagination_token ) if not mentions.data: break # 处理当前页提及逻辑... pagination_token = mentions.meta.get('next_token') if not pagination_token: break - 回复规则:回复内容必须包含原推文作者的@标识,否则会被API拒绝,同时需遵守Twitter内容规范,避免重复回复或违规内容
内容的提问来源于stack exchange,提问作者Abdulaziz
相关产品推荐
相关产品推荐

