Help us shape the future of Go! Take the 2026 Go Developer Survey

tgbox

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2026 License: MIT Imports: 50 Imported by: 0

Documentation

Overview

Package tgbox is a lightweight, high-performance Telegram bot and userbot framework built on top of gotd/td (MTProto).

The client is configured with functional options and exposes a simple, handler-based API for processing updates:

client, err := tgbox.New("mybot",
	tgbox.WithAppID(123456),
	tgbox.WithAppHash("hash"),
	tgbox.WithBotToken("token"),
)
if err != nil {
	log.Fatal(err)
}
defer client.Close()

client.OnCommand("/start", func(ctx *tgbox.Context, upd *tgbox.Update) error {
	_, err := ctx.ReplyText("Hello!")
	return err
})

if err := client.Run(context.Background()); err != nil {
	log.Fatal(err)
}

Subpackages provide focused building blocks: filter (update filters), keyboard (inline/reply keyboard builders), and auth (headless MTProto authentication). Low-level MTProto plumbing lives under internal and is not part of the public API.

Package tgbox integrates the physical network simulation profile into the core MTProto engine.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilUpdate indicates that the context does not carry a valid update payload.
	ErrNilUpdate = errors.New("tgbox: context update payload is nil")

	// ErrNoPeer indicates that no recognizable target peer could be extracted from the update.
	ErrNoPeer = errors.New("tgbox: update structure does not present any recognizable peer")

	// ErrNoMessageID indicates that the update lacks a message ID required for editing operations.
	ErrNoMessageID = errors.New("tgbox: current update has no associated message ID to edit")

	// ErrNoCallbackQuery indicates that the context lacks an active callback query for the requested operation.
	ErrNoCallbackQuery = errors.New("tgbox: context does not hold an active callback query")

	// ErrNoInlineQuery indicates that the context lacks an active inline query for the requested operation.
	ErrNoInlineQuery = errors.New("tgbox: context does not hold an active inline query")

	// ErrFSMNotConfigured indicates that the conversational FSM engine or storage is missing.
	ErrFSMNotConfigured = errors.New("tgbox: conversational FSM engine/storage is not configured")

	// ErrInvalidFSMContext indicates that FSM operations were called on an update lacking ChatID or SenderID.
	ErrInvalidFSMContext = errors.New("tgbox: FSM operations require a valid chat and user context")

	// ErrNetworkNotConfigured indicates that network-level operations like Suspend/Resume require WithNetworkProfile.
	ErrNetworkNotConfigured = errors.New("tgbox: network profile is not configured")

	// ErrExpirationWatchNotSupported indicates that the underlying FSM storage backend does not support keyspace expiration notifications.
	ErrExpirationWatchNotSupported = errors.New("tgbox: FSM storage does not support reactive expiration watching")
)
View Source
var (
	// ErrEndGroups stops evaluation of all remaining groups for this update.
	ErrEndGroups = dispatcher.ErrEndGroups
	// ErrContinueGroups keeps scanning the current group for further
	// matching handlers instead of advancing to the next group.
	ErrContinueGroups = dispatcher.ErrContinueGroups
)

Control-flow sentinel errors handlers may return to steer group traversal.

Functions

func BuildBanRequest

func BuildBanRequest(channel tg.InputChannelClass, participant tg.InputPeerClass) *tg.ChannelsEditBannedRequest

BuildBanRequest constructs a ChannelsEditBannedRequest with default banned restrictions.

func BuildPromoteRequest

func BuildPromoteRequest(channel tg.InputChannelClass, user tg.InputUserClass) *tg.ChannelsEditAdminRequest

BuildPromoteRequest constructs a ChannelsEditAdminRequest with default administrative permissions.

func ClientIDFromContext

func ClientIDFromContext(ctx context.Context) int64

ClientIDFromContext extracts the embedded ClientID from a standard context.

func DefaultAdminRights

func DefaultAdminRights() tg.ChatAdminRights

