telegram

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 13 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

This section is empty.

Variables

This section is empty.

Functions

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.

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
  • 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. Returns a map containing "uid" (user ID) and "subject" (username) if a user is found.

func MarshalData

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

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". Returns the formatted string suitable for use in Telegram callback queries.

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 respects the RetryAfter duration from Telegram's error response and retries up to maxRetries times. Returns an error if max retries are exceeded or if 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. For regular messages, it sends a new message. The function automatically chooses between text and photo messages based on media presence.

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.

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.

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. It removes any existing webhook and starts listening for updates using long polling.

func (*Bot) Update

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

Update applies additional configuration options to the underlying bot client.

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

NewButton creates an inline keyboard button with text, callback route, and data. The route and data are marshaled together to form the 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 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 using metadata. The extracted data becomes available to downstream handlers.

func NewGroupMessageFilterMiddleware

func NewGroupMessageFilterMiddleware(b *bot.Bot, 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 instance 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 from the same message are processed only once, based on the message ID as the deduplication key.

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