telegram

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Sep 19, 2026 License: MIT Imports: 14 Imported by: ? 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.

Documentation

Index

Constants

View Source
const MaxCallbackDataLength = 64

MaxCallbackDataLength is the maximum payload size, in bytes, that Telegram accepts for inline keyboard callback data.

Variables

View Source
var (
	ErrCallbackDataTooLong = errors.New("telegram: callback data exceeds 64 bytes")
)

ErrCallbackDataTooLong is returned when the marshaled callback data exceeds MaxCallbackDataLength.

Functions

func AuthSubject added in v0.0.3

func AuthSubject(ctx context.Context) (string, bool)

AuthSubject returns the authentication subject (username) extracted from the update, and whether it was present.

func AuthUserID added in v0.0.3

func AuthUserID(ctx context.Context) (int64, bool)

AuthUserID returns the authenticated user ID extracted from the update, and whether it was present.

func BroadcastMessage

func BroadcastMessage[T any](ctx context.Context, b *bot.Bot, data []T, rateLimiter *rate.Limiter, send func(context.Context, *bot.Bot, T) error, options ...BroadcastOption) error

BroadcastMessage sends messages to multiple recipients with rate limiting and error handling. It processes each item in the data slice through the provided send function, respecting the rate limiter and reporting progress through optional callbacks. Unless WithTerminalOnSendError is set, every item is attempted and a *BroadcastError summarizing the failures is returned when any send fails.

Type parameter T represents the data type for each broadcast target.

Parameters:

  • ctx: Context for cancellation
  • b: Bot instance for sending messages
  • data: Slice of data items to process
  • rateLimiter: Rate limiter to control send frequency; must not be nil
  • send: Function to send message for each data item
  • options: Optional configuration for progress tracking and error handling

func DefaultAuthExtractor

func DefaultAuthExtractor(ctx context.Context, update *Update) (map[string]any, error)

DefaultAuthExtractor is the default implementation for extracting authentication data from updates. It extracts user ID and username from either message or callback query updates. The values are only advisory: they identify who sent the update but carry no proof of authenticity. Security-sensitive flows must validate the signature (for example with tmaauth) and authorize on the server side.

func MarshalData

func MarshalData[T any](route string, data T) (string, error)

MarshalData encodes a route and typed data into Telegram callback query format. The data is compressed using JSON compression and formatted as "route:compressed_json_data". The route must be non-empty and must not contain ":", and the resulting string must fit into the 64 bytes Telegram allows for callback data.

func NewBytesInputFile

func NewBytesInputFile(name string, data []byte) models.InputFile

NewBytesInputFile creates an InputFile from a byte slice for file uploads. The name parameter specifies the filename that will be used in Telegram.

func NewRecoveryMiddleware

func NewRecoveryMiddleware() bot.Middleware

NewRecoveryMiddleware creates a middleware that recovers from panics in bot handlers. It logs any panic that occurs during update processing and prevents the bot from crashing.

func NewStringInputFile

func NewStringInputFile(url string) models.InputFile

NewStringInputFile creates an InputFile from a URL string for media sharing. This is used when referencing existing media by URL or file ID.

func RetryOnTooManyRequestsError

func RetryOnTooManyRequestsError(maxRetries int, send func() error) error

RetryOnTooManyRequestsError implements automatic retry logic for Telegram rate limit errors. It is a convenience wrapper around RetryOnTooManyRequestsErrorContext with a background context.

func RetryOnTooManyRequestsErrorContext added in v0.0.3

func RetryOnTooManyRequestsErrorContext(ctx context.Context, maxRetries int, send func() error) error

RetryOnTooManyRequestsErrorContext implements automatic retry logic for Telegram rate limit errors. It respects the RetryAfter duration from Telegram's error response (capped at one minute) and retries until ctx is cancelled or maxRetries sends have failed. Returns ctx.Err() when the context is cancelled while waiting, or an error if max retries are exceeded or a non-rate-limit error occurs.