DefaultAdminRights returns standard administrative permissions for channel moderation.

func DefaultBannedRights

func DefaultBannedRights() tg.ChatBannedRights

DefaultBannedRights returns standard restriction permissions to ban a member.

func RegisterControllers

func RegisterControllers(r Registrar, controllers ...Controller) error

RegisterControllers registers one or more controllers onto the provided Registrar.

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext extracts the embedded TraceID from a standard context.

func WithClientID

func WithClientID(ctx context.Context, clientID int64) context.Context

WithClientID embeds the active Bot/Userbot ID into the standard Go context.

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID embeds a unique sequential TraceID into the standard Go context.

Types

type AdminService

type AdminService interface {
	Promote(ctx context.Context, channel tg.InputChannelClass, user tg.InputUserClass) error
	Ban(ctx context.Context, channel tg.InputChannelClass, participant tg.InputPeerClass) error
}

AdminService defines administrative operations for supergroups and channels.

func NewAdminService

func NewAdminService(rpc *tg.Client) AdminService

NewAdminService creates an instance of AdminService decoupled from Context.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main entry point for the tgbox framework.

func New

func New(appName string, opts ...Option) (*Client, error)

New creates a TGBox client.

func (*Client) API

func (c *Client) API() *tg.Client

API returns the underlying raw MTProto API client.

func (*Client) Admin

func (c *Client) Admin() AdminService

Admin returns the application-scoped AdminService for supergroup and channel moderation.

func (*Client) Chat

func (c *Client) Chat() MessageService

Chat returns the application-scoped MessageService for sending and modifying messages.

func (*Client) Close

func (c *Client) Close() error

Close gracefully terminates open background storage engines and profilers.

func (*Client) DownloadFile

func (c *Client) DownloadFile(ctx context.Context, location tg.InputFileLocationClass, dst io.Writer) (tg.StorageFileTypeClass, error)

DownloadFile streams or downloads a file from Telegram servers into dst.

func (*Client) FetchSelf

func (c *Client) FetchSelf(ctx context.Context) error

FetchSelf retrieves and caches the current authenticated user/bot metadata.

func (*Client) Install

func (c *Client) Install(plugins ...Plugin) error

Install registers one or more plugins with the client.

func (*Client) OnCallbackQuery

func (c *Client) OnCallbackQuery(f Filter, h Handler, opts ...HandlerOption)

OnCallbackQuery registers an update handler for inline button callbacks.

func (*Client) OnChatJoinRequest

func (c *Client) OnChatJoinRequest(f Filter, h Handler, opts ...HandlerOption)

OnChatJoinRequest registers an update handler for chat join requests.

func (*Client) OnChatMemberUpdated

func (c *Client) OnChatMemberUpdated(f Filter, h Handler, opts ...HandlerOption)

OnChatMemberUpdated registers an update handler for chat membership updates.

func (*Client) OnCommand

func (c *Client) OnCommand(pattern string, h Handler, opts ...HandlerOption)

OnCommand registers a handler for command matching via the parametric Radix Trie.

func (*Client) OnDeletedMessages

func (c *Client) OnDeletedMessages(f Filter, h Handler, opts ...HandlerOption)

OnDeletedMessages registers an update handler for message deletion events.

func (*Client) OnEditedMessage

func (c *Client) OnEditedMessage(f Filter, h Handler, opts ...HandlerOption)

OnEditedMessage registers an update handler for edited messages.

func (*Client) OnInlineQuery

func (c *Client) OnInlineQuery(f Filter, h Handler, opts ...HandlerOption)

OnInlineQuery registers an update handler for inline queries.

func (*Client) OnMessage

func (c *Client) OnMessage(f Filter, h Handler, opts ...HandlerOption)

OnMessage registers an update handler for new incoming messages.

func (*Client) OnRawUpdate

func (c *Client) OnRawUpdate(h RawHandler, opts ...HandlerOption)

