How to Build a Telegram Bot in Go

Web
TITLE: How to Build a Telegram Bot in Go

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)
		}
	}
}
  1. Install the library by running go get github.com/go-telegram-bot-api/telegram-bot-api/v5.
  2. Replace YOUR_BOT_TOKEN with the token you received from @BotFather.
  3. Run the program with go run main.go to start listening for messages.