diff --git a/bot.go b/bot.go index 15087c1..566cf9e 100644 --- a/bot.go +++ b/bot.go @@ -30,7 +30,9 @@ type Middleware func(next HandlerFunc) HandlerFunc type HandlerFunc func(ctx context.Context, bot *Bot, update *models.Update) type MatchFunc func(update *models.Update) bool -// Bot represents Telegram Bot main object +// Bot is a Telegram bot client. It receives updates by polling or through a +// webhook, runs middlewares and handlers for them, and provides methods for +// Telegram API calls. type Bot struct { lastUpdateID int64 diff --git a/common.go b/common.go index 4010ea7..0888469 100644 --- a/common.go +++ b/common.go @@ -13,11 +13,11 @@ import ( "time" ) -// escape special symbols in text for MarkdownV2 parse mode - -var shouldBeEscaped = "_*[]()~`>#+-=|{}.!" +const shouldBeEscaped = "_*[]()~`>#+-=|{}.!" // EscapeMarkdown escapes plain text for Telegram MarkdownV2 syntax. +// Use it for user input and other dynamic text. +// For example, EscapeMarkdown("Hello_world") returns "Hello\_world". func EscapeMarkdown(s string) string { var result []rune for _, r := range s { @@ -29,7 +29,9 @@ func EscapeMarkdown(s string) string { return string(result) } -// EscapeMarkdownUnescaped escapes unescaped special symbols for Telegram Markdown v2 syntax +// EscapeMarkdownUnescaped escapes special symbols that are not already escaped +// for Telegram MarkdownV2 syntax. Use it for text that may already contain +// MarkdownV2 escapes. func EscapeMarkdownUnescaped(s string) string { var result []rune var escaped bool @@ -48,10 +50,6 @@ func EscapeMarkdownUnescaped(s string) string { return string(result) } -// log functions - -// random string generator - const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const ( diff --git a/handlers.go b/handlers.go index 083692d..734a884 100644 --- a/handlers.go +++ b/handlers.go @@ -7,40 +7,51 @@ import ( "github.com/go-telegram/bot/models" ) +// HandlerType selects the update data that a handler matches against. type HandlerType int const ( - HandlerTypeMessageText HandlerType = iota - HandlerTypeCallbackQueryData - HandlerTypeCallbackQueryGameShortName - HandlerTypePhotoCaption - HandlerTypeInlineQuery - HandlerTypeWidgetQueryData - HandlerTypeSharedWidgetQueryData + HandlerTypeMessageText HandlerType = iota // Text of Update.Message + HandlerTypeCallbackQueryData // Data of Update.CallbackQuery + HandlerTypeCallbackQueryGameShortName // GameShortName of Update.CallbackQuery + HandlerTypePhotoCaption // Caption of Update.Message, for any message type + HandlerTypeInlineQuery // Query of Update.InlineQuery + HandlerTypeWidgetQueryData // Data of Update.WidgetQuery + HandlerTypeSharedWidgetQueryData // Data of Update.SharedWidgetQuery ) +// MatchType defines how a handler pattern is compared with the update data. type MatchType int const ( - MatchTypeExact MatchType = iota - MatchTypePrefix - MatchTypeContains + MatchTypeExact MatchType = iota // Data equals pattern + MatchTypePrefix // Data starts with pattern + MatchTypeContains // Data contains pattern + // MatchTypeCommand matches a bot command anywhere in a message text or + // caption, so it works only with HandlerTypeMessageText and + // HandlerTypePhotoCaption. Specify the command without the slash, such as + // "start". It also matches /start@bot_username once GetMe has succeeded. MatchTypeCommand + // MatchTypeCommandStartOnly is like MatchTypeCommand, but the command must + // be at the start of the text or caption. MatchTypeCommandStartOnly - matchTypeRegexp - matchTypeFunc + // Internal match types (not for public use) + matchTypeRegexp // Regular expression matching (use RegisterHandlerRegexp) + matchTypeFunc // Custom function matching (use RegisterHandlerMatchFunc) ) +// handler is a registered update handler with its matching rules. type handler struct { - id string - handlerType HandlerType - matchType MatchType - handler HandlerFunc - - pattern string - re *regexp.Regexp - matchFunc MatchFunc + id string // Unique handler identifier for registration/unregistration + handlerType HandlerType // Type of content to extract from update + matchType MatchType // How to match extracted content against pattern + handler HandlerFunc // Function to execute when match is found + + // Pattern matching fields (used based on matchType) + pattern string // String pattern for basic matching + re *regexp.Regexp // Compiled regex for regexp matching + matchFunc MatchFunc // Custom function for function-based matching } // match reports whether the handler accepts update. botUsername is the bot's @@ -205,6 +216,9 @@ func (h handler) isCommand(command, botUsername string) bool { return addressed && name == h.pattern && strings.EqualFold(target, botUsername) } +// RegisterHandlerMatchFunc registers f for updates accepted by matchFunc. +// Handlers are checked in registration order, and only the first match runs. +// Middlewares in m wrap f. Returns an ID that can be passed to UnregisterHandler. func (b *Bot) RegisterHandlerMatchFunc(matchFunc MatchFunc, f HandlerFunc, m ...Middleware) string { b.handlersMx.Lock() defer b.handlersMx.Unlock() @@ -223,6 +237,10 @@ func (b *Bot) RegisterHandlerMatchFunc(matchFunc MatchFunc, f HandlerFunc, m ... return id } +// RegisterHandlerRegexp registers f for updates whose data, selected by +// handlerType, matches re. Handlers are checked in registration order, and only +// the first match runs. Middlewares in m wrap f. Returns an ID that can be +// passed to UnregisterHandler. func (b *Bot) RegisterHandlerRegexp(handlerType HandlerType, re *regexp.Regexp, f HandlerFunc, m ...Middleware) string { b.handlersMx.Lock() defer b.handlersMx.Unlock() @@ -249,6 +267,10 @@ func (b *Bot) RegisterHandlerInlineQuery(f HandlerFunc, m ...Middleware) string return b.RegisterHandler(HandlerTypeInlineQuery, "", MatchTypePrefix, f, m...) } +// RegisterHandler registers f for updates whose data, selected by handlerType, +// matches pattern according to matchType. Handlers are checked in registration +// order, and only the first match runs. Middlewares in m wrap f. Returns an ID +// that can be passed to UnregisterHandler. func (b *Bot) RegisterHandler(handlerType HandlerType, pattern string, matchType MatchType, f HandlerFunc, m ...Middleware) string { b.handlersMx.Lock() defer b.handlersMx.Unlock() @@ -268,6 +290,7 @@ func (b *Bot) RegisterHandler(handlerType HandlerType, pattern string, matchType return id } +// UnregisterHandler removes the handler with the given ID. An unknown ID is ignored. func (b *Bot) UnregisterHandler(id string) { b.handlersMx.Lock() defer b.handlersMx.Unlock() diff --git a/options.go b/options.go index 098cff9..fec0a1f 100644 --- a/options.go +++ b/options.go @@ -7,73 +7,86 @@ import ( // Option is a function that configures a bot. type Option func(b *Bot) -// WithCheckInitTimeout allows to redefine CheckInitTimeout +// WithCheckInitTimeout sets the timeout for the GetMe call that New makes. func WithCheckInitTimeout(timeout time.Duration) Option { return func(b *Bot) { b.checkInitTimeout = timeout } } -// WithMiddlewares allows to set middlewares for each incoming request +// WithMiddlewares adds middlewares that wrap the handler of each incoming update. +// A middleware can run code before and after the next handler, or skip it. +// The first added middleware is the outermost, so they start in the order added. func WithMiddlewares(middlewares ...Middleware) Option { return func(b *Bot) { b.middlewares = append(b.middlewares, middlewares...) } } -// WithMessageTextHandler allows to set handler for incoming text messages -// Also you can use *bot.RegisterHandler function after bot creation +// WithMessageTextHandler registers a handler for messages whose text matches +// pattern and matchType. To add a handler after creating the bot, use +// Bot.RegisterHandler. func WithMessageTextHandler(pattern string, matchType MatchType, handler HandlerFunc) Option { return func(b *Bot) { b.RegisterHandler(HandlerTypeMessageText, pattern, matchType, handler) } } -// WithCallbackQueryDataHandler allows to set handler for incoming callback query -// Also you can use *bot.RegisterHandler function after bot creation +// WithCallbackQueryDataHandler registers a handler for callback queries whose +// data matches pattern and matchType. To add a handler after creating the bot, +// use Bot.RegisterHandler. func WithCallbackQueryDataHandler(pattern string, matchType MatchType, handler HandlerFunc) Option { return func(b *Bot) { b.RegisterHandler(HandlerTypeCallbackQueryData, pattern, matchType, handler) } } -// WithPhotoCaptionHandler allows to set handler for incoming photos with caption -// Also you can use *bot.RegisterHandler function after bot creation +// WithPhotoCaptionHandler registers a handler for messages whose caption +// matches pattern and matchType. It checks the caption of any message type, not +// only photos. To add a handler after creating the bot, use Bot.RegisterHandler. func WithPhotoCaptionHandler(pattern string, matchType MatchType, handler HandlerFunc) Option { return func(b *Bot) { b.RegisterHandler(HandlerTypePhotoCaption, pattern, matchType, handler) } } -// WithDefaultHandler allows to set default handler for incoming updates +// WithDefaultHandler sets the handler for updates that no registered handler matches. func WithDefaultHandler(handler HandlerFunc) Option { return func(b *Bot) { b.defaultHandlerFunc = handler } } -// WithDebug allows to enable debug mode. In debug mode, all requests and responses are logged by debug handler +// WithDebug enables debug mode. The debug handler then receives API requests, +// API responses and webhook payloads, except getUpdates requests and responses +// whose result is an empty array. func WithDebug() Option { return func(b *Bot) { b.isDebug = true } } -// WithErrorsHandler allows to set handler for errors +// WithErrorsHandler sets the callback for errors reported internally by the +// library, such as polling and webhook processing errors. Errors from API +// methods such as SendMessage are returned to the caller and must be handled +// there. func WithErrorsHandler(handler ErrorsHandler) Option { return func(b *Bot) { b.errorsHandler = handler } } -// WithDebugHandler allows to set handler for debug messages +// WithDebugHandler sets the handler for debug messages. The bot emits them only +// in debug mode, see WithDebug. func WithDebugHandler(handler DebugHandler) Option { return func(b *Bot) { b.debugHandler = handler } } -// WithHTTPClient allows to set custom http client +// WithHTTPClient sets the HTTP client for requests to the Telegram API and the +// polling timeout. A getUpdates request asks Telegram to wait up to pollTimeout +// minus one second. func WithHTTPClient(pollTimeout time.Duration, client HttpClient) Option { return func(b *Bot) { b.pollTimeout = pollTimeout @@ -81,7 +94,7 @@ func WithHTTPClient(pollTimeout time.Duration, client HttpClient) Option { } } -// WithServerURL allows to set custom server url +// WithServerURL sets the Bot API server URL, such as that of a local Bot API server. func WithServerURL(serverURL string) Option { return func(b *Bot) { b.url = serverURL @@ -97,7 +110,8 @@ func WithSkipGetMe() Option { } } -// WithAllowedUpdates allows to set custom params for getUpdates method +// WithAllowedUpdates sets the update types requested from getUpdates. It applies +// only to polling. func WithAllowedUpdates(params AllowedUpdates) Option { return func(b *Bot) { b.allowedUpdates = params @@ -115,37 +129,45 @@ func WithUpdatesChannelCap(cap int) Option { } } -// WithWebhookSecretToken allows setting X-Telegram-Bot-Api-Secret-Token sent from Telegram servers +// WithWebhookSecretToken sets the expected value of the +// X-Telegram-Bot-Api-Secret-Token header. Webhook requests with a different +// value are rejected. An empty token disables the check. func WithWebhookSecretToken(webhookSecretToken string) Option { return func(b *Bot) { b.webhookSecretToken = webhookSecretToken } } -// WithWorkers allows setting the number of workers that are processing the Updates channel +// WithWorkers sets the number of workers that take updates from the queue. By +// default a worker starts each handler in a new goroutine, so this number does +// not limit concurrent handlers. With WithNotAsyncHandlers, it limits how many +// queued updates are handled at once. Start and StartWebhook report an error +// and return if workers is not positive. func WithWorkers(workers int) Option { return func(b *Bot) { b.workers = workers } } -// UseTestEnvironment allows to use test environment +// UseTestEnvironment sends API requests to the Telegram test environment. func UseTestEnvironment() Option { return func(b *Bot) { b.testEnvironment = true } } -// WithNotAsyncHandlers runs each handler in its worker goroutine. -// A worker then takes the next update only after its handler returns, so a -// WebhookHandler request may wait for a busy worker. +// WithNotAsyncHandlers runs each handler synchronously in the calling +// goroutine: the worker for queued updates, or the caller of ProcessUpdate. +// Each worker handles its updates sequentially, but several workers can still +// run handlers concurrently. A WebhookHandler request may wait for a busy worker. func WithNotAsyncHandlers() Option { return func(b *Bot) { b.notAsyncHandlers = true } } -// WithInitialOffset allows to set initial offset for getUpdates method +// WithInitialOffset sets the ID of the last processed update. The first +// getUpdates request uses offset+1 as its offset. func WithInitialOffset(offset int64) Option { return func(b *Bot) { b.lastUpdateID = offset diff --git a/process_update.go b/process_update.go index da26e15..d6c6396 100644 --- a/process_update.go +++ b/process_update.go @@ -17,7 +17,9 @@ func applyMiddlewares(h HandlerFunc, m ...Middleware) HandlerFunc { return wrapped } -// ProcessUpdate allows you to process update +// ProcessUpdate finds the handler for upd, applies the bot middlewares and runs +// it. The handler runs in a new goroutine, or in the calling goroutine with +// WithNotAsyncHandlers. func (b *Bot) ProcessUpdate(ctx context.Context, upd *models.Update) { h := b.findHandler(upd)