如何通过Telego Go机器人发送格式化HTML或图片消息?
选择图片还是格式化HTML?
优先选择格式化HTML+原生交互按钮,原因如下:
- 维护成本低:文本内容可直接修改,无需重新制作图片;按钮是原生Telegram交互元素,不用调整图片布局。
- 体验更好:WebApp按钮支持原生跳转,点击响应更流畅;文本可适配不同设备屏幕,不会出现拉伸变形。
- 兼容性强:屏幕阅读器可识别文本内容,符合无障碍设计;加载速度更快,节省用户带宽。
纯图片方案仅适合需要固定视觉样式且无需交互的场景,维护和体验都远不如HTML方案。
用Telego Go机器人实现需求的方法
1. 发送带HTML格式文本+WebApp按钮的消息
Telego支持发送HTML格式消息,配合InlineKeyboardMarkup添加WebApp按钮,示例代码:
package main import ( "fmt" "os" "github.com/mymmrac/telego" tu "github.com/mymmrac/telego/telegoutil" ) func main() { botToken := os.Getenv("BOT_TOKEN") bot, err := telego.NewBot(botToken, telego.WithDefaultDebugLogger()) if err != nil { fmt.Println(err) return } // 启动长轮询接收消息 updates, stop := bot.UpdatesViaLongPolling(nil) defer stop() for update := range updates { if update.Message == nil { continue } chatID := tu.ID(update.Message.Chat.ID) // 创建WebApp按钮 orderButton := tu.InlineKeyboardButton("order food").WithWebApp(&telego.WebAppInfo{ URL: "你的PWA实际访问地址", // 替换为你的PWA URL }) keyboard := tu.InlineKeyboard(orderButton.Row()) // 发送带HTML格式的消息 _, err := bot.SendMessage(tu.Message(chatID, "<b>Let's get started</b>"). WithParseMode(telego.ModeHTML). WithReplyMarkup(keyboard), ) if err != nil { fmt.Printf("发送消息失败: %v\n", err) } } }
Telegram允许的HTML格式标签包括<b>、<i>、<u>、<code>等,可根据需求调整文本样式。
2. 发送图片+HTML文本+WebApp按钮
如果需要搭配图片,使用SendPhoto方法,附带格式化说明文本和按钮:
// 在循环内替换SendMessage为以下代码 _, err := bot.SendPhoto(tu.Photo(chatID, tu.FileURL("图片的在线URL")). WithCaption("<b>Let's get started</b>"). WithParseMode(telego.ModeHTML). WithReplyMarkup(keyboard), ) if err != nil { fmt.Printf("发送图片失败: %v\n", err) }
也可以使用本地图片,将tu.FileURL替换为tu.FilePath("本地图片路径")。
内容的提问来源于stack exchange,提问作者hoos
相关产品推荐
相关产品推荐