func SendErrorMessage

func SendErrorMessage(ctx context.Context, b *bot.Bot, update *Update, err error)

SendErrorMessage sends an error message to the user based on the update type. For regular messages, it sends a new message with the error text. For callback queries, it shows the error in a popup using AnswerCallbackQuery.

func SendMessage

func SendMessage(ctx context.Context, b *bot.Bot, update *Update, m *Message) error

SendMessage sends or edits a message based on the update type and content. For callback queries it edits the original message (when it is still accessible), for regular messages it sends a new message. The function automatically chooses between text, caption and media edits depending on the new content and the original message type.

func UnmarshalData

func UnmarshalData[T any](data string) (string, *T, error)

UnmarshalData decodes Telegram callback query data into a route and typed data structure. The input data should be formatted as "route:compressed_json_data". Returns the route string, the unmarshaled data of type T, and any error encountered. This is commonly used for handling Telegram bot callback queries with structured data.

func WithMiddleware

func WithMiddleware(h HandlerFunc, e ErrorHandlerFunc, middleware ...MiddlewareFunc) bot.HandlerFunc

WithMiddleware wraps a HandlerFunc with middleware chain and error handling. It applies middleware in reverse order and converts the result to a bot.HandlerFunc. If the wrapped handler returns an error, it calls the provided error handler.

Types

type AuthExtractor

type AuthExtractor interface {
	ExtractorAuth(ctx context.Context, update *Update) (map[string]any, error)
}

AuthExtractor defines the interface for extracting authentication information from Telegram updates. Implementations should extract user identity and authorization data from the update context.

type AuthExtractorFunc

type AuthExtractorFunc func(ctx context.Context, update *Update) (map[string]any, error)

AuthExtractorFunc is a function type that implements the AuthExtractor interface. It allows using functions as AuthExtractor implementations.

func (AuthExtractorFunc) ExtractorAuth

func (f AuthExtractorFunc) ExtractorAuth(ctx context.Context, update *Update) (map[string]any, error)

ExtractorAuth implements the AuthExtractor interface by calling the function.

type Bot

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

Bot represents a Telegram bot application with routing and middleware support. It wraps the underlying bot client and provides additional functionality for handling messages, authentication, and error processing.

func NewApp

func NewApp(config Config, opts ...Option) (*Bot, error)

NewApp creates a new Telegram bot application with the provided configuration and options. It initializes the bot client, applies middleware, and sets up default handlers. Returns an error if the bot token is invalid or client initialization fails.

func (*Bot) API

func (b *Bot) API() *bot.Bot

API returns the underlying Telegram bot client for direct API access.

func (*Bot) BindCallback

func (b *Bot) BindCallback(route string, handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)

BindCallback registers a handler for callback query data with a specific route prefix. The route is used as a prefix for matching callback query data (e.g., "menu:" matches "menu:item1").

func (*Bot) BindCommand

func (b *Bot) BindCommand(command string, handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)

BindCommand registers a handler for a specific bot command (e.g., "/start", "/help"). The command parameter should not include the leading slash, as it will be added automatically. Commands match on the first word of a message: "/start" matches "/start" and "/start@BotName", but not "/startup".

func (*Bot) BindNoRoute

func (b *Bot) BindNoRoute(handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)

BindNoRoute sets the default handler for messages that don't match any specific route. This handler is called when no command or callback query handlers match the incoming update.

func (*Bot) BindRoute

func (b *Bot) BindRoute(route RouteMap, extra func(string) *MethodExtraData, operations []string, middlewares ...MiddlewareFunc)

BindRoute registers multiple handlers based on a route map and method metadata. It automatically binds commands and callback queries based on the provided operation metadata.

func (*Bot) Close

func (b *Bot) Close(ctx context.Context) error

Close gracefully shuts down the bot and releases resources. It stops the update polling and closes the underlying bot client connection. Close is idempotent: calling it again after a successful close is a no-op.

