Telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便
获取机器人
Telegram 非常有趣,要新增自己的 Bot,只要跟 Telegram 上的 BotFather 说一下,他就会给你一个 Bot
按BotFather 给你的步骤做,最后可以看到他会提供一个API Token 给你,只要有这个Token 就可以跟Bot 沟通。要保存好,等等会用到,也不要给别人看到,以免自己的Bot 变成别人的玩具。
Go-Telegram-bot-api
Go 已经有社区开发的函式库: https://github.com/go-telegram-bot-api/telegram-bot-api
新建项目
初始化
go mod init tgBot
go get -u github.com/go-telegram-bot-api/telegram-bot-api/v5
之后只要 import 就可以使用:
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
只需要刚刚创建好的 Bot 的 API Token 就可以连接到Telegram
bot, err := tgbotapi.NewBotAPI("你的bot token")
if err != nil {
panic(err)
}
处理 Update
要接收使用者传过来的讯息,Telegram API 称为 Update,我们使用的函示库基本上都自动处理好了,只需要接收一个 Channel 就好。使用 bot.GetUpdatesChan(config) 会需要给一个 Config,这可以用 tgbotapi.NewUpdate(0) 来生成
updateConfig := tgbotapi.NewUpdate(0)
updateConfig.Timeout = 60
updates := bot.GetUpdatesChan(updateConfig)
用 for 把 Channel 中的 Update 一个一个拿出来,然后用 tgbotapi 产生一个 Message 物件,里面放在聊天室的 ID 和要回传的 Text,最后用 bot 把 Message 传回去
for update := range updates {
text := update.Message.Text
chatID := update.Message.Chat.ID
replyMsg := tgbotapi.NewMessage(chatID, text)
_, _ = bot.Send(replyMsg)
}
示例代码:
package main
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI("你的bot token")
if err != nil {
panic(err)
}
bot.Debug = true
updateConfig := tgbotapi.NewUpdate(0)
updateConfig.Timeout = 60
updates := bot.GetUpdatesChan(updateConfig)
for update := range updates {
text := update.Message.Text
chatID := update.Message.Chat.ID
replyMsg := tgbotapi.NewMessage(chatID, text)
_, _ = bot.Send(replyMsg)
}
}
改写成非阻塞的 Goroutine
每次处理和回复都会需要一点时间,甚至是要去 DB 找资料,如果用上面的写法,在处理多人或高速传讯息的时候会被卡住,一次只能处理的一个讯息。还好 Go 的并发写法非常简单,只要放一个 go 在前面,就可以非阻塞的执行 function 中的内容。我们先把 handleUpdate 提取成一个 function,然后再用 go 去执行他:
package main
import (
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI("你的bot token")
if err != nil {
panic(err)
}
bot.Debug = true
updateConfig := tgbotapi.NewUpdate(0)
updateConfig.Timeout = 60
updates := bot.GetUpdatesChan(updateConfig)
for update := range updates {
go handleUpdate(bot, update)
}
}
func handleUpdate(bot *tgbotapi.BotAPI, update tgbotapi.Update) {
text := update.Message.Text
chatID := update.Message.Chat.ID
replyMsg := tgbotapi.NewMessage(chatID, text)
_, _ = bot.Send(replyMsg)
}