tgbot

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 9 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

tgbot – Telegram Bot API wrapper for Go

Go Report Card GoDoc

A lightweight wrapper around github.com/go-telegram/bot. It adds a simple handler API with a flattened Message type, middleware support, per-handler tracing hooks, file download links, and HTTP health-check endpoints for webhook mode.

Table of Contents

Section Description
Overview What the library does and why it exists
Features High-level capabilities
Quick start: long polling Minimal code to get a bot running in polling mode
Quick start: webhook Minimal code to run the bot behind an HTTP webhook
Configuration YAML config file (used by the webhook CLI)
Workers Parallel update processing with WithWorkers
Middleware How to plug custom middleware
Tracing & probes Tracer interface, no-op implementation, liveness/readiness endpoints
Command registration AddMenuCommand, AddTextCommand, default / text / callback handlers
Messages & file download Message types and downloading documents/photos
Operations & HTTP endpoints SendMessage, DeleteMessage, GetDownloadLink, /live, /ready
Development Building, testing, linting
Examples Example bots and webhook CLI
License MIT License

Overview

tgbot simplifies the most common tasks when building a Telegram bot in Go:

  • Create a bot with a token and optional options (WithWebHookToken, WithWorkers, timeouts, tracer factory, probes).
  • Run it with Start(ctx) – long polling by default, or webhook mode (with a built-in HTTP server) when a webhook secret token is set.
  • Register commands that automatically appear in the bot's menu and match incoming updates.
  • Add middleware that wraps every handler (e.g. logging, auth, rate limiting).
  • Attach a tracer (or use the default no-op tracer) that is called before/after each handler.
  • Download files (documents, photos) sent to the bot.
  • Expose /live and /ready health-check endpoints in webhook mode, useful for Kubernetes / Docker.

The library is deliberately small – the core type is TGBot (see tgbot.go) and all functionality is exposed through a handful of exported functions and methods.

Features

Feature Details
Long-polling & webhook modes Start(ctx) uses webhook mode when WithWebHookToken is set, long polling otherwise.
Concurrent processing WithWorkers(n) processes updates with n parallel workers (default 1).
Middleware chain AddMiddleware; middleware run in the order they were added (first added is outermost).
Tracer interface Tracer.Before/OnSuccess/OnError/After, created per handler call by WithNewTracerFn; NewNoopTracer included.
Liveness / readiness probes /live and /ready HTTP handlers in webhook mode; probe functions are optional.
Command registration AddMenuCommand (published to the bot menu on Start) & AddTextCommand (no menu entry).
Default / text / callback handlers AddDefaultHandler, AddDefaultTextHandler, AddDefaultCallbackQueryHandler.
Typed messages Message.Type: text, callback query, payment, document, photo.
File download GetDownloadLink for document/photo file IDs; Message.LargestPhoto() helper.
Operations SendMessage, DeleteMessage, GetDownloadLink.
YAML config loading via github.com/jinzhu/configor (webhook CLI).
Go 1.27+ Module go.mod declares go 1.27.0.
Standard tooling make build, make test, make bench, make lint, make fmt (golangci-lint).

Quick start: long polling

package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/Mikhalevich/tgbot"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, nil))

	bot, err := tgbot.New("YOUR_TELEGRAM_TOKEN")
	if err != nil {
		logger.Error("create bot", slog.String("error", err.Error()))
		os.Exit(1)
	}

	bot.AddDefaultHandler(func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
		operations.SendMessage(ctx, msg.ChatID, "You said: "+msg.Text)

		return nil
	})

	if err := bot.Start(context.Background()); err != nil {
		logger.Error("start bot", slog.String("error", err.Error()))
		os.Exit(1)
	}
}

Run: go run main.go

If a handler returns an error, the bot replies to the message with internal error.

Quick start: webhook

package main

import (
	"context"
	"log/slog"
	"os"
	"os/signal"
	"syscall"

	"github.com/Mikhalevich/tgbot"
)

func main() {
	logger := slog.New(slog.NewTextHandler(os.Stdout, nil))

	bot, err := tgbot.New(
		"YOUR_TELEGRAM_TOKEN",
		tgbot.WithWebHookToken("my-secret-token"), // enables webhook mode and validates incoming requests
		tgbot.WithLivenessProbe(func(ctx context.Context) error { return nil }),
		tgbot.WithReadinessProbe(func(ctx context.Context) error { return nil }),
	)
	if err != nil {
		logger.Error("create bot", slog.String("error", err.Error()))
		os.Exit(1)
	}

	bot.AddDefaultHandler(func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
		operations.SendMessage(ctx, msg.ChatID, "You said: "+msg.Text)

		return nil
	})

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	// blocks until ctx is cancelled, then shuts the HTTP server down gracefully
	if err := bot.Start(ctx); err != nil {
		logger.Error("start bot", slog.String("error", err.Error()))
		os.Exit(1)
	}
}