OnRawUpdate registers a low-level handler for raw MTProto updates.

func (*Client) OnState

func (c *Client) OnState(state string, h Handler, opts ...HandlerOption)

OnState registers a handler for conversational state transitions.

func (*Client) RegisterController

func (c *Client) RegisterController(controllers ...Controller) error

RegisterController registers one or more controllers with the client.

func (*Client) Resume

func (c *Client) Resume() error

Resume unblocks socket dialing if a gated dialer is configured.

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run starts the MTProto connection, authenticates, and blocks until the context is canceled.

func (*Client) Self

func (c *Client) Self() *tg.User

Self returns the authenticated Telegram User object.

func (*Client) Sender

func (c *Client) Sender() *message.Sender

Sender returns the application-scoped, concurrency-safe message.Sender bound to this client.

func (*Client) State

func (c *Client) State() StateManager

State returns the application-scoped StateManager for conversational FSM management.

func (*Client) Suspend

func (c *Client) Suspend() error

Suspend pauses socket dialing and closes active connections if a gated dialer is configured.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, name string, src io.Reader, size int64) (tg.InputFileClass, error)

UploadFile streams and uploads a file to Telegram servers using the connection pool.

type CommandRouter

type CommandRouter interface {
	Insert(path string, handler commandRoute)
	Match(path string) (handler commandRoute, params map[string]string, ok bool)
}

CommandRouter defines the contract for the parametric command routing tree.

type Context

type Context struct {
	// StdContext represents the underlying standard Go context for cancellation and deadlines.
	StdContext context.Context

	// Update contains the normalized and parsed update metadata for this request.
	Update *Update

	// Entities represents the cached peer metadata extracted from this update transaction.
	Entities *tg.Entities

	// Logger represents the structured transaction-scoped logger with request telemetry (trace_id, client_id).
	Logger *slog.Logger

	// Params contains route variables extracted from parametric Radix tree routing.
	Params map[string]string
	// contains filtered or unexported fields
}

Context is the request-scoped container passed to every update handler. It encapsulates the normalized update event, peer entities, route parameters, and cancellation context for a single update execution lifecycle. It is intentionally decoupled from long-lived application services (RPC, Sender, Storage).

func (*Context) ActiveChannelAndSender

func (c *Context) ActiveChannelAndSender() (*tg.InputChannel, tg.InputUserClass, error)

ActiveChannelAndSender resolves the current update's channel and sender purely from update metadata.

func (*Context) ClientID

func (c *Context) ClientID() int64

ClientID returns the ID of the bot/userbot executing this transaction directly from the active tgbox context.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the underlying standard library context.Context.

func (*Context) CurrentPeer

func (c *Context) CurrentPeer() (tg.InputPeerClass, error)

CurrentPeer extracts the target MTProto input peer from the context update safely.

func (*Context) Deadline

func (c *Context) Deadline() (time.Time, bool)

Deadline implements the context.Context interface.

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done implements the context.Context interface.

func (*Context) Err

func (c *Context) Err() error

Err implements the context.Context interface.

func (*Context) Param

func (c *Context) Param(key string) string

Param retrieves a parsed route variable by its key. Returns an empty string if the key does not exist.

func (*Context) PeerPromise

func (c *Context) PeerPromise() peer.Promise

PeerPromise wraps CurrentPeer inside a peer.Promise.

func (*Context) ResolveUser

func (c *Context) ResolveUser(id int64) (tg.InputUserClass, error)

ResolveUser resolves a user ID to an InputUserClass using entities extracted in the current update.

func (*Context) TraceID

func (c *Context) TraceID() string

TraceID returns the transaction's unique trace identifier directly from the active tgbox context.

func (*Context) Value

func (c *Context) Value(key any) any

Value implements the context.Context interface.

type Controller

type Controller interface {
	// RegisterRoutes registers the controller's endpoints and handlers onto the provided Registrar.
	RegisterRoutes(r Registrar) error
}

