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

基于Aiogram 3.11开发Telegram Bot:视频转视频消息及回传实现

基于Aiogram 3.11实现视频转圆形视频消息(Video Note)方案

核心需求拆解

  • 接收用户发送的视频文件
  • 将视频转换为符合Telegram Video Note规范的正方形分辨率视频(通常为320x320或640x640)
  • 通过Aiogram回传转换后的圆形视频消息

实现步骤与代码示例

1. 依赖安装

需安装Aiogram指定版本和视频处理库ffmpeg-python(用于视频格式、分辨率调整):

pip install aiogram==3.11 ffmpeg-python

注意:系统需提前安装FFmpeg本体,否则ffmpeg-python无法调用功能。

2. 完整代码实现

初始化模块与机器人

import os
import ffmpeg
from aiogram import Bot, Dispatcher, Router
from aiogram.types import Message, Video
from aiogram.filters import Command

# 替换为你的机器人Token
BOT_TOKEN = "你的Telegram机器人Token"
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
router = Router()
dp.include_router(router)

视频转换工具函数

def convert_to_video_note(input_path: str, output_path: str):
    """将普通视频裁剪并缩放到符合Video Note要求的正方形视频"""
    # 获取原视频分辨率信息
    probe = ffmpeg.probe(input_path)
    video_stream = next(s for s in probe["streams"] if s["codec_type"] == "video")
    origin_width = int(video_stream["width"])
    origin_height = int(video_stream["height"])
    
    # 计算正方形裁剪参数:取原视频最小边为裁剪尺寸,居中裁剪
    crop_size = min(origin_width, origin_height)
    x_offset = (origin_width - crop_size) // 2
    y_offset = (origin_height - crop_size) // 2
    
    # 使用FFmpeg完成裁剪、缩放、格式转换
    (
        ffmpeg
        .input(input_path)
        .filter("crop", crop_size, crop_size, x_offset, y_offset)
        .filter("scale", 640, 640)  # 统一缩放到640x640,适配Telegram要求
        .output(output_path, vcodec="libx264", acodec="aac", format="mp4")
        .overwrite_output()
        .run(capture_stdout=True, capture_stderr=True)
    )

消息处理逻辑

@router.message(Command("Get_circle"))
async def cmd_circle(message: Message):
    await message.answer("请发送需要转换的视频文件")

@router.message(lambda msg: msg.video is not None)
async def handle_user_video(message: Message):
    video: Video = message.video
    # 下载用户发送的视频到临时文件
    temp_input_path = f"temp_video_{video.file_id}.mp4"
    await bot.download(video, destination=temp_input_path)
    
    # 转换为Video Note格式
    temp_output_path = f"video_note_{video.file_id}.mp4"
    try:
        convert_to_video_note(temp_input_path, temp_output_path)
        # 发送转换后的圆形视频消息
        with open(temp_output_path, "rb") as video_note_file:
            await message.answer_video_note(video_note=video_note_file)
    except Exception as e:
        await message.answer(f"转换失败:{str(e)}")
    finally:
        # 清理临时文件,避免磁盘占用
        if os.path.exists(temp_input_path):
            os.remove(temp_input_path)
        if os.path.exists(temp_output_path):
            os.remove(temp_output_path)

# 启动机器人
if __name__ == "__main__":
    import asyncio
    asyncio.run(dp.start_polling(bot))

3. 关键注意事项

  • Video Note规范:Telegram要求视频必须为正方形,格式为MP4,文件大小不超过1GB;
  • FFmpeg依赖:需确保系统已安装FFmpeg,可通过ffmpeg -version验证;
  • 临时文件管理:转换完成后及时删除临时文件,避免磁盘空间浪费;
  • 错误处理:捕获转换过程中的异常,给用户明确的错误反馈。

内容的提问来源于stack exchange,提问作者Игорь А

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:22:18