Run: go run main.go – the bot listens on :80 (the port is fixed) and serves:

  • POST / – Telegram webhook updates,
  • GET /live and GET /ready – health checks.

Server timeouts are configurable with WithReadTimeout, WithWriteTimeout and WithShutdownTimeout. The webhook itself must be registered with Telegram separately, e.g. with the cmd/webhook CLI (--set), using the same secret token.

Configuration

The webhook CLI (cmd/webhook/main.go) loads a YAML config:

token: <BOT_TOKEN>
webhook_secret_token: <SECRET_TOKEN>
url: https://example.com/hook
certificate_path: ./certs/public.pem

The struct tags map directly:

type Config struct {
    Token              string `yaml:"token" required:"true"`
    WebHookSecretToken string `yaml:"webhook_secret_token" required:"true"`
    URL                string `yaml:"url" required:"true"`
    CertificatePath    string `yaml:"certificate_path" required:"true"`
}

You can adjust the config path with the -config flag:

./webhook -config ./config/config.yaml

Available flags:

Flag Default Description
--config config/config.yaml Path to YAML file
--get false Dump webhook info
--set false Set webhook
--remove false Remove webhook

Workers

By default updates are processed by a single worker, one at a time. Use WithWorkers to process them in parallel (works in both long-polling and webhook modes):

bot, err := tgbot.New(
	"YOUR_TELEGRAM_TOKEN",
	tgbot.WithWorkers(4),
)
  • The value must be at least 1: 0 means no update is ever processed, and a negative value makes Start panic.
  • With more than one worker, handlers run concurrently and there is no ordering guarantee, even for updates from the same chat. Handlers (and middleware/tracers) that share state must be safe for concurrent use.
  • Register all handlers before calling Start.

Middleware

func LoggingMiddleware(logger *slog.Logger) tgbot.Middleware {
	return func(next tgbot.Handler) tgbot.Handler {
		return func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
			logger.Info("incoming update", slog.String("text", msg.Text))

			return next(ctx, msg, operations)
		}
	}
}

Register it:

bot.AddMiddleware(LoggingMiddleware(logger))

Middleware run in the order they were added: the first added is the outermost, the most recently added runs closest to the handler.

Important: the middleware chain is applied when a handler is registered, so call AddMiddleware before registering handlers – handlers registered earlier won't get middleware added later.

Tracing & probes

  • Tracer – implements Before, OnSuccess, OnError, After. A new tracer is created for every handler call by the factory passed to WithNewTracerFn (the default is NewNoopTracer). examples/echotracer/main.go shows a simple struct that logs each phase.
type tracer struct{ logger *slog.Logger }

func (t tracer) Before(ctx context.Context, pattern string, msg tgbot.Message) context.Context {
	t.logger.Info("handler start", slog.String("pattern", pattern))
	return ctx
}
func (t tracer) OnSuccess(ctx context.Context) { /* … */ }
func (t tracer) OnError(ctx context.Context, err error) {
	t.logger.Error("handler error", slog.String("err", err.Error()))
}
func (t tracer) After(ctx context.Context) { /* … */ }

bot, err := tgbot.New(
	"YOUR_TELEGRAM_TOKEN",
	tgbot.WithNewTracerFn(func() tgbot.Tracer {
		return tracer{logger: logger}
	}),
)

To override only some methods, embed tgbot.NoopTracer in your struct (see examples/downloadfile/main.go).

  • Probes – optional functions passed to tgbot.New with WithLivenessProbe / WithReadinessProbe. The endpoints respond 200 UP when the probe succeeds and 500 DOWN when it returns an error; when no probe is set they return an empty 200 OK.
bot, err := tgbot.New(
	"YOUR_TELEGRAM_TOKEN",
	tgbot.WithWebHookToken("my-secret-token"),
	tgbot.WithLivenessProbe(func(ctx context.Context) error { return nil }),
	tgbot.WithReadinessProbe(func(ctx context.Context) error { return nil }),
)

The HTTP handlers are at /live and /ready (see probes.go) and are only served in webhook mode.

Command registration

bot.AddMenuCommand("start", "Begin using the bot", func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
	operations.SendMessage(ctx, msg.ChatID, "Welcome!")
	return nil
})

bot.AddTextCommand("help", func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
	operations.SendMessage(ctx, msg.ChatID, "Help text, args: "+msg.Args)
	return nil
})
  • AddMenuCommand – also registers the command as a BotCommand; menu commands are published to Telegram when Start is called.
  • AddTextCommand – only matches the command (no menu entry).

A command matches when the message starts with a /command entity whose name has the registered command as a prefix. msg.Args contains the text after the command.

Catch-all handlers:

  • AddDefaultHandler – any update not matched by another handler.
  • AddDefaultTextHandler – any text message not matched by a command.
  • AddDefaultCallbackQueryHandler – all callback queries (msg.Data holds the callback data).

