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

使用Tweepy发布视频遇400错误:媒体ID无效问题求助

Tweepy发布视频报错「媒体ID无效」的解决办法
  • 问题根源:视频上传到Twitter后需要转码处理,不像图片能立即生效。你用V1 API上传视频后直接调用V2创建推文,此时视频还在处理中,媒体ID尚未完成验证,因此触发无效报错。

  • 解决步骤:

    1. 上传视频后,必须轮询检查媒体处理状态,直到状态变为succeeded才能调用推文接口
    2. 确保视频符合Twitter免费版要求:MP4格式、H.264视频编码、AAC音频编码、时长≤140秒、文件大小≤512MB
  • 修改后的可运行代码:

import time
import tweepy

# V1 Twitter API Authentication
auth = tweepy.OAuthHandler(api_key, api_key_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)

# V2 Twitter API Authentication
client = tweepy.Client(
    bearer_token,
    api_key,
    api_key_secret,
    access_token,
    access_token_secret,
    wait_on_rate_limit=True,
)

# 上传视频到Twitter
media_upload_result = api.chunked_upload(filename="Pledge.mp4", media_category="tweet_video")
media_id = media_upload_result.media_id_string
print(f"获取到媒体ID: {media_id}")

# 轮询等待媒体处理完成
while True:
    media_status = api.get_media_status(media_id)
    processing_state = media_status.processing_info["state"]
    
    if processing_state == "succeeded":
        print("媒体转码完成,可发布推文")
        break
    elif processing_state == "failed":
        raise Exception("媒体处理失败,请检查视频格式")
    
    # 每5秒检查一次状态
    time.sleep(5)

# 发布带视频的推文
text = "Hello Twitter!"
client.create_tweet(text=text, media_ids=[media_id])
print("推文发布成功!")
  • 额外排查点:如果仍报错,先验证视频格式是否合规,可使用FFmpeg转码为标准格式:
ffmpeg -i Pledge.mp4 -c:v libx264 -c:a aac -strict -2 formatted_pledge.mp4

内容的提问来源于stack exchange,提问作者Pablo Cobo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:57:42