Controller represents a cohesive group of route handlers configured via explicit dependency injection.

type ControllerFunc

type ControllerFunc func(r Registrar) error

ControllerFunc allows plain functions to act as a Controller.

func (ControllerFunc) RegisterRoutes

func (f ControllerFunc) RegisterRoutes(r Registrar) error

RegisterRoutes implements Controller.

type Dispatcher

type Dispatcher interface {
	Start(ctx context.Context)
	Handle(c *Context, update *Update)
	AddRoute(kind int, f Filter, h Handler, m []Middleware, group int)
	SetInterceptor(f func(*Context, *Update) bool)
	SetWildcardKind(kind int)
}

Dispatcher defines the contract for routing updates to handlers.

type Filter

type Filter func(ctx *Context, update *Update) bool

Filter defines a predicate for routing updates.

type Handler

type Handler func(ctx *Context, update *Update) error

Handler is the universal function signature for all update handlers.

func Logger

func Logger(h Handler) Handler

Logger is a middleware that logs update processing details.

func Recover

func Recover(h Handler) Handler

Recover is a middleware that recovers from panics in handlers and converts them into errors.

type HandlerOption

type HandlerOption interface {
	// contains filtered or unexported methods
}

HandlerOption defines optional configurations for a registered handler.

func InGroup

func InGroup(group int) HandlerOption

InGroup assigns a priority group to the handler. Groups are evaluated in ascending order; within a group, the first handler whose filter matches runs, then evaluation moves to the next group.

func WithLocalMiddlewares

func WithLocalMiddlewares(m ...Middleware) HandlerOption

WithLocalMiddlewares adds middlewares to the handler.

type Lock

type Lock interface {
	// Release unlocks the distributed resource.
	Release(ctx context.Context) error
}

Lock represents a handle to an acquired distributed lock. It must be released gracefully to allow other cluster replicas to manage the tenant.

type Locker

type Locker interface {
	// Obtain attempts to acquire a lock for a given key with a strict TTL.
	// If the lock is already acquired by another node, implementations
	// return their held-lock sentinel (e.g. redis.ErrLockHeld).
	Obtain(ctx context.Context, key string, ttl time.Duration) (Lock, error)
}

Locker defines the distributed locking contract required to prevent race conditions and session corruption during concurrent cluster logins.

type MessageService

type MessageService interface {
	SendText(ctx context.Context, peer tg.InputPeerClass, text string, opts ...SendOption) (tg.UpdatesClass, error)
	SendHTML(ctx context.Context, peer tg.InputPeerClass, text string, opts ...SendOption) (tg.UpdatesClass, error)
	SendMarkdown(ctx context.Context, peer tg.InputPeerClass, text string, opts ...SendOption) (tg.UpdatesClass, error)
	SendRichMarkdown(ctx context.Context, peer tg.InputPeerClass, text string, opts ...SendOption) (tg.UpdatesClass, error)
	SendRich(ctx context.Context, peer tg.InputPeerClass, msg tg.InputRichMessageClass, opts ...SendOption) (tg.UpdatesClass, error)
	ReplyText(ctx context.Context, peer tg.InputPeerClass, msgID int, text string, opts ...SendOption) (tg.UpdatesClass, error)
	ReplyHTML(ctx context.Context, peer tg.InputPeerClass, msgID int, text string, opts ...SendOption) (tg.UpdatesClass, error)
	ReplyMarkdown(ctx context.Context, peer tg.InputPeerClass, msgID int, text string, opts ...SendOption) (tg.UpdatesClass, error)
	ReplyRichMarkdown(ctx context.Context, peer tg.InputPeerClass, msgID int, text string, opts ...SendOption) (tg.UpdatesClass, error)
	ReplyRich(ctx context.Context, peer tg.InputPeerClass, msgID int, msg tg.InputRichMessageClass, opts ...SendOption) (tg.UpdatesClass, error)
	EditActive(ctx context.Context, peer tg.InputPeerClass, msgID int, text string, opts ...SendOption) (tg.UpdatesClass, error)
	EditRich(ctx context.Context, peer tg.InputPeerClass, msgID int, msg tg.InputRichMessageClass, opts ...SendOption) (tg.UpdatesClass, error)
	EditReplyMarkup(ctx context.Context, peer tg.InputPeerClass, msgID int, markup keyboard.ReplyMarkup) (tg.UpdatesClass, error)
	AnswerCallback(ctx context.Context, queryID int64, alert bool, text string) error
}

