You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

将视频拖入Telegram机器人聊天窗口后出现Error code:400错误的技术咨询

解决Telegram Bot 400 Bad Request错误的问题

你遇到的Error code: 400, Description: Bad Request: wrong file identifier/HTTP URL specified错误,主要是由代码里的几个关键问题导致的,我来帮你一步步排查和修复:

问题1:FFmpeg命令未实际执行,输出文件未生成

你只是构建了FFmpeg的处理逻辑链,但没有调用执行方法——这意味着out.mp4根本没有被创建(或者是个空文件)。当你尝试用bot.send_document发送这个无效文件时,Telegram API自然会返回"文件标识符错误"的400请求。

问题2:消息处理器兼容多类型,但仅处理video类型,存在潜在报错风险

你的处理器监听了document, photo, audio, video, voice多种内容类型,但函数里直接访问message.video。如果用户发送的是其他类型(比如把视频作为document文件拖拽上传),会直接引发属性错误;即使当前是video类型,这种不严谨的处理也可能导致后续逻辑异常。

问题3:文件发送方式不够可靠

直接传文件名给send_document,如果文件不存在、权限不足或者路径错误,Bot无法正确读取文件,同样会触发Telegram的无效文件报错。


修正后的完整代码

我把所有问题都修复了,你可以直接测试这个版本:

import ffmpeg
import telebot
from telebot.types import Message

bot = telebot.TeleBot("你的Bot Token", parse_mode=None)
MY_ID = 123456789  # 替换成你的实际Telegram ID

@bot.message_handler(content_types=['video'])
def handle_video(message: Message):
    try:
        # 下载用户发送的视频
        file_info = bot.get_file(message.video.file_id)
        downloaded_file = bot.download_file(file_info.file_path)
        
        # 保存原始视频到本地
        input_file = "temp_input.mp4"
        with open(input_file, 'wb') as f:
            f.write(downloaded_file)
        
        # 执行FFmpeg视频处理(必须调用.run()才会实际执行)
        output_file = "processed_video.mp4"
        (
            ffmpeg.input(input_file)
            .filter('hflip')
            .filter('contrast', contrast=0.9)
            .filter('gamma_b', gamma_b=1.3)
            .filter('saturation', saturation=1)
            .output(output_file)
            .overwrite_output()  # 自动覆盖已存在的输出文件
            .run(capture_stdout=True, capture_stderr=True)
        )
        
        # 以文件对象的方式发送处理后的视频,确保文件可读
        with open(output_file, 'rb') as f:
            bot.send_document(MY_ID, f)
        
        print("视频处理并发送成功!")
        
    except Exception as e:
        print(f"处理出错: {str(e)}")
        bot.send_message(message.chat.id, f"视频处理失败:{str(e)}")

bot.infinity_polling()

额外优化建议

  • 异常捕获:代码里添加了全局异常捕获,能帮你快速定位FFmpeg执行失败、文件读写错误等问题
  • 限定处理类型:只监听video类型,避免处理非视频内容引发的无效操作
  • FFmpeg路径配置:如果你的系统环境中FFmpeg不在默认PATH里,需要在调用时指定路径,比如ffmpeg.input(..., cmd="/usr/local/bin/ffmpeg")

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

火山引擎 最新活动