• go-telegram-bot-api库的使用
  • 自动回复消息


    package main
    
    import (
    	"log"
    
    	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
    )
    
    func main() {
    	// 创建一个新的 Telegram Bot API 客户端
    	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    	if err != nil {
    		log.Panic(err)
    	}
    
    	// 开启调试模式,输出日志
    	bot.Debug = true
    
    	// 输出 Bot 的用户名
    	log.Printf("Authorized on account %s", bot.Self.UserName)
    
    	// 创建一个新的更新对象
    	u := tgbotapi.NewUpdate(0)
    	u.Timeout = 60
    
    	// 获取消息更新的通道
    	updates := bot.GetUpdatesChan(u)
    
    	// 循环处理每个更新
    	for update := range updates {
    		// 检查是否收到消息
    		if update.Message != nil {
    			// 输出收到的消息到日志中
    			log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
    
    			// 构造一个新的消息对象,回复的消息内容与收到的消息内容相同
    			msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
    			// 设置回复消息的 ID,使回复消息能够与原消息进行关联
    			msg.ReplyToMessageID = update.Message.MessageID
    
    			// 发送回复消息
    			bot.Send(msg)
    		}
    	}
    }


    使用 Webhooks


    (比如你想在 Google App Engine 上运行),你可以使用稍微不同的方法。

    package main
    
    import (
    	"log"
    	"net/http"
    
    	"github.com/go-telegram-bot-api/telegram-bot-api/v5"
    )
    
    func main() {
    	// 创建一个新的 Telegram Bot API 客户端
    	bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// 开启调试模式,输出日志
    	bot.Debug = true
    
    	// 输出 Bot 的用户名
    	log.Printf("Authorized on account %s", bot.Self.UserName)
    
    	// 创建一个新的 Webhook 对象,并使用自签名证书
    	wh, _ := tgbotapi.NewWebhookWithCert("https://www.example.com:8443/"+bot.Token, "cert.pem")
    
    	// 向 Telegram 发送设置 Webhook 的请求
    	_, err = bot.Request(wh)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// 获取当前 Webhook 的信息
    	info, err := bot.GetWebhookInfo()
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// 如果上一次设置 Webhook 失败,则输出错误信息
    	if info.LastErrorDate != 0 {
    		log.Printf("Telegram callback failed: %s", info.LastErrorMessage)
    	}
    
    	// 监听 Telegram 发送的 Webhook 更新
    	updates := bot.ListenForWebhook("/" + bot.Token)
    	// 启动 HTTPS 服务器并监听指定端口,使用 cert.pem 和 key.pem 作为证书和私钥
    	go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)
    
    	// 处理接收到的更新
    	for update := range updates {
    		log.Printf("%+v\n", update)
    	}
    }


    命令处理



    package main
    
    import (
        "log"
        "os"
    
        tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
    )
    
    func main() {
        // 创建新的Telegram Bot API客户端
        bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
        if err != nil {
            log.Panic(err)
        }
    
        // 开启调试模式,输出日志
        bot.Debug = true
    
        // 输出Bot的用户名
        log.Printf("Authorized on account %s", bot.Self.UserName)
    
        // 创建一个新的更新对象
        u := tgbotapi.NewUpdate(0)
        u.Timeout = 60
    
        // 获取消息更新的通道
        updates := bot.GetUpdatesChan(u)
    
        // 遍历消息更新
        for update := range updates {
            // 如果收到的更新不是消息类型,跳过处理
            if update.Message == nil {
                continue
            }
    
            // 如果消息不是命令类型,跳过处理
            if !update.Message.IsCommand() {
                continue
            }
    
            // 创建一个新的消息配置对象
            msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")
    
            // 从消息中提取命令
            switch update.Message.Command() {
            case "help":
                // 如果收到 /help 命令,回复帮助信息
                msg.Text = "我理解 /sayhi 和 /status."
            case "sayhi":
                // 如果收到 /sayhi 命令,回复问候消息
                msg.Text = "Hi :)"
            case "status":
                // 如果收到 /status 命令,回复状态信息
                msg.Text = "我很好."
            default:
                // 对于其他未知命令,回复提示信息
                msg.Text = "我不知道这个命令"
            }
    
            // 发送回复消息
            if _, err := bot.Send(msg); err != nil {
                log.Panic(err)
            }
        }
    }



    键盘


    package main
    
    import (
        "log"
        "os"
    
        tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
    )
    
    // 定义一个数字键盘
    var numericKeyboard = tgbotapi.NewReplyKeyboard(
        tgbotapi.NewKeyboardButtonRow(
            tgbotapi.NewKeyboardButton("1"),
            tgbotapi.NewKeyboardButton("2"),
            tgbotapi.NewKeyboardButton("3"),
        ),
        tgbotapi.NewKeyboardButtonRow(
            tgbotapi.NewKeyboardButton("4"),
            tgbotapi.NewKeyboardButton("5"),
            tgbotapi.NewKeyboardButton("6"),
        ),
    )
    
    func main() {
        // 创建新的Telegram Bot API客户端
        bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
        if err != nil {
            log.Panic(err)
        }
    
        // 开启调试模式,输出日志
        bot.Debug = true
    
        // 输出Bot的用户名
        log.Printf("Authorized on account %s", bot.Self.UserName)
    
        // 创建一个新的更新对象
        u := tgbotapi.NewUpdate(0)
        u.Timeout = 60
    
        // 获取消息更新的通道
        updates := bot.GetUpdatesChan(u)
    
        // 遍历消息更新
        for update := range updates {
            // 如果收到的更新不是消息类型,跳过处理
            if update.Message == nil {
                continue
            }
    
            // 创建一个新的消息对象,回复的消息内容与收到的消息内容相同
            msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
    
            // 根据收到的消息内容进行判断
            switch update.Message.Text {
            case "open":
                // 如果收到 "open" 命令,显示数字键盘
                msg.ReplyMarkup = numericKeyboard
            case "close":
                // 如果收到 "close" 命令,关闭键盘
                msg.ReplyMarkup = tgbotapi.NewRemoveKeyboard(true)
            }
    
            // 发送回复消息
            if _, err := bot.Send(msg); err != nil {
                log.Panic(err)
            }
        }
    }



    内联键盘


    package main
    
    import (
        "log"
        "os"
    
        tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
    )
    
    // 定义一个内联键盘
    var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup(
        // 第一行按钮
        tgbotapi.NewInlineKeyboardRow(
            tgbotapi.NewInlineKeyboardButtonURL("1.com", "http://1.com"), // URL按钮
            tgbotapi.NewInlineKeyboardButtonData("2", "2"),               // 数据按钮
            tgbotapi.NewInlineKeyboardButtonData("3", "3"),               // 数据按钮
        ),
        // 第二行按钮
        tgbotapi.NewInlineKeyboardRow(
            tgbotapi.NewInlineKeyboardButtonData("4", "4"), // 数据按钮
            tgbotapi.NewInlineKeyboardButtonData("5", "5"), // 数据按钮
            tgbotapi.NewInlineKeyboardButtonData("6", "6"), // 数据按钮
        ),
    )
    
    func main() {
        // 创建新的Telegram Bot API客户端
        bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
        if err != nil {
            log.Panic(err)
        }
    
        // 开启调试模式,输出日志
        bot.Debug = true
    
        // 输出Bot的用户名
        log.Printf("Authorized on account %s", bot.Self.UserName)
    
        // 创建一个新的更新对象
        u := tgbotapi.NewUpdate(0)
        u.Timeout = 60
    
        // 获取消息更新的通道
        updates := bot.GetUpdatesChan(u)
    
        // 循环处理每个更新
        for update := range updates {
            // 检查是否收到消息更新
            if update.Message != nil {
                // 根据收到的消息构造一个新的消息对象
                msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
    
                // 如果收到的消息是 "open",添加数字键盘
                switch update.Message.Text {
                case "open":
                    msg.ReplyMarkup = numericKeyboard
                }
    
                // 发送消息
                if _, err = bot.Send(msg); err != nil {
                    panic(err)
                }
            } else if update.CallbackQuery != nil {
                // 回复回调查询,告诉Telegram向用户显示包含收到数据的消息
                callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data)
                if _, err := bot.Request(callback); err != nil {
                    panic(err)
                }
    
                // 最后,发送包含收到数据的消息
                msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Data)
                if _, err := bot.Send(msg); err != nil {
                    panic(err)
                }
            }
        }
    }