MessageService defines the segregated contract for sending, replying to, and modifying messages. It decouples message delivery mechanics from the request-scoped Context.

func NewChatService

func NewChatService(sender *message.Sender, rpc *tg.Client, peerStorage contribstorage.PeerStorage) MessageService

NewChatService instantiates a decoupled messaging service bound to the client lifecycle.

type Middleware

type Middleware func(Handler) Handler

Middleware is a function that wraps a Handler.

type MultiTenantSessionStorage

type MultiTenantSessionStorage interface {
	// GetSessionStorage returns a thread-safe gotd session.Storage bound to a specific tenant.
	GetSessionStorage(tenantKey string) SessionStorage

	// DeleteSession permanently purges the stored MTProto session bytes for a specific tenant.
	DeleteSession(ctx context.Context, tenantKey string) error

	// HasSession verifies if the session data exists for the given tenant without loading it.
	HasSession(ctx context.Context, tenantKey string) (bool, error)
}

MultiTenantSessionStorage abstracts session management, allowing tgbox to dynamically map gotd session.Storage adapters based on unique tenant identifier keys (e.g., bot tokens, user IDs).

The interface is defined in the consumer package (tgbox root) following Go's implicit interface convention. Concrete implementations (e.g., store/redis.Store) satisfy it without importing this package.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option defines a functional configuration for the Client.

func WithAppHash

func WithAppHash(hash string) Option

WithAppHash sets the Telegram Application Hash.

func WithAppID

func WithAppID(id int) Option

WithAppID sets the Telegram Application ID.

func WithAppVersion

func WithAppVersion(v string) Option

WithAppVersion sets the application version string (app_version) reported to the Telegram servers during initialization.

func WithAutoPeerCaching

func WithAutoPeerCaching(enabled bool) Option

WithAutoPeerCaching enables automatic background dialogs collection for peer cache warming.

func WithBotToken

func WithBotToken(token string) Option

WithBotToken sets the Telegram Bot token for authentication.

func WithDeviceConfig

func WithDeviceConfig(d telegram.DeviceConfig) Option

WithDeviceConfig completely overrides the underlying device configuration sent during the initConnection phase of the MTProto handshake.

func WithDeviceModel

func WithDeviceModel(model string) Option

WithDeviceModel sets the raw device model string (device_model) reported to the Telegram servers during initialization.

func WithEngine

func WithEngine(e engine.Engine) Option

WithEngine provides a custom MTProto Engine implementation.

func WithEngineOptions

func WithEngineOptions(fn func(opts *telegram.Options)) Option

WithEngineOptions applies custom options directly to the underlying gotd engine options.

func WithFSMStorage

func WithFSMStorage(s fsm.Storage) Option

WithFSMStorage configures a custom conversational FSM storage backend.

func WithHTTPProxy

func WithHTTPProxy(addr, username, password string, fallback bool) Option

WithHTTPProxy explicitly configures an HTTP CONNECT proxy using separate parameters.

func WithInitParams

func WithInitParams(v tg.JSONValueClass) Option

WithInitParams specifies custom, raw JSON parameters (params) sent to the Telegram servers during initialization. This allows complete and unrestricted flexibility to define properties such as timezone offsets.

func WithLangCode

func WithLangCode(code string) Option

WithLangCode sets either an ISO 639-1 language code or a language pack name (lang_code) obtained from a language pack link.