Messages & file download

Handlers receive a flattened tgbot.Message. msg.Type tells which fields are populated:

Type Fields
TypeText Text, Args
TypeCallbackQuery Data (plus Text of the original message, if accessible)
TypePayment Payment (IsSuccessful for a successful payment, IsCheckout for a pre-checkout query)
TypeDocument Document (FileID, FileName, FileSize)
TypePhoto Photo (all available sizes; LargestPhoto() returns the biggest one)

MessageID, ChatID, IsGroup and User are filled in for regular messages. For media messages Text holds the caption.

To download a file, resolve its file ID to a download URL with GetDownloadLink and fetch it over HTTP:

bot.AddDefaultHandler(func(ctx context.Context, msg tgbot.Message, operations tgbot.Operations) error {
	var fileID string

	switch msg.Type {
	case tgbot.TypeDocument:
		fileID = msg.Document.FileID
	case tgbot.TypePhoto:
		photo, ok := msg.LargestPhoto()
		if !ok {
			return errors.New("no photo sizes")
		}
		fileID = photo.FileID
	default:
		return nil
	}

	link, err := operations.GetDownloadLink(ctx, fileID)
	if err != nil {
		return fmt.Errorf("get download link: %w", err)
	}

	// download link with an HTTP GET request
	_ = link

	return nil
})

See examples/downloadfile/main.go for a complete example that saves files to disk.

Operations & HTTP endpoints

Handlers receive an tgbot.Operations value (implemented by *TGBot):

Method Signature Description
SendMessage SendMessage(ctx context.Context, chatID int64, msg string) Sends a text message; errors are logged.
DeleteMessage DeleteMessage(ctx context.Context, chatID int64, messageID int) Deletes a message; errors are logged.
GetDownloadLink GetDownloadLink(ctx context.Context, fileID string) (string, error) Returns a download URL for a document/photo file ID.

HTTP endpoints (webhook mode only):

Endpoint Description
GET /live 200 UP if the liveness probe succeeds, otherwise 500 DOWN.
GET /ready 200 UP if the readiness probe succeeds, otherwise 500 DOWN.

Development

Command What it does
make build go build – compiles the root package. Use go build ./... to also build the examples and CLI.
make test go test ./... – runs all package tests (there are none yet).
make bench go test -bench=. -benchmem ./... – runs benchmarks.
make lint Runs golangci-lint (v2.15.0, installed on first use into tools/bin/<version>/).
make fmt golangci-lint fmt – auto-format code.

Examples

Example Purpose
examples/echotracer/main.go Minimal bot that echoes incoming text, with a custom slog-based tracer.
examples/downloadfile/main.go Bot that saves incoming documents and photos to a downloads/ directory.
cmd/webhook/main.go CLI to manage webhooks (--set, --get, --remove). Uses a YAML config file and the github.com/go-telegram/bot low-level API.

All of them compile with go build ./... and can be run after setting a real Telegram token.

License

This project is released under the MIT License – see LICENSE for full text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Document added in v1.0.0

type Document struct {
	FileID   string
	FileName string
	FileSize int64
}

type Handler

type Handler func(ctx context.Context, msg Message, operations Operations) error

type Message added in v1.0.0

type Message struct {
	Type      Type
	MessageID int
	ChatID    int64
	IsGroup   bool
	User      User
	// for text message
	Text string
	Args string
	// for callback query
	Data     string
	Payment  Payment
	Document Document
	// available photo sizes
	Photo []PhotoSize
}

func (Message) LargestPhoto added in v1.0.0

func (m Message) LargestPhoto() (PhotoSize, bool)

LargestPhoto returns the photo size with the highest resolution. The second return value is false if the message has no photo.

type Middleware

type Middleware func(next Handler) Handler

type NewTracerFn

type NewTracerFn func() Tracer

type NoopTracer

type NoopTracer struct {
}

func NewNoopTracer

func NewNoopTracer() NoopTracer

NewNoopTracer returns a no-op Tracer implementation that performs no tracing actions.

func (NoopTracer) After

func (n NoopTracer) After(ctx context.Context)

func (NoopTracer) Before

func (n NoopTracer) Before(ctx context.Context, pattern string, msg Message) context.Context

func (NoopTracer) OnError

func (n NoopTracer) OnError(ctx context.Context, err error)

func (NoopTracer) OnSuccess

func (n NoopTracer) OnSuccess(ctx context.Context)

type Operations added in v1.0.0

type Operations interface {
	SendMessage(ctx context.Context, chatID int64, msg string)
	DeleteMessage(ctx context.Context, chatID int64, messageID int)
	GetDownloadLink(ctx context.Context, fileID string) (string, error)
}

type Option

type Option func(o *options)

