Telegram MP4转MP3机器人开发问题:无法读取用户发送的视频
问题分析与解决方法
你的代码核心问题是直接把Telegram的消息对象(update.message)传给了VideoFileClip,VideoFileClip需要的是本地文件路径或可读取的文件流,而不是消息对象,所以才会无法读取视频。
下面是具体的修复步骤和修正后的代码:
关键修复点
- 从消息对象中提取视频文件,而非直接使用
update.message - 先将用户发送的视频下载到本地,再用MoviePy处理
- 不要硬编码
chat_id,改用消息自带的聊天ID - 增加文件清理逻辑,避免临时文件堆积
修正后的代码
from telegram import Update from telegram.ext import ContextTypes import moviepy.editor as mp import os async def convert_video_to_audio(update: Update, context: ContextTypes.DEFAULT_TYPE): # 检查消息中是否包含视频 if not update.message.video: await update.message.reply_text("请发送视频文件!") return try: # 获取视频文件对象 video_file = await context.bot.get_file(update.message.video.file_id) # 下载视频到本地临时文件 temp_video_path = "temp_video.mp4" await video_file.download_to_drive(temp_video_path) # 转换视频为音频 video_clip = mp.VideoFileClip(temp_video_path) audio_clip = video_clip.audio temp_audio_path = "temp_audio.mp3" audio_clip.write_audiofile(temp_audio_path) # 发送音频给用户 await context.bot.send_audio( chat_id=update.message.chat.id, audio=open(temp_audio_path, 'rb'), timeout=10000 ) # 清理临时文件 video_clip.close() audio_clip.close() os.remove(temp_video_path) os.remove(temp_audio_path) except Exception as e: # 打印错误方便调试,生产环境可移除 print(f"转换错误: {str(e)}") await update.message.reply_text("抱歉,无法将该视频转换为音频")
额外注意事项
- 确保你的Bot已在BotFather中开启处理视频消息的权限
- 处理大视频时,需注意服务器存储空间和超时设置
- 可结合用户ID、时间戳生成唯一临时文件名,避免多用户同时使用时的文件冲突
内容的提问来源于stack exchange,提问作者Yogendran Prakash
相关产品推荐
相关产品推荐