func WithLangPack

func WithLangPack(pack string) Option

WithLangPack sets the platform pack string (lang_pack), which indicates the target platform UI layer (e.g., "android", "tdesktop").

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the structured slog logger for the client.

func WithNetworkProfile

func WithNetworkProfile(profile network.Profile) Option

WithNetworkProfile injects a strictly modeled Profile into the MTProto pipeline. It configures the physical transport protocol, OS-level TCP tuning (segmentation, buffers), Keep-Alive jitters, connection pool limits, and Perfect Forward Secrecy (PFS) temporary key parameters.

func WithPFS

func WithPFS(enabled bool, ttl ...time.Duration) Option

WithPFS configures Perfect Forward Secrecy (PFS) with optional temporary authorization key TTL.

func WithPeerStorage

func WithPeerStorage(p storage.PeerStorage) Option

WithPeerStorage configures custom peer storage.

func WithProfiler

func WithProfiler(cfg ProfilerConfig) Option

WithProfiler enables runtime diagnostic profiling and the goroutine leak watchdog.

func WithProxy

func WithProxy(rawURL string, fallback bool) Option

WithProxy configures the client to route all network traffic through a proxy specified by a raw URL (e.g. "socks5://user:pass@127.0.0.1:1080" or "http://127.0.0.1:8080"). If fallback is true, direct connection is attempted as a backup if the proxy goes offline.

func WithSOCKS5

func WithSOCKS5(addr, username, password string, fallback bool) Option

WithSOCKS5 explicitly configures a SOCKS5 proxy using separate parameters.

func WithSessionStorage

func WithSessionStorage(s SessionStorage) Option

WithSessionStorage sets a custom session storage backend. When omitted, a bbolt database derived from the app name is created next to the binary.

func WithSystemLangCode

func WithSystemLangCode(code string) Option

WithSystemLangCode sets the system language code (system_lang_code) reported to the Telegram servers during initialization.

func WithSystemVersion

func WithSystemVersion(v string) Option

WithSystemVersion sets the raw operating system version string (system_version) reported to the Telegram servers during initialization.

func WithTrafficObserver

func WithTrafficObserver(cb func()) Option

WithTrafficObserver attaches a traffic activity callback for keep-alive monitoring.

func WithWorkers

func WithWorkers(w int) Option

WithWorkers configures the number of parallel dispatcher worker shards.

func WithoutUpdates

func WithoutUpdates() Option

WithoutUpdates disables the update manager in the underlying engine.

type Plugin

type Plugin interface {
	// Register is called by the client to initialize the plugin.
	Register(r Registrar) error
}

Plugin defines the interface for TGBox modules.

type Profiler

type Profiler struct {
	// contains filtered or unexported fields
}

Profiler monitors runtime health, detects goroutine leaks, and exposes pprof endpoints. It implements io.Closer for clean teardown.

func NewProfiler

func NewProfiler(cfg ProfilerConfig, logger *slog.Logger) *Profiler

NewProfiler instantiates and launches the profiler engine and background watchdog.

func (*Profiler) Addr

func (p *Profiler) Addr() string

Addr returns the listening address of the diagnostic HTTP server, or empty string if disabled.

func (*Profiler) Close

func (p *Profiler) Close() error

Close stops the background watchdog and terminates the diagnostic HTTP server gracefully.

func (*Profiler) LeakedGoroutines

func (*Profiler) LeakedGoroutines() int

LeakedGoroutines returns the count of permanently blocked goroutines detected via GC reachability. Returns 0 if the goroutineleak profile is unavailable or no leaks are detected.

func (*Profiler) NumGoroutine

func (*Profiler) NumGoroutine() int

NumGoroutine returns the current number of active goroutines.

type ProfilerConfig

