Telegram API发送带预览文档问题:Thumb属性被忽略
Telegram机器人文档缩略图不显示问题
我正在开发一个Telegram机器人,需求是发送带有预览图的文档。流程是先接收用户发送的文档,再接收缩略图,之后把文档和缩略图一起发送。但实际发送后只显示文档,Thumb属性完全被忽略,换telebot库试了也一样。
附上Go代码:
bot, err := tgbotapi.NewBotAPI(viper.GetString("tg_api_key")) if err != nil { panic(err) } u := tgbotapi.NewUpdate(0) u.Timeout = 60 var docId tgbotapi.FileID updates := bot.GetUpdatesChan(u) for update := range updates { msg := update.Message if msg == nil { continue } var reply []string switch { case msg.Text == "/start": reply = []string{"Send me the document to be previewed"} case msg.Document != nil: docId = tgbotapi.FileID(msg.Document.FileID) reply = []string{"Now send me the thumbnail"} case msg.Photo != nil: doc := tgbotapi.NewDocument(msg.Chat.ID, docId) doc.Thumb = tgbotapi.FileID(msg.Photo[0].FileID) bot.Send(doc) continue default: reply = []string{"Unknown command"} } result := tgbotapi.NewMessage(msg.Chat.ID, strings.Join(reply, "\n")) bot.Send(result) }
预期效果:
问题解决办法
1. 确保缩略图符合Telegram规格
Telegram要求文档缩略图必须是100x100像素的正方形,且文件大小不超过200KB。你当前取的msg.Photo[0]是分辨率最低的图,但不一定满足100x100的要求,不符合的话会被直接忽略。
修改代码,遍历照片数组选最接近要求的尺寸:
import "math" // 实现绝对值函数 func abs(x int) int { if x < 0 { return -x } return x } // 在处理Photo的分支里替换原有代码 case msg.Photo != nil: var thumbFileID tgbotapi.FileID minDiff := math.MaxInt32 // 遍历所有照片尺寸,找最接近100x100的 for _, photo := range msg.Photo { diff := abs(photo.Width - 100) + abs(photo.Height - 100) if diff < minDiff { minDiff = diff thumbFileID = tgbotapi.FileID(photo.FileID) } } doc := tgbotapi.NewDocument(msg.Chat.ID, docId) doc.Thumb = thumbFileID bot.Send(doc) continue
2. 处理文档自带缩略图的情况
如果用户发送的原始文档本身内置了缩略图(比如PDF、Word文档),Telegram会优先用内置图,忽略你设置的Thumb参数。
解决方式:
- 下载原始文档,移除其内置缩略图后重新上传;
- 尝试添加
DisableContentTypeDetection参数,部分场景下能强制使用自定义缩略图:
doc.DisableContentTypeDetection = true
3. 更新库到最新版本
旧版tgbotapi可能存在参数传递bug,执行命令更新:
go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5
内容的提问来源于stack exchange,提问作者James May
相关产品推荐
相关产品推荐

