tgbot

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 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, idiomatic wrapper around the official Telegram Bot API (github.com/go-telegram/bot). It adds convenience methods, middleware support, HTTP health‑check endpoints, and configurable tracing/profiling hooks.

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)
Middleware How to plug custom middleware
Tracing & probes Tracer interface, no‑op implementation, liveness/readiness endpoints
Command registration AddMenuCommand, AddTextCommand, default / text / callback handlers
HTTP helpers SendMessage, DeleteMessage, /live, /ready
Development Building, testing, linting, and releasing
Examples Echo‑tracer bot 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, timeouts, tracers, probes).
  • Run in long‑polling mode (bot.Start(ctx)) or webhook mode (bot.StartWebhook(ctx) + HTTP server).
  • Register commands that automatically appear in the bot’s menu and match incoming updates.
  • Add middleware that runs for every update (e.g. logging, auth, rate‑limiting).
  • Attach a tracer (or a no‑op tracer) to log before/after each handler.
  • Expose /live and /ready health‑check endpoints useful for Kubernetes / Docker.
  • Load configuration from a YAML file (the webhook example uses github.com/jinzhu/configor).

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 Choose at runtime via WithWebHookToken or the isWebHook() guard.
Middleware chain AddMiddleware / applyMiddleware; middleware run in reverse‑add order.
Tracer interface Tracer.Before/OnSuccess/OnError/After; NewNoopTracer included.
Liveness / readiness probes /live and /ready HTTP handlers; probe functions are optional.
Command registration AddMenuCommand (adds to BotCommand list) & AddTextCommand (matches text).
Default / text / callback handlers AddDefaultHandler, AddDefaultTextHandler, AddDefaultCallbackQueryHandler.
Helper methods SendMessage, DeleteMessage, setMyCommands.
YAML config loading via github.com/jinzhu/configor (webhook CLI).
Go 1.26+ compatible Module go.mod declares go 1.26.6.
Standard tooling make build, make test, make vet, make lint (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",
		tgbot.WithNewTracerFn(func() tgbot.Tracer {
			return tgbot.NewTracer(logger) // your own tracer
		}),
	)
	if err != nil {
		logger.Error("create bot", slog.String("error", err.Error()))
		os.Exit(1)
	}

	bot.AddDefaultHandler(func(ctx context.Context, msg tgbot.BotMessage, sender tgbot.MessageSender) error {
		_, err := sender.SendMessage(ctx, msg.ChatID, "You said: "+msg.Text)
		return err
	})

	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

Quick start – Webhook

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",
		tgbot.WithWebHookToken("my-secret-token"),   // required for webhook validation
		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)
	}

	// HTTP mux that also serves /live and /ready
	httpMux := ... // your mux, see start.go for the built‑in pattern

	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 will listen on :80 (configurable via WithReadTimeout/WithWriteTimeout).

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

Middleware

func LoggingMiddleware(next tgbot.Handler) tgbot.Handler {
	return func(ctx context.Context, msg tgbot.BotMessage, sender tgbot.MessageSender) error {
		logger := slog.FromContext(ctx)
		logger.Info("incoming update", slog.String("text", msg.Text))
		return next(ctx, msg, sender)
	}
}

Register it:

bot.AddMiddleware(LoggingMiddleware)

Middleware are applied last‑in‑first‑out (the most recently added runs closest to the handler).

Tracing & probes

  • Tracer – implements Before, OnSuccess, OnError, After. The example 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.BotMessage) 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) { /* … */ }
  • Probes – optional functions passed with WithLivenessProbe / WithReadinessProbe. When nil the endpoints simply return 200 OK without checking anything.
bot.WithLivenessProbe(func(ctx context.Context) error { return nil })
bot.WithReadinessProbe(func(ctx context.Context) error { return nil })

The HTTP handlers are at /live and /ready (see probes.go).

Command registration

bot.AddMenuCommand("start", "Begin using the bot")
bot.AddTextCommand("help", func(ctx context.Context, msg tgbot.BotMessage, sender tgbot.MessageSender) error {
	_, err := sender.SendMessage(ctx, msg.ChatID, "Help text")
	return err
})
  • AddMenuCommand – also registers the command as a BotCommand visible in Telegram's UI.
  • AddTextCommand – only matches the command text (no menu entry).

You can also set a default handler that catches any update not matched by a registered command (AddDefaultHandler).

HTTP helpers

Method Signature Description
SendMessage func (t *TGBot) SendMessage(ctx context.Context, chatID int64, msg string) Sends a text message; errors are logged.
DeleteMessage func (t *TGBot) DeleteMessage(ctx, chatID int64, messageID int) Deletes a message; errors are logged.
/live http.HandlerFunc Returns 200 OK if the liveness probe succeeds, otherwise 500.
/ready http.HandlerFunc Returns 200 OK if the readiness probe succeeds.

Development

Command What it does
make build go build ./… – compiles the library and examples.
make test go test ./… – runs all package tests.
make vet go vet ./… – static analysis.
make lint Runs golangci-lint (v2.12.2) from tools/bin/.
make fmt golangci-lint fmt – auto‑format code.

The Makefile also defines the tag APP_TAG := 0.5.2 (used for release artefacts).

Examples

Example Purpose
examples/echotracer/main.go Minimal bot that echoes incoming text, with a custom slog‑based tracer.
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.

Both examples compile with go build ./… and can be run directly 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 BotMessage

type BotMessage struct {
	MessageID int
	ChatID    int64
	IsGroup   bool
	User      User
	// for text message
	Text string
	// for callback query
	Data    string
	Payment Payment
	Args    string
}

type Handler

type Handler func(ctx context.Context, msg BotMessage, sender MessageSender) error

type MessageSender

type MessageSender interface {
	SendMessage(ctx context.Context, chatID int64, msg string)
	DeleteMessage(ctx context.Context, chatID int64, messageID int)
}

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 BotMessage) 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 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 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 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 (*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 BotMessage) context.Context
	OnSuccess(ctx context.Context)
	OnError(ctx context.Context, err error)
	After(ctx context.Context)
}

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
echotracer command

Jump to

Keyboard shortcuts

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