type ProfilerConfig struct {
	// Enabled indicates whether the diagnostic engine should run.
	Enabled bool

	// HTTPAddr specifies the loopback address for the HTTP pprof endpoint (e.g., "127.0.0.1:6060" or "127.0.0.1:0").
	// If empty, no HTTP listener is started, but the background leak watchdog remains active.
	HTTPAddr string

	// ScanInterval defines the frequency of background goroutine checks. Default: 15 seconds.
	ScanInterval time.Duration

	// GoroutineThreshold specifies the limit of active goroutines before emitting a warning log. Default: 5000.
	GoroutineThreshold int

	// OnThresholdExceeded is an optional callback triggered when active goroutines exceed the threshold.
	OnThresholdExceeded func(count int)

	// OnLeakDetected is an optional callback triggered when GC-reachability analysis detects permanently leaked goroutines.
	OnLeakDetected func(count int)
}

ProfilerConfig configures the diagnostic profiling engine and goroutine leak watchdog.

type RawHandler

type RawHandler func(ctx *Context, entities *tg.Entities, raw tg.UpdateClass) error

RawHandler is a lower-level handler for raw MTProto updates.

type Registrar

type Registrar interface {
	OnMessage(f Filter, h Handler, opts ...HandlerOption)
	OnEditedMessage(f Filter, h Handler, opts ...HandlerOption)
	OnCallbackQuery(f Filter, h Handler, opts ...HandlerOption)
	OnInlineQuery(f Filter, h Handler, opts ...HandlerOption)
	OnChatMemberUpdated(f Filter, h Handler, opts ...HandlerOption)
	OnChatJoinRequest(f Filter, h Handler, opts ...HandlerOption)
	OnDeletedMessages(f Filter, h Handler, opts ...HandlerOption)
	OnCommand(pattern string, h Handler, opts ...HandlerOption)
	OnState(state string, h Handler, opts ...HandlerOption)
	OnRawUpdate(h RawHandler, opts ...HandlerOption)
	API() *tg.Client
	Self() *tg.User
}

Registrar abstracts the handler registration methods for plugins, controllers, and the client.

type SendOption

type SendOption func(b *message.Builder) error

SendOption configures a message dynamically before dispatch.

func WithMarkup

func WithMarkup(markup keyboard.ReplyMarkup) SendOption

WithMarkup assigns an inline or reply keyboard to the message.

type SessionStorage

type SessionStorage = session.Storage

SessionStorage is the contract for persisting a single MTProto session. It aliases gotd's session.Storage so implementations from gotd/contrib (file, bbolt, redis, ...) plug in directly.

type StateManager

type StateManager interface {
	GetState(ctx context.Context, chatID, userID int64) (string, error)
	SetState(ctx context.Context, chatID, userID int64, state string, ttl time.Duration) error
	ClearState(ctx context.Context, chatID, userID int64) error
	WatchExpired(ctx context.Context, handler func(chatID, userID int64)) error
}

StateManager manages conversational finite-state machine transitions independently of the request context.

func NewStateManager

func NewStateManager(storage fsm.Storage) StateManager

NewStateManager constructs a new StateManager with the given persistence storage backend.

type Update

type Update struct {
	// Kind defines the classification of the update.
	Kind UpdateKind

	// Message contains the normalized message object if applicable.
	Message *tg.Message

	// CallbackQuery contains the callback query information if applicable.
	CallbackQuery *tg.UpdateBotCallbackQuery

	// InlineQuery contains the inline search query if applicable.
	InlineQuery *tg.UpdateBotInlineQuery

	// ChatMember contains the chat participant update if applicable.
	ChatMember *tg.UpdateChatParticipant

	// ChannelMember contains the channel participant update if applicable.
	ChannelMember *tg.UpdateChannelParticipant

	// JoinRequest contains the pending join request info if applicable.
	JoinRequest *tg.UpdatePendingJoinRequests

	// Raw holds the original, unmodified raw update class from MTProto.
	Raw tg.UpdateClass

	// IsOutgoing indicates if this update was triggered synthetically
	// by an outgoing RPC call (e.g., self-sent messages).
	IsOutgoing bool
}

