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

使用grammy库在Telegram发送GIF却显示为视频的问题求助

问题:Grammy发送GIF显示为视频而非动画

我们使用Grammy库开发Telegram机器人时遇到问题:尝试按照文档使用sendAnimation方法发送GIF文件,这些文件却在Telegram中以视频形式显示,而非动画。已确认文件确实为GIF格式,寻求解决方案、原因解释或类似经验分享。

相关代码

async function sendChallengeAnimation(
    ctx: CommandContext<Context>
): Promise<void> {
    const randomAnimationNumber =
        Math.floor(Math.random() * challengeAnimationsCount) + 1
    const video = InputMediaBuilder.video(
        new InputFile(`media/challenge/${randomAnimationNumber}.gif`)
    )
    await ctx.replyWithMediaGroup([video])
}

原因分析

  1. API方法误用:你当前代码使用了InputMediaBuilder.video()和replyWithMediaGroup,这两个方法是按视频类型上传文件,即便文件后缀是GIF,Telegram也会将其识别为视频处理。
  2. 文件编码问题:部分文件虽后缀为.gif,但实际是视频编码(如MP4封装),Telegram会检测文件实际编码格式,而非仅依赖后缀判断类型。

解决方案

方案1:使用专用的动画发送方法

直接调用Grammy提供的replyWithAnimation方法,该方法专门针对GIF动画设计:

async function sendChallengeAnimation(
    ctx: CommandContext<Context>
): Promise<void> {
    const randomAnimationNumber =
        Math.floor(Math.random() * challengeAnimationsCount) + 1
    await ctx.replyWithAnimation(
        new InputFile(`media/challenge/${randomAnimationNumber}.gif`)
    )
}

方案2:媒体组中发送动画

如果必须通过媒体组发送,需替换InputMediaBuilder.video()为InputMediaBuilder.animation():

async function sendChallengeAnimation(
    ctx: CommandContext<Context>
): Promise<void> {
    const randomAnimationNumber =
        Math.floor(Math.random() * challengeAnimationsCount) + 1
    const animation = InputMediaBuilder.animation(
        new InputFile(`media/challenge/${randomAnimationNumber}.gif`)
    )
    await ctx.replyWithMediaGroup([animation])
}

方案3:验证并修复GIF文件编码

用工具(如ffmpeg)检查文件实际编码:

ffmpeg -i your-file.gif

若输出显示为视频流(如Video: h264),则需转成标准GIF格式:

ffmpeg -i your-file.gif -f gif output.gif

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:22:08