go-telegram-bot-api Keyboard 的代码示范

36 min read

以下是一个简单的示范代码,用于使用 go-telegram-bot-api 中的 Keyboard 功能:

package main

import (
	"log"

	"github.com/go-telegram-bot-api/telegram-bot-api"
)

func main() {
	bot, err := tgbotapi.NewBotAPI("YOUR_TOKEN_HERE")
	if err != nil {
		log.Panic(err)
	}

	bot.Debug = true

	log.Printf("Authorized on account %s", bot.Self.UserName)

	updateConfig := tgbotapi.NewUpdate(0)
	updateConfig.Timeout = 60

	updates, err := bot.GetUpdatesChan(updateConfig)

	for update := range updates {
		if update.Message == nil { // ignore non-Message updates
			continue
		}

		msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")

		// 创建一个简单的Keyboard,包含两个按钮
		button1 := tgbotapi.NewKeyboardButton("Button 1")
		button2 := tgbotapi.NewKeyboardButton("Button 2")
		row := []tgbotapi.KeyboardButton{button1, button2}
		keyboard := tgbotapi.NewReplyKeyboard(row)

		// 将 Keyboard 绑定到消息上
		msg.ReplyMarkup = keyboard

		// 发送消息
		if _, err := bot.Send(msg); err != nil {
			log.Panic(err)
		}
	}
}

在这个示例中,我们先创建了一个包含两个按钮的 Keyboard,然后用它来回复收到的每一个消息。在实际使用中,您可以根据自己的需求来创建更复杂的 Keyboard,比如带有多个行的 Keyboard,或者带有回调函数的 Inline Keyboard。