Update wraps various Telegram updates into a single normalized structure. This struct is designed to be lightweight and easily accessible.

func (*Update) ChatID

func (u *Update) ChatID() int64

ChatID extracts the ID of the chat/peer where this update took place. Returns 0 if the update is not associated with a specific chat.

func (*Update) GetMessage

func (u *Update) GetMessage() tg.MessageClass

GetMessage returns the associated message class, implementing AnswerableMessageUpdate.

func (*Update) SenderID

func (u *Update) SenderID() int64

SenderID extracts the user ID of the sender who triggered this update. Returns 0 if the sender cannot be identified.

type UpdateKind

type UpdateKind int

UpdateKind defines the normalized category of the incoming Telegram update.

const (
	// KindRaw represents an un-normalized raw update.
	KindRaw UpdateKind = iota
	// KindMessage represents a new incoming message update.
	KindMessage
	// KindEditedMessage represents an edited message update.
	KindEditedMessage
	// KindDeletedMessages represents a message deletion event.
	KindDeletedMessages
	// KindCallbackQuery represents an inline button click event.
	KindCallbackQuery
	// KindInlineQuery represents an inline search query.
	KindInlineQuery
	// KindChatMemberUpdated represents a chat member status change.
	KindChatMemberUpdated
	// KindChatJoinRequest represents a pending request to join a chat.
	KindChatJoinRequest
)

Directories

Path Synopsis
Package auth provides a headless, event-driven MTProto authentication state machine.
Package auth provides a headless, event-driven MTProto authentication state machine.
examples
bot command
Package main is a sample implementation of a Telegram bot using the tgbox framework.
Package main is a sample implementation of a Telegram bot using the tgbox framework.
Package filter provides built-in filter implementations for TGBox.
Package filter provides built-in filter implementations for TGBox.
internal
clock
Package clock provides a decorator around gotd/td/clock to control and suppress native timers safely.
Package clock provides a decorator around gotd/td/clock to control and suppress native timers safely.
dispatcher
Package dispatcher routes updates to handlers through a sharded worker pool, so updates that share a routing key (e.g.
Package dispatcher routes updates to handlers through a sharded worker pool, so updates that share a routing key (e.g.
engine
Package engine provides the core MTProto connection management.
Package engine provides the core MTProto connection management.
fsm
Package fsm implements a conversational Finite State Machine persistence layer.
Package fsm implements a conversational Finite State Machine persistence layer.
interceptor
Package interceptor provides decorators for tg.Invoker to sniff, augment, and control MTProto operations.
Package interceptor provides decorators for tg.Invoker to sniff, augment, and control MTProto operations.
keepalive
Package keepalive provides a fuzzed, zero-allocation heartbeat engine to bypass DPI heuristics.
Package keepalive provides a fuzzed, zero-allocation heartbeat engine to bypass DPI heuristics.
pool
Package pool manages a dynamic fleet of tgbox clients with LRU capacity bounds and idle garbage collection.
Package pool manages a dynamic fleet of tgbox clients with LRU capacity bounds and idle garbage collection.
router
Package router implements a high-performance parametric Radix Tree (Trie) designed for Telegram command routing and dynamic parameter extraction.
Package router implements a high-performance parametric Radix Tree (Trie) designed for Telegram command routing and dynamic parameter extraction.
storage
Package storage provides storage implementations for sessions and peers.
Package storage provides storage implementations for sessions and peers.
Package keyboard provides fluent builders for Telegram inline and reply keyboards.
Package keyboard provides fluent builders for Telegram inline and reply keyboards.
Package network provides physical layer emulation boundaries and traffic tuning parameters to safely bypass DPI and mimic official Telegram clients.
Package network provides physical layer emulation boundaries and traffic tuning parameters to safely bypass DPI and mimic official Telegram clients.
store

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL