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

如何使用Telegram Bot API的Go语言版本创建ReplyKeyboardMarkup

如何在tgbotapi中创建ReplyKeyboardMarkup所需的KeyboardButton矩阵

早期版本的tgbotapi库允许直接用字符串数组快速生成键盘,但现在需要严格遵循Telegram API规范,使用KeyboardButton对象的二维数组来构建键盘。

修正后的代码示例

// 创建KeyboardButton的二维数组
var itemsSel [][]tgbotapi.KeyboardButton
// 第一行按钮:三个按钮在同一行
row := []tgbotapi.KeyboardButton{
    tgbotapi.NewKeyboardButton(item1.Caption),
    tgbotapi.NewKeyboardButton(item2.Caption),
    tgbotapi.NewKeyboardButton(item3.Caption),
}
itemsSel = append(itemsSel, row)

msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Select item")
msg.ReplyMarkup = &tgbotapi.ReplyKeyboardMarkup{
    Keyboard:        itemsSel,
    ResizeKeyboard:  true,
    OneTimeKeyboard: false,
    Selective:       false,
}

log.Println(msg.ReplyMarkup)

msg.ReplyToMessageID = update.Message.MessageID
bot.Send(msg)

关键说明

  • 单个KeyboardButton可以通过tgbotapi.NewKeyboardButton()方法创建,传入按钮显示的文本即可。
  • 每一行按钮是一个[]tgbotapi.KeyboardButton切片,多行按钮就组成[][]tgbotapi.KeyboardButton矩阵。
  • 如果需要多行布局,只需添加更多行切片到itemsSel中,比如:
    // 添加第二行单个按钮
    itemsSel = append(itemsSel, []tgbotapi.KeyboardButton{tgbotapi.NewKeyboardButton("Back")})
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 22:06:35