Telegram Bot为何自动转GIF为WEBM?如何解决发送格式异常?
解决Telegram Bot发送GIF自动转WEBM的问题
Telegram自动转格式是因为sendAnimation接口本身为动画优化设计,会自动将GIF转成更高效的WEBM格式。要保留GIF格式,需改用sendDocument接口,并明确指定文件的MIME类型为image/gif,同时确保文件名后缀为.gif。
修改后的代码示例:
private void sendGifAsDocument(FaceSwapperResponseDto image, String chatId) { BotInitialize bot = LegramContextHolder.getContext().getBot(); String filePath = "file.gif"; try (FileOutputStream fos = new FileOutputStream(filePath)) { fos.write(image.getImageBytes()); } catch (IOException e) { e.printStackTrace(); } File file = new File(filePath); SendDocument sendDocument = new SendDocument(); sendDocument.setChatId(chatId); // 指定MIME类型为image/gif,避免格式转换 InputFile inputFile = new InputFile(file); inputFile.setMediaType("image/gif"); sendDocument.setDocument(inputFile); bot.execute(sendDocument); }
关键注意点:
- 放弃使用
sendAnimation接口,该接口会强制触发Telegram的动画格式优化 - 显式设置
InputFile的MediaType为image/gif,明确告知Telegram文件类型 - 本地保存的文件必须保留
.gif后缀,辅助Telegram识别原始格式
按上述方式发送后,接收端将收到原始的GIF格式文件,不会被转换为WEBM。
内容的提问来源于stack exchange,提问作者Omar Kudaiberdiev
相关产品推荐
相关产品推荐

