Documentation
¶
Index ¶
- func BroadcastMessage[T any](ctx context.Context, b *bot.Bot, data []T, rateLimiter *rate.Limiter, ...) error
- func DefaultAuthExtractor(ctx context.Context, update *Update) (map[string]any, error)
- func MarshalData[T any](route string, data T) string
- func NewBytesInputFile(name string, data []byte) models.InputFile
- func NewRecoveryMiddleware() bot.Middleware
- func NewStringInputFile(url string) models.InputFile
- func RetryOnTooManyRequestsError(maxRetries int, send func() error) error
- func SendErrorMessage(ctx context.Context, b *bot.Bot, update *Update, err error)
- func SendMessage(ctx context.Context, b *bot.Bot, update *Update, m *Message) error
- func UnmarshalData[T any](data string) (string, *T, error)
- func WithMiddleware(h HandlerFunc, e ErrorHandlerFunc, middleware ...MiddlewareFunc) bot.HandlerFunc
- type AuthExtractor
- type AuthExtractorFunc
- type Bot
- func (b *Bot) API() *bot.Bot
- func (b *Bot) BindCallback(route string, handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)
- func (b *Bot) BindCommand(command string, handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)
- func (b *Bot) BindNoRoute(handlerFunc HandlerFunc, middlewares ...MiddlewareFunc)
- func (b *Bot) BindRoute(route RouteMap, extra func(string) *MethodExtraData, operations []string, ...)
- func (b *Bot) Close(ctx context.Context) error
- func (b *Bot) SendMessage(ctx context.Context, update *Update, m *Message) error
- func (b *Bot) Start(ctx context.Context) error
- func (b *Bot) Update(options ...bot.Option)
- type BroadcastOption
- type Button
- type Config
- type ErrorHandlerFunc
- type HandlerFunc
- type Message
- type MessageSender
- type MethodExtraData
- type MiddlewareFunc
- type Option
- type RouteMap
- type RouteMapBuilder
- type Update
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
Close gracefully shuts down the bot and releases resources. It stops the update polling and closes the underlying bot client connection.
func (*Bot) SendMessage ¶
SendMessage sends a message in response to an update using the bot's 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 ¶
type Button = models.InlineKeyboardButton
Button is an alias for Telegram's inline keyboard button.
func NewButton ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 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.