如何使用Telegram Bot API的Go语言版本创建ReplyKeyboardMarkup
早期版本的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
相关产品推荐
相关产品推荐

