Documentation
¶
Overview ¶
Package telegram builds Telegram bots on top of github.com/go-telegram/bot with command and callback routing, handler middleware, typed callback data and reply helpers.
Create a bot with NewApp, register handlers with Bot.BindCommand, Bot.BindCallback and Bot.BindNoRoute, then run long polling with Bot.Start until its context is cancelled. Handlers reply with Bot.SendMessage, which sends a new message for a regular message and edits the original message for a callback query. Use Bot.API for any Bot API call this package does not wrap.
Usage ¶
import (
"context"
"fmt"
"os"
"os/signal"
"github.com/go-sphere/telegram-bot/telegram"
)
app, err := telegram.NewApp(telegram.Config{Token: os.Getenv("TELEGRAM_BOT_TOKEN")})
if err != nil {
return err
}
app.BindCommand("start", func(ctx context.Context, update *telegram.Update) error {
return app.SendMessage(ctx, update, &telegram.Message{Text: "Hello!"})
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
return app.Start(ctx) // blocks until ctx is cancelled
Register every handler before calling Bot.Start. Polling stops when the context passed to Start is cancelled; Bot.Close is not required to stop it.
Callback buttons ¶
Continuing the recipe above, NewButton encodes a route and a typed payload into callback data of the form "route:payload". A handler bound with Bot.BindCallback for the same route receives the press and decodes the payload with UnmarshalData:
type page struct {
N int `json:"n"` // only fields with a json tag are encoded
}
app.BindCommand("menu", func(ctx context.Context, update *telegram.Update) error {
btn, err := telegram.NewButton("Next", "page", page{N: 2})
if err != nil {
return err // empty route, ':' in route, or payload over 64 bytes
}
return app.SendMessage(ctx, update, &telegram.Message{
Text: "Page 1",
Button: [][]telegram.Button{{btn}},
})
})
app.BindCallback("page", func(ctx context.Context, update *telegram.Update) error {
_, p, err := telegram.UnmarshalData[page](update.CallbackQuery.Data)
if err != nil {
return err
}
return app.SendMessage(ctx, update, &telegram.Message{Text: fmt.Sprint("Page ", p.N)})
})
Middleware and errors ¶
A HandlerFunc returns an error instead of replying to failures itself. Errors go to the ErrorHandlerFunc set with WithErrorHandler (by default they are logged with log/slog; SendErrorMessage can show them to the user). Middleware set with AppendMiddlewares runs first, then NewAuthMiddleware with the extractor set by WithAuthExtractor, then middleware passed to an individual Bind call. Ready-made middleware includes NewSingleFlightMiddleware and NewGroupMessageFilterMiddleware. Handler panics are recovered and logged.
Handlers run in their own goroutines by default, so several updates can be processed concurrently; pass github.com/go-telegram/bot.WithNotAsyncHandlers through AppendBotOptions to process updates synchronously.
Related helpers: BroadcastMessage for rate-limited mass sending and RetryOnTooManyRequestsErrorContext for retrying after HTTP 429 responses. Mini App init data is validated by package github.com/go-sphere/telegram-bot/tmaauth.
Example ¶
This example routes updates offline: WithNotAsyncHandlers makes ProcessUpdate run the matching handler synchronously, so no network or polling is needed. A real bot calls Start instead (see Bot.Start).
package main
import (
"context"
"fmt"
"github.com/go-sphere/telegram-bot/telegram"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
func main() {
app, err := telegram.NewApp(
telegram.Config{Token: "123:test-token"},
telegram.AppendBotOptions(bot.WithNotAsyncHandlers()),
)
if err != nil {
fmt.Println("new app:", err)
return
}
app.BindCommand("start", func(ctx context.Context, update *telegram.Update) error {
uid, _ := telegram.AuthUserID(ctx)
fmt.Println("start from user", uid)
return nil
})
app.BindNoRoute(func(ctx context.Context, update *telegram.Update) error {
fmt.Println("no route:", update.Message.Text)
return nil
})
ctx := context.Background()
for _, text := range []string{"/start", "/startup"} {
app.API().ProcessUpdate(ctx, &telegram.Update{Message: &models.Message{
Text: text,
From: &models.User{ID: 42},
}})
}
}
Output: start from user 42 no route: /startup
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
Examples ¶
Constants ¶
const MaxCallbackDataLength = 64
MaxCallbackDataLength is the maximum payload size, in bytes, that Telegram accepts for inline keyboard callback data. MarshalData and NewButton reject longer data.
Variables ¶
var (
ErrCallbackDataTooLong = errors.New("telegram: callback data exceeds 64 bytes")
)
ErrCallbackDataTooLong is returned, wrapped, when the marshaled callback data exceeds MaxCallbackDataLength; test for it with errors.Is.
Functions ¶
func AuthSubject ¶ added in v0.0.3
AuthSubject returns the authentication subject (username) extracted from the update, and whether it was present. The value is present only when the extractor stored a string under AuthSubjectKey; it may be empty for users without a username.
func AuthUserID ¶ added in v0.0.3
AuthUserID returns the authenticated user ID extracted from the update, and whether it was present. The value is present only when the extractor stored an int64 under AuthUserIDKey, as DefaultAuthExtractor does.
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.
Items are sent one at a time on the calling goroutine, in slice order. If ctx is cancelled, or rateLimiter.Wait fails (for example because a deadline would be exceeded), BroadcastMessage stops and returns that error; items already sent are not reported. b is passed to send unchanged and may be nil when send does not use it.
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
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/go-sphere/telegram-bot/telegram"
"github.com/go-telegram/bot"
"golang.org/x/time/rate"
)
func main() {
users := []int64{1, 2, 3}
limiter := rate.NewLimiter(rate.Inf, 1) // use a finite rate for real broadcasts
err := telegram.BroadcastMessage(context.Background(), nil, users, limiter,
func(ctx context.Context, b *bot.Bot, chatID int64) error {
if chatID == 2 {
return errors.New("blocked by user")
}
return nil // a real send function would call b.SendMessage
},
)
var be *telegram.BroadcastError
if errors.As(err, &be) {
fmt.Printf("sent %d of %d, first error: %v\n", be.Success, be.Total, be.Err)
}
}
Output: sent 2 of 3, first error: blocked by user
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, stored under AuthUserIDKey (int64) and AuthSubjectKey (string). It returns nil, nil for updates without a message sender or callback query, and never returns an error. 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. A too long result returns an error wrapping ErrCallbackDataTooLong; JSON encoding errors for data are returned as is.
Data is encoded with github.com/go-sphere/jsoncompressor: struct values become JSON arrays in field order and only exported fields with a json tag are included, so untagged fields are silently dropped. Reordering the fields of T breaks callback data created before the change.
Example (TooLong) ¶
package main
import (
"errors"
"fmt"
"strings"
"github.com/go-sphere/telegram-bot/telegram"
)
func main() {
_, err := telegram.MarshalData("route", strings.Repeat("x", 80))
fmt.Println(errors.Is(err, telegram.ErrCallbackDataTooLong))
}
Output: true
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. The returned file reads from data, which must not be modified until the message has been sent; it can be uploaded once.
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. NewApp installs it by default; it is a github.com/go-telegram/bot middleware, for use with bot.WithMiddlewares rather than AppendMiddlewares.
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; Telegram fetches or resolves it when the message is sent.
func RetryOnTooManyRequestsError ¶
RetryOnTooManyRequestsError implements automatic retry logic for Telegram rate limit errors. It is a convenience wrapper around RetryOnTooManyRequestsErrorContext with a background context, so waiting cannot be cancelled; prefer the Context variant inside handlers.
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.
send is called at most maxRetries+1 times. Only errors matching *github.com/go-telegram/bot.TooManyRequestsError (via errors.As) are retried; any other error is returned unchanged. A negative maxRetries returns an error without calling send. The max-retries error does not wrap the last rate-limit error.
Example ¶
package main
import (
"context"
"fmt"
"github.com/go-sphere/telegram-bot/telegram"
"github.com/go-telegram/bot"
)
func main() {
attempts := 0
err := telegram.RetryOnTooManyRequestsErrorContext(context.Background(), 3, func() error {
attempts++
if attempts == 1 {
return &bot.TooManyRequestsError{Message: "Too Many Requests", RetryAfter: 0}
}
return nil
})
fmt.Println(attempts, err)
}
Output: 2 <nil>
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, truncated to 200 characters. It does nothing when b, err or update is nil, and ignores errors from the Bot API. Its signature matches ErrorHandlerFunc, so it can be passed to WithErrorHandler to show handler errors to users.
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.
In detail:
- Regular message: sendMessage, or sendPhoto when m.Media is set, to the same chat.
- Callback query on an accessible message: editMessageMedia when m.Media is set, editMessageCaption when the original has media, otherwise editMessageText.
- Callback query on an inline message: editMessageMedia or editMessageText by inline message id.
- Callback query whose message is no longer accessible: a callback answer telling the user the message is unavailable.
It returns nil without a request when update or m is nil, or when the update is neither a message nor a callback query. It returns an error when b is nil. API errors are returned as produced by github.com/go-telegram/bot. ctx bounds the HTTP request.
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.
The payload is decoded with github.com/go-sphere/jsoncompressor, so T must have the same tagged fields, in the same order, as the value given to MarshalData. Data without ":" returns an error and an empty route. When the payload cannot be decoded into T, the route is still returned with a nil value and the decoding error.
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. The first middleware is therefore the outermost one and runs first. A nil e discards errors.
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.
ExtractorAuth returns values to store in the handler context: each map key is stored under ContextKey(key). A nil map adds nothing. A non-nil error stops the update before the handler runs and is passed to the bot's error handler. Implementations may be called concurrently for different updates.
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.
Create a Bot with NewApp; the zero value is not usable. Register handlers (BindCommand, BindCallback, BindNoRoute, BindRoute) and apply Update before calling Start: BindNoRoute and Update are not synchronized with update processing. After Close, the Bot must not be used again.
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.
NewApp makes no network request: the underlying client is created with github.com/go-telegram/bot.WithSkipGetMe, so an invalid but non-empty token is only detected by the first API call. It returns an error when config.Token is empty or whitespace only, or when an option passed through AppendBotOptions makes client creation fail (for example by removing WithSkipGetMe and failing the getMe call).
Defaults: unmatched updates are logged, handler errors are logged with log/slog, DefaultAuthExtractor fills the context, handler panics are recovered and logged, and Start deletes any configured webhook first.
func (*Bot) API ¶
API returns the underlying Telegram bot client for direct API access. It returns nil after Close.
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 handler matches callback data starting with route followed by ":", so BindCallback("menu", ...) matches "menu:item1" produced by NewButton(text, "menu", data) or MarshalData("menu", data). Middleware and error handling are applied as in BindCommand.
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".
handlerFunc is wrapped with the bot middleware (AppendMiddlewares, then the auth middleware), followed by middlewares, and its error is passed to the bot's error handler. Handlers are tried in registration order and the first match wins.
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. It replaces the handler set with WithDefaultHandler and, unlike that option, runs the bot middleware and error handler around handlerFunc. Call it before Start.
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.
For every name in operations, extra is queried for metadata; operations with nil metadata or with both Command and CallbackQuery empty are skipped. A non-empty Command is bound with BindCommand and a non-empty CallbackQuery with BindCallback, both using route[name] and middlewares. BindRoute panics if route[name] is nil for an operation being bound.
With code generated by protoc-gen-route for MenuService in package menuv1:
routes := menuv1.RegisterMenuServiceRouteServer(srv, codec, app.SendMessage) app.BindRoute(routes, menuv1.GetExtraRouteDataByMenuServiceOperation, menuv1.GetAllRouteMenuServiceOperations(), )
func (*Bot) Close ¶
Close calls the Telegram Bot API "close" method, then detaches the client from b. It is not a cleanup method and must not be deferred as one: the Bot API close method is only for moving a bot from one Bot API server to another, Telegram rejects it with 429 for the first 10 minutes after the bot is launched, and it does not stop polling (cancel the context passed to Start for that). Normal shutdown needs no call at all.
The client is detached even when the request fails, so API returns nil and other methods must not be called afterwards. Calling Close again is a no-op that returns nil.
func (*Bot) SendMessage ¶
SendMessage sends a message in response to an update using the bot's client. It behaves like the package-level SendMessage: a regular message gets a new reply in the same chat, and a callback query edits the message that carried the button. It returns nil without sending when update or m is nil, and returns an error when the underlying client is nil (for example after Close).
Example ¶
This example points the client at a local test server to show which Bot API method SendMessage uses for a regular message.
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"github.com/go-sphere/telegram-bot/telegram"
"github.com/go-telegram/bot"
"github.com/go-telegram/bot/models"
)
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
fmt.Println("called", r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:])
_, _ = io.WriteString(w, `{"ok":true,"result":{"message_id":1,"chat":{"id":7}}}`)
}))
defer srv.Close()
app, err := telegram.NewApp(
telegram.Config{Token: "123:test-token"},
telegram.AppendBotOptions(bot.WithServerURL(srv.URL)),
)
if err != nil {
fmt.Println("new app:", err)
return
}
update := &telegram.Update{Message: &models.Message{Chat: models.Chat{ID: 7}}}
if err := app.SendMessage(context.Background(), update, &telegram.Message{Text: "hi"}); err != nil {
fmt.Println("send:", err)
}
}
Output: called sendMessage
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.
Start returns nil after ctx is cancelled and the polling and worker goroutines have stopped; cancelling ctx is how a running bot is stopped. Handlers that were started asynchronously may still be running when Start returns. Polling errors are reported through the underlying client's error handler (see github.com/go-telegram/bot.WithErrorsHandler), not returned.
Example ¶
This example shows the full lifecycle of a polling bot. It needs a real token and network access, so it is compiled but not run.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"github.com/go-sphere/telegram-bot/telegram"
)
func main() {
app, err := telegram.NewApp(telegram.Config{Token: os.Getenv("TELEGRAM_BOT_TOKEN")})
if err != nil {
fmt.Println("new app:", err)
return
}
app.BindCommand("start", func(ctx context.Context, update *telegram.Update) error {
return app.SendMessage(ctx, update, &telegram.Message{Text: "Hello!"})
})
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
if err := app.Start(ctx); err != nil { // blocks until ctx is cancelled
fmt.Println("start:", err)
}
}
Output:
type BroadcastError ¶ added in v0.0.3
type BroadcastError struct {
Total int // Number of items in the broadcast
Failed int // Number of items whose send function returned an error
Success int // Total minus Failed
Err error // The first send error encountered
}
BroadcastError reports a broadcast that finished with some failed sends. BroadcastMessage returns it as *BroadcastError; use errors.As to read the counts. errors.Is and errors.As also see the first send error through Unwrap.
func (*BroadcastError) Error ¶ added in v0.0.3
func (e *BroadcastError) Error() string
Error reports the success and failure counts and the first send error.
func (*BroadcastError) Unwrap ¶ added in v0.0.3
func (e *BroadcastError) Unwrap() error
Unwrap returns the first send error.
type BroadcastOption ¶
type BroadcastOption func(*broadcastOptions)
BroadcastOption defines a function type for configuring broadcast operations. Pass options to BroadcastMessage.
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. It is called before each item and once more with (total, errors, total) after the last item when the broadcast is not stopped early. It runs on the goroutine that called BroadcastMessage.
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 and BroadcastMessage returns that send error unwrapped. The default is false.
type Button ¶
type Button = models.InlineKeyboardButton
Button is an alias for Telegram's inline keyboard button. Create one with NewButton or NewURLButton and place it in Message.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, as described in MarshalData (only json-tagged struct fields are encoded). 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.
Example ¶
package main
import (
"fmt"
"github.com/go-sphere/telegram-bot/telegram"
)
func main() {
type page struct {
N int `json:"n"` // only fields with a json tag are encoded
}
btn, err := telegram.NewButton("Next", "page", page{N: 2})
if err != nil {
fmt.Println("button:", err)
return
}
// A handler registered with BindCallback("page", ...) receives this data
// in update.CallbackQuery.Data.
route, p, err := telegram.UnmarshalData[page](btn.CallbackData)
if err != nil || p == nil {
fmt.Println("decode:", err)
return
}
fmt.Println(btn.Text, route, p.N)
}
Output: Next page 2
func NewURLButton ¶
NewURLButton creates an inline keyboard button that opens a URL when pressed. The URL is not validated locally.
type Config ¶
type Config struct {
// Token is the bot token issued by @BotFather. It must not be empty or
// whitespace only; NewApp rejects such a token.
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. SendErrorMessage has a compatible signature for showing errors to users.
type HandlerFunc ¶
HandlerFunc defines a function type for handling Telegram bot updates. It processes an Update and returns an error if processing fails; the error is passed to the bot's ErrorHandlerFunc rather than sent to the user. ctx carries the values added by middleware such as the auth middleware.
type Message ¶
type Message struct {
Text string // Message text, or the photo caption when Media is set
Media models.InputFile // Optional photo, sent with sendPhoto; nil sends text only
ParseMode models.ParseMode // Text parsing mode (HTML, Markdown, etc.); empty means plain text
Button [][]models.InlineKeyboardButton // Inline keyboard layout as rows of buttons; empty means no keyboard
}
Message represents a complete message that can be sent or edited in Telegram. It supports text content, media attachments, formatting, and inline keyboards. Send it with Bot.SendMessage or SendMessage.
type MessageSender ¶
MessageSender defines a function that sends messages in response to updates. Bot.SendMessage has this signature.
type MethodExtraData ¶
type MethodExtraData struct {
Command string // Command to bind with Bot.BindCommand; empty means no command route
CallbackQuery string // Callback route to bind with Bot.BindCallback; empty means no callback route
}
MethodExtraData holds the routing metadata of one operation for Bot.BindRoute. Code generated by protoc-gen-route creates one value per operation.
func NewMethodExtraData ¶
func NewMethodExtraData(raw map[string]string) *MethodExtraData
NewMethodExtraData creates a new MethodExtraData instance from a raw string map. It reads the "command" and "callback_query" keys; missing keys leave the corresponding field empty. raw may be nil.
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. A middleware may stop processing by returning without calling next.
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 through ctx.Value(ContextKey(key)), AuthUserID and AuthSubject. If the extractor returns an error, the next handler is not called and the error is returned. NewApp installs this middleware with the extractor from WithAuthExtractor.
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.
Only messages in group and supergroup chats are filtered; private chats, callback queries and other updates pass through. A group message reaches the next handler when it replies to a message from the bot, mentions "@username" in its text or caption, contains a text mention of the bot, or carries a command with the "@username" suffix. Other group messages are dropped silently (the middleware returns nil). If fetching the bot info fails, the error is returned. With trimMention, the first matching mention is removed from update.Message.Text or Caption before next runs.
Parameters:
- b: The bot client used to retrieve bot information, usually Bot.API()
- trimMention: Whether to remove mention text from processed messages
- infoExpire: Duration to cache bot information before refreshing; zero or negative calls getMe for every group message
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.
A press that arrives while an identical one is still being handled waits for it and receives the same error instead of running the handler again; later presses run normally. Updates that are not callback queries pass through unchanged. Each call returns a middleware with its own state.
type Option ¶
type Option = func(*options)
Option defines a function type for configuring bot application options. Options are applied by NewApp in order; a later option overrides an earlier one that sets the same value, while Append options accumulate.
func AppendBotOptions ¶
AppendBotOptions adds additional options to the underlying bot client configuration. These options will be passed directly to the bot.New() constructor, after the defaults (WithSkipGetMe, panic recovery middleware and the default handler), so they can override them.
func AppendMiddlewares ¶
func AppendMiddlewares(middlewares ...MiddlewareFunc) Option
AppendMiddlewares adds middleware functions to the bot application. Middleware will be applied to all handlers registered with a Bind method in the order they are provided: the first middleware is the outermost and runs before the auth middleware and before middleware passed to the Bind call.
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. It replaces DefaultAuthExtractor and runs for every handler registered with a Bind method; see NewAuthMiddleware for how its result reaches handlers. A nil extractor is ignored.
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. fn is a raw github.com/go-telegram/bot handler: the middleware chain and error handler of this package are not applied. Use Bot.BindNoRoute for a HandlerFunc with middleware. A nil fn is ignored. The default logs the message text or callback data with log/slog.
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, including an error from middleware such as the auth extractor. A nil fn discards errors. The default handler logs the error with log/slog.
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. The Register<Service>RouteServer functions generated by github.com/go-sphere/protoc-gen-route have this shape; pass their result to Bot.BindRoute.