func WithLivenessProbe

func WithLivenessProbe(probe Probe) Option

WithLivenessProbe sets the probe function used for the liveness HTTP health check endpoint.

func WithNewTracerFn

func WithNewTracerFn(tracerFn NewTracerFn) Option

WithNewTracerFn sets the factory function used to create a new Tracer for each handler invocation.

func WithReadTimeout

func WithReadTimeout(timeout time.Duration) Option

WithReadTimeout sets the read timeout for the HTTP server used in webhook mode.

func WithReadinessProbe

func WithReadinessProbe(probe Probe) Option

WithReadinessProbe sets the probe function used for the readiness HTTP health check endpoint.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout sets the maximum duration to wait for the HTTP server to shut down gracefully.

func WithWebHookToken

func WithWebHookToken(token string) Option

WithWebHookToken sets the webhook secret token used to validate incoming webhook requests.

func WithWorkers added in v1.1.0

func WithWorkers(workers int) Option

WithWorkers allows setting the number of parallel workers for processing.

func WithWriteTimeout

func WithWriteTimeout(timeout time.Duration) Option

WithWriteTimeout sets the write timeout for the HTTP server used in webhook mode.

type Payment

type Payment struct {
	IsSuccessful   bool
	IsCheckout     bool
	ID             string
	InvoicePayload string
	Currency       string
	TotalAmount    int
}

type PhotoSize added in v1.0.0

type PhotoSize struct {
	FileID   string
	Width    int
	Height   int
	FileSize int64
}

func (PhotoSize) Size added in v1.0.0

func (p PhotoSize) Size() int

type Probe

type Probe func(ctx context.Context) error

type TGBot

type TGBot struct {
	// contains filtered or unexported fields
}

func New

func New(
	token string,
	opts ...Option,
) (*TGBot, error)

New creates a new TGBot instance with the given Telegram bot token and options. It initializes the bot API and applies all provided options. Returns an error if the bot API creation fails.

func (*TGBot) AddDefaultCallbackQueryHandler

func (t *TGBot) AddDefaultCallbackQueryHandler(h Handler)

AddDefaultCallbackQueryHandler registers a handler for all callback query updates.

func (*TGBot) AddDefaultHandler

func (t *TGBot) AddDefaultHandler(h Handler)

AddDefaultHandler sets the handler that is called when no other command handler matches an incoming message.

func (*TGBot) AddDefaultTextHandler

func (t *TGBot) AddDefaultTextHandler(h Handler)

AddDefaultTextHandler registers a handler for all text messages that do not match any registered command. The handler is called with the full message text as the pattern.

func (*TGBot) AddMenuCommand

func (t *TGBot) AddMenuCommand(command string, description string, handler Handler)

AddMenuCommand registers a bot command with a description in the bot's menu. The command is also registered as a handler for incoming messages matching the command.

func (*TGBot) AddMiddleware

func (t *TGBot) AddMiddleware(m Middleware)

AddMiddleware adds a middleware function to the bot's middleware chain. Middlewares are applied in the order they were added.

func (*TGBot) AddTextCommand

func (t *TGBot) AddTextCommand(command string, handler Handler)

AddTextCommand registers a command handler without a menu description. The handler is triggered when a message starts with the given command.

func (*TGBot) DeleteMessage

func (t *TGBot) DeleteMessage(
	ctx context.Context,
	chatID int64,
	messageID int,
)

DeleteMessage deletes a message from a chat by its ID. Errors are logged but not returned to the caller.

func (t *TGBot) GetDownloadLink(
	ctx context.Context,
	fileID string,
) (string, error)

func (*TGBot) SendMessage

func (t *TGBot) SendMessage(ctx context.Context, chatID int64, msg string)

SendMessage sends a text message to the specified chat. Errors are logged but not returned to the caller.

func (*TGBot) Start

func (t *TGBot) Start(ctx context.Context) error

Start initializes the bot and begins processing updates. If a webhook token was configured, it starts the webhook server and HTTP listener. Otherwise, it starts the bot in long-polling mode. Returns an error if starting the bot or webhook server fails.

type Tracer

type Tracer interface {
	Before(ctx context.Context, pattern string, msg Message) context.Context
	OnSuccess(ctx context.Context)
	OnError(ctx context.Context, err error)
	After(ctx context.Context)
}

type Type added in v1.0.0

type Type int
const (
	TypeInvalid Type = iota
	TypeText
	TypeCallbackQuery
	TypePayment
	TypeDocument
	TypePhoto
)

type User

type User struct {
	FirstName string
	LastName  string
	Username  string
}

func (User) FullName

func (u User) FullName() string

FullName returns the full name of the user by combining the first and last name. If only one of the names is set, it returns that name. If both are empty, it returns an empty string.

Directories

Path Synopsis
cmd
webhook command
examples
downloadfile command
echotracer command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL