使用Tweepy与Twitter API v2发带图推文遇权限问题求助
解决Twitter机器人发图的权限问题及API v2实现方案
一、用Twitter API v2 + Tweepy v4实现发图(无需升级权限)
Essential权限完全支持API v2的媒体上传和发推文接口,你之前用Tweepy v4失败大概率是写法不对。以下是适配v2的可行代码:
先确保安装最新版Tweepy:
pip install --upgrade tweepy
替换你的认证与发图逻辑:
import tweepy import time # 你的API密钥与令牌 consumer_key = '####' consumer_secret = '####' access_token = '####' access_token_secret = '####' # Tweepy v4的OAuth1认证方式 auth = tweepy.OAuth1UserHandler( consumer_key, consumer_secret, access_token, access_token_secret ) # 初始化v2客户端用于发推文 client_v2 = tweepy.Client( consumer_key=consumer_key, consumer_secret=consumer_secret, access_token=access_token, access_token_secret=access_token_secret ) # 初始化v1.1 API实例用于上传媒体(Essential权限允许此操作) api_v1 = tweepy.API(auth) def tweet_image(frame_file, status_text): # 上传图片获取媒体ID media = api_v1.media_upload(filename=frame_file) # 用v2接口发布带媒体的推文 response = client_v2.create_tweet(text=status_text, media_ids=[media.media_id_string]) print(f"推文发布成功,ID: {response.data['id']}") # 循环发图示例 frame_number = 0 tweet_interval = 3600 # 自定义发图间隔,这里是1小时 while True: # 调用你的图片生成逻辑,得到frame_file路径 # frame_file = your_image_generator() tweet_image(frame_file, f"第{frame_number+1}张生成图") frame_number += 1 time.sleep(tweet_interval)
二、关于Elevated权限的申请
如果一定要用v1.1的update_with_media旧接口,申请入口在Twitter开发者平台:
- 登录账号后进入对应项目
- 左侧菜单选「Projects & Apps」→ 你的应用
- 切换到「Permissions and features」标签页
- 找到「Elevated」权限选项点击「Apply」,填写学习用途的说明即可,一般很快通过
不过更推荐用v2方案,因为官方正逐步淘汰v1.1旧接口,v2是长期支持的方向。
内容的提问来源于stack exchange,提问作者georgelid6
相关产品推荐
相关产品推荐

