Documentation
¶
Index ¶
- Constants
- Variables
- func AuthSubject(ctx context.Context) (string, bool)
- func AuthUserID(ctx context.Context) (int64, bool)
- 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, error)
- 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 RetryOnTooManyRequestsErrorContext(ctx context.Context, 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 BroadcastError
- type BroadcastOption
- type Button
- type Config
- type ContextKey
- type ErrorHandlerFunc
- type HandlerFunc
- type Message
- type MessageSender
- type MethodExtraData
- type MiddlewareFunc
- type Option
- func AppendBotOptions(opt ...bot.Option) Option
- func AppendMiddlewares(middlewares ...MiddlewareFunc) Option
- func WithAuthExtractor(extractor AuthExtractorFunc) Option
- func WithDefaultHandler(fn bot.HandlerFunc) Option
- func WithDeleteWebhookOnStart(enabled bool) Option
- func WithErrorHandler(fn ErrorHandlerFunc) Option
- type RouteMap
- type RouteMapBuilder
- type Update
Constants ¶
const MaxCallbackDataLength = 64
MaxCallbackDataLength is the maximum payload size, in bytes, that Telegram accepts for inline keyboard callback data.
Variables ¶
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
AuthSubject returns the authentication subject (username) extracted from the update, and whether it was present.
func AuthUserID ¶ added in v0.0.3
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 ¶
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 ¶
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 ¶
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 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 ¶
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 (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 ¶
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. 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 ¶
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 ¶
SendMessage sends a message in response to an update using the bot's client.
func (*Bot) Start ¶
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.
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 ¶
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. 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 ¶
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 ¶
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. 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 ¶
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
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 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.