TITLE: How to Build a Telegram Bot in Go
You build a Telegram bot in Go by initializing a client with your API token, registering a message handler, and starting the update listener.
package main
import (
"fmt"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI("YOUR_BOT_TOKEN")
if err != nil {
panic(err)
}
bot.Debug = true
fmt.Println("Authorized on account", 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, "Hello!")
msg.DisableNotification = true
bot.Send(msg)
}
}
}
- Install the library by running
go get github.com/go-telegram-bot-api/telegram-bot-api/v5. - Replace
YOUR_BOT_TOKENwith the token you received from @BotFather. - Run the program with
go run main.goto start listening for messages.