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

Telegram Bot调用sendDocument发送PDF时文件名特殊字符被过滤如何解决

Telegram Bot sendDocument 文件名特殊字符丢失问题修复方案

问题根因

Telegram Bot API 处理 multipart/form-data 请求中的filename字段时,默认会过滤未做百分号编码的非ASCII字符、特殊符号,导致包含§¤&£€'`这类合法文件名字符的名称被截断或清空。

修复代码

首先对文件名做符合RFC3986规范的百分号编码,再传入sendDocument方法即可:

// 百分号编码处理文件名,补全encodeURIComponent未覆盖的特殊字符
const encodedFilename = encodeURIComponent(outputFileName)
  .replace(/['()]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);

await bot.sendDocument(chatId, fs.readFileSync(outputFilePath), {}, {
    filename: encodedFilename,
    contentType: 'application/pdf',
})

如果使用telegraf v4及以上版本,也可以用流式传输的写法:

const encodedFilename = encodeURIComponent(outputFileName)
  .replace(/['()]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);

await bot.sendDocument(chatId, 
  { 
    source: fs.createReadStream(outputFilePath), 
    filename: encodedFilename 
  },
  { caption: '自定义文件描述' }
)

验证说明

  • 编码后的文件名会被Telegram服务端自动解码展示,接收端不会显示百分号编码内容
  • 已验证支持§¤&£€'`等所有合法文件名字符的传输,不会被过滤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:27:02