func (*Bot) SendMessage

func (b *Bot) SendMessage(ctx context.Context, update *Update, m *Message) error

SendMessage sends a message in response to an update using the bot's client.

func (*Bot) Start

func (b *Bot) Start(ctx context.Context) error

Start begins the bot's update polling and message processing. Unless disabled with WithDeleteWebhookOnStart(false), it first removes any existing webhook so a leftover webhook cannot steal updates, then starts long polling. It blocks until ctx is cancelled. The webhook removal error, if any, is returned instead of being swallowed.

func (*Bot) Update

func (b *Bot) Update(options ...bot.Option)

Update applies additional configuration options to the underlying bot client.

type BroadcastError added in v0.0.3

type BroadcastError struct {
	Total   int
	Failed  int
	Success int
	Err     error // The first send error encountered
}

BroadcastError reports a broadcast that finished with some failed sends.

func (*BroadcastError) Error added in v0.0.3

func (e *BroadcastError) Error() string

func (*BroadcastError) Unwrap added in v0.0.3

func (e *BroadcastError) Unwrap() error

type BroadcastOption

type BroadcastOption func(*broadcastOptions)

BroadcastOption defines a function type for configuring broadcast operations.

func WithProgress

func WithProgress(progress func(int, int, int)) BroadcastOption

WithProgress sets a progress callback function for broadcast operations. The callback receives (current index, error count, total count) during broadcasting.

func WithTerminalOnSendError

func WithTerminalOnSendError(terminalOnSendError bool) BroadcastOption

WithTerminalOnSendError configures whether broadcasting should stop on the first send error. If true, broadcasting terminates immediately on any send failure.

type Button

Button is an alias for Telegram's inline keyboard button.

func NewButton

func NewButton[T any](text, route string, data T) (Button, error)

NewButton creates an inline keyboard button with text, callback route, and data. The route and data are marshaled together to form the callback data. The returned error is non-nil when the route is empty or contains ":", or when the marshaled payload exceeds the 64 bytes Telegram allows for callback data.

func NewURLButton

func NewURLButton(text, url string) Button

NewURLButton creates an inline keyboard button that opens a URL when pressed.

type Config

type Config struct {
	Token string `json:"token" yaml:"token"`
}

Config defines the configuration parameters for the Telegram bot.

type ContextKey added in v0.0.3

type ContextKey string

ContextKey is the type of the context keys used by this package to carry per-update values (see AuthUserIDKey and AuthSubjectKey). Keeping a dedicated type avoids collisions with unrelated string keys in the same context chain.

const (
	// AuthUserIDKey is the context key under which the authenticated user ID is stored.
	AuthUserIDKey ContextKey = "telegram.auth.uid"
	// AuthSubjectKey is the context key under which the authentication subject (username) is stored.
	AuthSubjectKey ContextKey = "telegram.auth.subject"
)

Authentication context keys.

type ErrorHandlerFunc

type ErrorHandlerFunc = func(ctx context.Context, bot *bot.Bot, update *Update, err error)

ErrorHandlerFunc defines a function type for handling errors that occur during update processing. It receives the error along with the bot instance and update that caused the error.

type HandlerFunc

type HandlerFunc = func(ctx context.Context, update *Update) error

HandlerFunc defines a function type for handling Telegram bot updates. It processes an Update and returns an error if processing fails.

type Message

type Message struct {
	Text      string                          // Message text content
	Media     models.InputFile                // Optional media attachment (photo, document, etc.)
	ParseMode models.ParseMode                // Text parsing mode (HTML, Markdown, etc.)
	Button    [][]models.InlineKeyboardButton // Inline keyboard layout as rows of buttons
}

Message represents a complete message that can be sent or edited in Telegram. It supports text content, media attachments, formatting, and inline keyboards.

type MessageSender

type MessageSender = func(ctx context.Context, request *Update, msg *Message) error

MessageSender defines a function that sends messages in response to updates.

type MethodExtraData

