telegram-bot

Go helpers for building Telegram bots and authenticating Telegram Mini Apps, built on top of github.com/go-telegram/bot and github.com/telegram-mini-apps/init-data-golang.
Packages
telegram — bot application wrapper with command/callback routing, middleware, typed callback payloads, reply/edit helpers, rate-limited broadcasting, and HTTP 429 retries.
tmaauth — validator and test token generator for Telegram Mini App initData.
Installation
go get github.com/go-sphere/telegram-bot
Quickstart (telegram)
Create a bot with telegram.NewApp, register command and callback handlers before Start, and cancel the context to shut down polling cleanly (see telegram/example_test.go):
package main
import (
"context"
"fmt"
"os"
"os/signal"
"github.com/go-sphere/telegram-bot/telegram"
)
func main() {
app, err := telegram.NewApp(telegram.Config{Token: os.Getenv("TELEGRAM_BOT_TOKEN")})
if err != nil {
fmt.Println("new app:", err)
return
}
app.BindCommand("start", func(ctx context.Context, update *telegram.Update) error {
return app.SendMessage(ctx, update, &telegram.Message{Text: "Hello!"})
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := app.Start(ctx); err != nil { // blocks until ctx is cancelled
fmt.Println("start:", err)
}
}
- Typed callback buttons: encode structured payloads (up to Telegram's 64-byte
MaxCallbackDataLength limit) with telegram.NewButton / telegram.MarshalData and decode them in Bot.BindCallback handlers with telegram.UnmarshalData[T]. Note that only exported fields with a json tag are encoded.
- Routing and middleware: register fallback handlers with
Bot.BindNoRoute or generated protoc-gen-route tables with Bot.BindRoute. Built-in middleware includes NewSingleFlightMiddleware (deduplicates concurrent identical callback presses), NewGroupMessageFilterMiddleware (filters group/supergroup messages by reply or @username mention), NewAuthMiddleware, and NewRecoveryMiddleware.
- Errors and sending:
Bot.SendMessage and telegram.SendMessage send a new reply for regular messages and edit the originating message for callback queries; telegram.SendErrorMessage can be passed to telegram.WithErrorHandler to surface errors to users. Use telegram.BroadcastMessage for rate-limited broadcasts and telegram.RetryOnTooManyRequestsErrorContext to retry HTTP 429 responses.
Telegram Mini App Auth (tmaauth)
Use tmaauth.NewTmaAuth to verify the signed window.Telegram.WebApp.initData string sent by Mini App clients (commonly in Authorization: tma <initData>):
package auth
import (
"errors"
"net/http"
"os"
"strings"
"time"
"github.com/go-sphere/telegram-bot/tmaauth"
)
var tma = tmaauth.NewTmaAuth(os.Getenv("TELEGRAM_BOT_TOKEN"), 24*time.Hour)
func userIDFromRequest(r *http.Request) (int64, error) {
initData, ok := strings.CutPrefix(r.Header.Get("Authorization"), tmaauth.AuthorizationPrefixTMA+" ")
if !ok {
return 0, errors.New("missing tma authorization")
}
claims, err := tma.ParseToken(r.Context(), initData)
if err != nil {
return 0, err // invalid signature, expired, or malformed
}
return claims.User.ID, nil
}
ParseToken and GenerateToken return tmaauth.ErrEmptyBotToken when the configured bot token is empty or whitespace-only.
- Validation errors from
github.com/telegram-mini-apps/init-data-golang (such as initdata.ErrSignInvalid, initdata.ErrExpired, and initdata.ErrSignMissing) can be matched with errors.Is.
- Use
tma.GenerateToken(ctx, &tmaauth.Claims{...}) to produce signed init data strings in tests and local tools.
Documentation
Full API reference and runnable examples are available on pkg.go.dev:
License
MIT License. See LICENSE for details.