go-telegram-bot-api Command Handling的代码示范

50 min read

以下是使用go-telegram-bot-api库实现Command Handling的示范代码:

package main

import (
	"log"
	"strings"

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

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

	bot.Debug = true

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

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

	updates, err := bot.GetUpdatesChan(u)

	// Define commands
	commands := map[string]func(*tgbotapi.Message){
		"start": func(msg *tgbotapi.Message) {
			msgText := "Welcome to my bot!"
			reply := tgbotapi.NewMessage(msg.Chat.ID, msgText)
			bot.Send(reply)
		},
		"help": func(msg *tgbotapi.Message) {
			msgText := "This is the help message."
			reply := tgbotapi.NewMessage(msg.Chat.ID, msgText)
			bot.Send(reply)
		},
	}

	for update := range updates {
		if update.Message == nil {
			continue
		}

		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		if update.Message.IsCommand() {
			command := strings.ToLower(update.Message.Command())
			if commandHandler, ok := commands[command]; ok {
				commandHandler(update.Message)
			} else {
				msgText := "Unknown command: " + command
				reply := tgbotapi.NewMessage(update.Message.Chat.ID, msgText)
				bot.Send(reply)
			}
		}
	}
}

在这个示范代码中,我们定义了两个命令:starthelp。这些命令对应着我们在Telegram中输入的命令。例如:/start/help

当收到一个消息时,我们会检查这个消息是否为一个命令。如果是一个命令,我们会提取这个命令的文本,并根据这个文本匹配对应的函数进行处理。如果找不到匹配的函数,我们会返回一个错误消息。

如果这个消息不是命令,则我们可以在这里定义何时执行特定的操作。例如,通过检查消息文本来进行不同的操作。这个例子只是处理了命令,但是您可以根据自己的需求来处理不同的消息类型。

请注意,在实际应用中,我们应该将命令处理函数作为单独的包/文件。这样可以更好地组织代码,并使我们的代码更易于维护。