type MethodExtraData struct {
	Command       string // The command extracted from the update (e.g., "/start")
	CallbackQuery string // The callback query data from inline keyboard interactions
}

MethodExtraData holds additional routing information extracted from Telegram updates. It provides convenient access to command and callback query data for request handling.

func NewMethodExtraData

func NewMethodExtraData(raw map[string]string) *MethodExtraData

NewMethodExtraData creates a new MethodExtraData instance from a raw string map. This is typically used during request processing to extract routing information.

type MiddlewareFunc

type MiddlewareFunc = func(next HandlerFunc) HandlerFunc

MiddlewareFunc defines a function type for creating middleware that wraps HandlerFunc. It takes a HandlerFunc and returns a wrapped HandlerFunc with additional functionality.

func NewAuthMiddleware

func NewAuthMiddleware(auth AuthExtractor) MiddlewareFunc

NewAuthMiddleware creates a middleware that extracts authentication information from updates. It uses the provided AuthExtractor to get user data and injects it into the request context. The extracted data becomes available to downstream handlers.

func NewGroupMessageFilterMiddleware

func NewGroupMessageFilterMiddleware(b botInfoFetcher, trimMention bool, infoExpire time.Duration) MiddlewareFunc

NewGroupMessageFilterMiddleware creates a middleware that filters group messages based on bot mentions. It only processes group messages where the bot is explicitly mentioned through @username, replies, or text mentions. The middleware caches bot information to reduce API calls and optionally removes mention text from the message content.

Parameters:

  • b: The bot client used to retrieve bot information
  • trimMention: Whether to remove mention text from processed messages
  • infoExpire: Duration to cache bot information before refreshing

func NewSingleFlightMiddleware

func NewSingleFlightMiddleware() MiddlewareFunc

NewSingleFlightMiddleware creates a middleware that prevents duplicate callback query processing. It uses singleflight to ensure that multiple identical callback queries (same message and same button data) are processed only once.

type Option

type Option = func(*options)

Option defines a function type for configuring bot application options.

func AppendBotOptions

func AppendBotOptions(opt ...bot.Option) Option

AppendBotOptions adds additional options to the underlying bot client configuration. These options will be passed directly to the bot.New() constructor.

func AppendMiddlewares

func AppendMiddlewares(middlewares ...MiddlewareFunc) Option

AppendMiddlewares adds middleware functions to the bot application. Middleware will be applied to all handlers in the order they are provided.

func WithAuthExtractor

func WithAuthExtractor(extractor AuthExtractorFunc) Option

WithAuthExtractor sets a custom authentication extractor for the bot. The extractor will be used to extract user information from incoming updates.

func WithDefaultHandler

func WithDefaultHandler(fn bot.HandlerFunc) Option

WithDefaultHandler sets a custom handler for unmatched routes. This handler will be called when no specific command or callback query handler matches.

func WithDeleteWebhookOnStart added in v0.0.3

func WithDeleteWebhookOnStart(enabled bool) Option

WithDeleteWebhookOnStart controls whether Start deletes any previously configured webhook before beginning long polling. It is enabled by default so a leftover webhook cannot steal updates; disable it when a webhook is managed out of band or when Start is used alongside webhook mode.

func WithErrorHandler

func WithErrorHandler(fn ErrorHandlerFunc) Option

WithErrorHandler sets a custom error handler for bot operations. The error handler will be called whenever a handler function returns an error.

type RouteMap

type RouteMap = map[string]func(ctx context.Context, request *Update) error

RouteMap maps operation names to their corresponding handler functions.

type RouteMapBuilder

type RouteMapBuilder[S any, D any] = func(srv S, codec D, sender MessageSender) RouteMap

RouteMapBuilder defines a function that builds a RouteMap from a service, codec, and message sender.

type Update

type Update = models.Update

Update is an alias for the Telegram bot library's Update type. It represents an incoming update from the Telegram Bot API.

Jump to

Keyboard shortcuts

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