Documentation
¶
Overview ¶
Package telekit provides a simple framework for building Telegram bots using the MTProto protocol via gotd/td.
It simplifies common bot development tasks such as:
- Event handling with filters (channels, users, message types)
- Command parsing with typed parameter validation
- Album (grouped media) handling
- Session management
Basic usage:
bot, err := telekit.New(telekit.Config{
APIID: 12345,
APIHash: "your-api-hash",
BotToken: "your-bot-token",
})
if err != nil {
log.Fatal(err)
}
bot.OnChannelPost(channelID, func(ctx *telekit.Context) error {
// Handle new channel post
return nil
})
bot.Command("start", nil, func(ctx *telekit.Context) error {
return ctx.Reply("Hello!")
})
if err := bot.Run(context.Background()); err != nil {
log.Fatal(err)
}
Index ¶
- Variables
- func EntitiesToHTML(text string, entities []tg.MessageEntityClass) string
- type Bot
- func (b *Bot) API() *tg.Client
- func (b *Bot) Command(name string, params Params, fn HandlerFunc)
- func (b *Bot) CommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)
- func (b *Bot) CommandWithDesc(def CommandDef, fn HandlerFunc)
- func (b *Bot) CommandWithFilter(def CommandDef, filter Filter, fn HandlerFunc)
- func (b *Bot) DeleteProfilePhotos(ctx context.Context) error
- func (b *Bot) LockedCommand(name string, params Params, fn HandlerFunc)
- func (b *Bot) LockedCommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)
- func (b *Bot) LockedCommandWithDesc(def CommandDef, fn HandlerFunc)
- func (b *Bot) OnAlbum(filter Filter, fn HandlerFunc)
- func (b *Bot) OnCallback(filter CallbackFilter, fn CallbackFunc)
- func (b *Bot) OnCallbackPrefix(prefix string, fn CallbackFunc)
- func (b *Bot) OnChannelDelete(channelID int64, fn DeleteFunc)
- func (b *Bot) OnChannelEdit(channelID int64, fn HandlerFunc)
- func (b *Bot) OnChannelPost(channelID int64, fn HandlerFunc)
- func (b *Bot) OnDelete(filter DeleteFilter, fn DeleteFunc)
- func (b *Bot) OnEdit(filter Filter, fn HandlerFunc)
- func (b *Bot) OnMessage(filter Filter, fn HandlerFunc)
- func (b *Bot) OnPrivateMessage(userIDs []int64, fn HandlerFunc)
- func (b *Bot) OnReady(fn func(ctx context.Context))
- func (b *Bot) ResetCommands(ctx context.Context) error
- func (b *Bot) ResolveChannel(ctx context.Context, username string) (channelID, accessHash int64, err error)
- func (b *Bot) ResolveChannelInfo(ctx context.Context, username string) (*ChannelInfo, error)
- func (b *Bot) ResolveIdentifier(ctx context.Context, identifier string, isChannel bool) (id, accessHash int64, title string, err error)
- func (b *Bot) ResolveUser(ctx context.Context, username string) (userID, accessHash int64, err error)
- func (b *Bot) Run(ctx context.Context) error
- func (b *Bot) SelfID() int64
- func (b *Bot) SetCommandsForScope(ctx context.Context, scope CommandScope, langCode string, ...) error
- func (b *Bot) SetProfilePhoto(ctx context.Context, photoURL string) error
- func (b *Bot) SetProfilePhotoFromBytes(ctx context.Context, data []byte, filename string) error
- func (b *Bot) SyncCommands(ctx context.Context) error
- func (b *Bot) UpdateBotInfo(ctx context.Context, info BotInfo) error
- type BotInfo
- type CallbackContext
- func (c *CallbackContext) API() *tg.Client
- func (c *CallbackContext) Answer(text string, alert bool) error
- func (c *CallbackContext) AnswerEmpty() error
- func (c *CallbackContext) ChatID() int64
- func (c *CallbackContext) Data() string
- func (c *CallbackContext) MessageID() int
- func (c *CallbackContext) Query() *tg.UpdateBotCallbackQuery
- func (c *CallbackContext) UserID() int64
- type CallbackFilter
- type CallbackFunc
- type ChannelInfo
- type CommandDef
- type CommandLock
- type CommandRegistration
- type CommandScope
- type Config
- type Context
- func (c *Context) API() *tg.Client
- func (c *Context) ChatID() int64
- func (c *Context) Entities() []tg.MessageEntityClass
- func (c *Context) IsChannel() bool
- func (c *Context) IsGroup() bool
- func (c *Context) IsOutgoing() bool
- func (c *Context) IsPrivate() bool
- func (c *Context) Media() tg.MessageMediaClass
- func (c *Context) Message() *tg.Message
- func (c *Context) MessageID() int
- func (c *Context) Messages() []*tg.Message
- func (c *Context) Param(key string) any
- func (c *Context) Params() ParsedParams
- func (c *Context) Reply(text string) error
- func (c *Context) Send(text string) error
- func (c *Context) SendTo(userID int64, text string) error
- func (c *Context) SenderID() int64
- func (c *Context) Text() string
- func (c *Context) Update() tg.UpdateClass
- type DeleteContext
- type DeleteFilter
- type DeleteFunc
- type Filter
- type HandlerFunc
- type ParamSchema
- type ParamType
- type Params
- type ParsedParams
- type ScopeAllGroupAdmins
- type ScopeAllGroups
- type ScopeAllPrivate
- type ScopeChannel
- type ScopeChannelAdmins
- type ScopeChannelUsername
- type ScopeChat
- type ScopeChatAdmins
- type ScopeChatMember
- type ScopeChatMemberChannel
- type ScopeDefault
- type ScopeUser
- type ScopeUsername
Constants ¶
This section is empty.
Variables ¶
var ( ErrMissingAPIID = errors.New("telekit: API ID is required") ErrMissingAPIHash = errors.New("telekit: API hash is required") ErrMissingBotToken = errors.New("telekit: bot token is required") )
Configuration errors
var ( ErrBotNotRunning = errors.New("telekit: bot is not running") ErrAlreadyRunning = errors.New("telekit: bot is already running") )
Runtime errors
Functions ¶
func EntitiesToHTML ¶ added in v0.2.0
func EntitiesToHTML(text string, entities []tg.MessageEntityClass) string
EntitiesToHTML converts Telegram message entities to HTML. Properly handles overlapping/nested entities.
Types ¶
type Bot ¶
type Bot struct {
// contains filtered or unexported fields
}
Bot is the main Telegram bot client.
func (*Bot) Command ¶
func (b *Bot) Command(name string, params Params, fn HandlerFunc)
Command registers a command handler with optional parameter schema.
func (*Bot) CommandFrom ¶
func (b *Bot) CommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)
CommandFrom registers a command handler that only responds to specific users.
func (*Bot) CommandWithDesc ¶
func (b *Bot) CommandWithDesc(def CommandDef, fn HandlerFunc)
CommandWithDesc registers a command with description (for menu sync).
func (*Bot) CommandWithFilter ¶
func (b *Bot) CommandWithFilter(def CommandDef, filter Filter, fn HandlerFunc)
CommandWithFilter registers a command handler with a custom filter.
func (*Bot) DeleteProfilePhotos ¶
DeleteProfilePhotos deletes the bot's profile photos.
func (*Bot) LockedCommand ¶
func (b *Bot) LockedCommand(name string, params Params, fn HandlerFunc)
LockedCommand registers a command with mutual exclusion.
func (*Bot) LockedCommandFrom ¶
func (b *Bot) LockedCommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)
LockedCommandFrom registers a locked command for specific users.
func (*Bot) LockedCommandWithDesc ¶
func (b *Bot) LockedCommandWithDesc(def CommandDef, fn HandlerFunc)
LockedCommandWithDesc registers a locked command with description.
func (*Bot) OnAlbum ¶
func (b *Bot) OnAlbum(filter Filter, fn HandlerFunc)
OnAlbum registers a handler for albums (grouped media).
func (*Bot) OnCallback ¶
func (b *Bot) OnCallback(filter CallbackFilter, fn CallbackFunc)
OnCallback registers a handler for callback queries (inline button clicks).
func (*Bot) OnCallbackPrefix ¶
func (b *Bot) OnCallbackPrefix(prefix string, fn CallbackFunc)
OnCallbackPrefix registers a handler for callback queries with a specific data prefix.
func (*Bot) OnChannelDelete ¶
func (b *Bot) OnChannelDelete(channelID int64, fn DeleteFunc)
OnChannelDelete registers a handler for deleted channel messages.
func (*Bot) OnChannelEdit ¶
func (b *Bot) OnChannelEdit(channelID int64, fn HandlerFunc)
OnChannelEdit registers a handler for edited channel posts.
func (*Bot) OnChannelPost ¶
func (b *Bot) OnChannelPost(channelID int64, fn HandlerFunc)
OnChannelPost registers a handler for new channel posts.
func (*Bot) OnDelete ¶
func (b *Bot) OnDelete(filter DeleteFilter, fn DeleteFunc)
OnDelete registers a handler for deleted messages.
func (*Bot) OnEdit ¶
func (b *Bot) OnEdit(filter Filter, fn HandlerFunc)
OnEdit registers a handler for edited messages.
func (*Bot) OnMessage ¶
func (b *Bot) OnMessage(filter Filter, fn HandlerFunc)
OnMessage registers a handler for new messages.
func (*Bot) OnPrivateMessage ¶
func (b *Bot) OnPrivateMessage(userIDs []int64, fn HandlerFunc)
OnPrivateMessage registers a handler for private messages from specific users.
func (*Bot) ResetCommands ¶
ResetCommands removes all bot commands from Telegram. It resets commands for all scope+langCode combinations that were previously saved.
func (*Bot) ResolveChannel ¶
func (b *Bot) ResolveChannel(ctx context.Context, username string) (channelID, accessHash int64, err error)
ResolveChannel resolves a channel by username and returns its ID and access hash.
func (*Bot) ResolveChannelInfo ¶
ResolveChannelInfo resolves a channel by username and returns full channel info.
func (*Bot) ResolveIdentifier ¶
func (b *Bot) ResolveIdentifier(ctx context.Context, identifier string, isChannel bool) (id, accessHash int64, title string, err error)
ResolveIdentifier resolves an identifier (numeric ID or @username) and returns ID, access hash, and display title. For channels, title fallback order: username || title. For users, title is empty.
func (*Bot) ResolveUser ¶
func (b *Bot) ResolveUser(ctx context.Context, username string) (userID, accessHash int64, err error)
ResolveUser resolves a user by username and returns their ID and access hash.
func (*Bot) SetCommandsForScope ¶
func (b *Bot) SetCommandsForScope(ctx context.Context, scope CommandScope, langCode string, commands []CommandRegistration) error
SetCommandsForScope sets commands for a specific scope and language. Username-based scopes (ScopeChannelUsername, ScopeUsername) are resolved automatically.
func (*Bot) SetProfilePhoto ¶
SetProfilePhoto sets the bot's profile photo from a URL.
func (*Bot) SetProfilePhotoFromBytes ¶
SetProfilePhotoFromBytes sets the bot's profile photo from raw bytes.
func (*Bot) SyncCommands ¶
SyncCommands registers all commands with Telegram so they appear in the bot menu. It resets previous command scopes and sets new ones based on registered commands. Should be called after all commands are registered and the bot is running.
type BotInfo ¶
type BotInfo struct {
// Name is the bot's display name.
Name string
// About is the short description shown in the bot's profile.
About string
// Description is the longer description shown when starting the bot.
Description string
// LangCode is the language code for this info.
// Empty string means default language.
LangCode string
}
BotInfo holds bot profile information.
type CallbackContext ¶
CallbackContext provides access to callback query data.
func (*CallbackContext) API ¶
func (c *CallbackContext) API() *tg.Client
API returns the raw tg.Client for advanced operations.
func (*CallbackContext) Answer ¶
func (c *CallbackContext) Answer(text string, alert bool) error
Answer sends an answer to the callback query (toast/alert).
func (*CallbackContext) AnswerEmpty ¶
func (c *CallbackContext) AnswerEmpty() error
AnswerEmpty acknowledges the callback without showing anything.
func (*CallbackContext) ChatID ¶
func (c *CallbackContext) ChatID() int64
ChatID returns the chat ID where the button was clicked.
func (*CallbackContext) Data ¶
func (c *CallbackContext) Data() string
Data returns the callback data string.
func (*CallbackContext) MessageID ¶
func (c *CallbackContext) MessageID() int
MessageID returns the message ID containing the button.
func (*CallbackContext) Query ¶
func (c *CallbackContext) Query() *tg.UpdateBotCallbackQuery
Query returns the raw callback query.
func (*CallbackContext) UserID ¶
func (c *CallbackContext) UserID() int64
UserID returns the user who clicked the button.
type CallbackFilter ¶
type CallbackFilter struct {
// Data filters by callback data prefix.
DataPrefix string
// Users filters by user IDs.
Users []int64
// Custom is a custom filter function.
Custom func(ctx *CallbackContext) bool
}
CallbackFilter defines conditions for callback query handlers.
type CallbackFunc ¶
type CallbackFunc func(ctx *CallbackContext) error
CallbackFunc is the function signature for callback query handlers.
type ChannelInfo ¶
type ChannelInfo struct {
ID int64
AccessHash int64
Username string // empty for private channels
Title string
}
ChannelInfo contains resolved channel information.
type CommandDef ¶
type CommandDef struct {
// Name is the command name without the leading slash.
Name string
// Description is shown in the bot's command menu.
Description string
// Params defines the parameter schema for validation.
Params Params
// Locked enables mutual exclusion for this command.
// When true, this command blocks other locked commands for the same user.
Locked bool
// Scope defines where the command is available (default: ScopeDefault).
Scope CommandScope
// LangCode is the language code for this command's description.
LangCode string
}
CommandDef defines a command with its metadata.
type CommandLock ¶
type CommandLock struct {
// contains filtered or unexported fields
}
CommandLock provides mutual exclusion for locked commands per user. Locked commands block other locked commands for the same user. Non-locked commands always run without blocking.
func (*CommandLock) TryAcquire ¶
func (l *CommandLock) TryAcquire(userID int64, acquire bool) bool
TryAcquire checks if command can proceed and optionally acquires lock. If acquire is false, always returns true. If acquire is true, returns true only if lock was acquired.
func (*CommandLock) Unlock ¶
func (l *CommandLock) Unlock(userID int64)
Unlock releases the lock for user.
type CommandRegistration ¶
type CommandRegistration struct {
// Name is the command name without leading slash.
Name string
// Description is shown in the bot menu.
Description string
// Scope defines where the command is available.
// Defaults to ScopeDefault if nil.
Scope CommandScope
// LangCode is the language code for this registration.
// Empty string means all languages.
LangCode string
}
CommandRegistration holds command info for syncing to Telegram.
type CommandScope ¶
type CommandScope interface {
// contains filtered or unexported methods
}
CommandScope defines where a command should be available.
type Config ¶
type Config struct {
// APIID is the Telegram API ID from https://my.telegram.org
APIID int
// APIHash is the Telegram API hash from https://my.telegram.org
APIHash string
// BotToken is the bot token from @BotFather
BotToken string
// SessionDir is the directory for storing session data.
// Defaults to "./session" if empty.
SessionDir string
// Logger is the logger to use. If nil, a default logger is created.
Logger *slog.Logger
// DeviceModel is the device model to report to Telegram.
// Defaults to "telekit" if empty.
DeviceModel string
// SystemVersion is the system version to report to Telegram.
// Defaults to "1.0" if empty.
SystemVersion string
// AppVersion is the app version to report to Telegram.
// Defaults to "1.0.0" if empty.
AppVersion string
// LangCode is the language code to report to Telegram.
// Defaults to "en" if empty.
LangCode string
// SystemLangCode is the system language code.
// Defaults to "en" if empty.
SystemLangCode string
// AlbumTimeout is the duration to wait for grouped messages.
// Defaults to 500ms if zero.
AlbumTimeout time.Duration
// SyncCommands automatically syncs commands to Telegram after OnReady.
// Commands registered in OnReady will be included.
SyncCommands bool
// BotInfo is the bot profile information to set on startup.
// If set, the bot info will be updated when the bot starts.
BotInfo *BotInfo
// ProfilePhotoURL is the URL of the bot's profile photo.
// If set, the profile photo will be updated when the bot starts.
ProfilePhotoURL string
// Verbose enables debug logging for the MTProto client.
Verbose bool
}
Config holds the configuration for the bot.
type Context ¶
Context provides access to the current update and utility methods.
func (*Context) Entities ¶
func (c *Context) Entities() []tg.MessageEntityClass
Entities returns the message entities (formatting).
func (*Context) IsOutgoing ¶
IsOutgoing returns true if this is an outgoing message.
func (*Context) Media ¶
func (c *Context) Media() tg.MessageMediaClass
Media returns the message media (photo, video, etc.).
func (*Context) Params ¶
func (c *Context) Params() ParsedParams
Params returns the parsed command parameters.
type DeleteContext ¶
DeleteContext provides access to deleted message info.
func (*DeleteContext) API ¶
func (c *DeleteContext) API() *tg.Client
API returns the raw tg.Client for advanced operations.
func (*DeleteContext) ChannelID ¶
func (c *DeleteContext) ChannelID() int64
ChannelID returns the channel ID (for channel deletes).
func (*DeleteContext) ChatID ¶
func (c *DeleteContext) ChatID() int64
ChatID returns the chat ID (for non-channel deletes).
func (*DeleteContext) MessageIDs ¶
func (c *DeleteContext) MessageIDs() []int
MessageIDs returns the IDs of deleted messages.
type DeleteFilter ¶
type DeleteFilter struct {
// Chats filters by chat IDs.
Chats []int64
// Custom is a custom filter function.
Custom func(ctx *DeleteContext) bool
}
DeleteFilter defines conditions for delete handlers.
type DeleteFunc ¶
type DeleteFunc func(ctx *DeleteContext) error
DeleteFunc is the function signature for deleted message handlers.
type Filter ¶
type Filter struct {
// Chats filters by chat IDs (channels, groups, users).
// Empty means all chats.
Chats []int64
// Users filters by user IDs.
// Empty means all users.
Users []int64
// Incoming filters for incoming messages only.
Incoming bool
// Outgoing filters for outgoing messages only.
Outgoing bool
// Custom is a custom filter function.
// Return true to process the message, false to skip.
Custom func(ctx *Context) bool
}
Filter defines conditions for when a handler should be invoked.
type HandlerFunc ¶
HandlerFunc is the function signature for event handlers.
type ParamSchema ¶
type ParamSchema struct {
// Type is the parameter type (string, int, bool, enum).
Type ParamType
// Required indicates if the parameter must be provided.
Required bool
// Default is the default value if not provided.
Default any
// Enum contains allowed values for enum type.
Enum []string
// Description is a human-readable description for help text.
Description string
}
ParamSchema defines validation rules for a command parameter.
type Params ¶
type Params map[string]ParamSchema
Params is a map of parameter names to their schemas.
type ParsedParams ¶
ParsedParams holds validated parameter values.
func (ParsedParams) Bool ¶
func (p ParsedParams) Bool(key string) bool
Bool returns the bool value of a parameter.
func (ParsedParams) Has ¶
func (p ParsedParams) Has(key string) bool
Has returns true if the parameter was provided.
func (ParsedParams) Int ¶
func (p ParsedParams) Int(key string) int64
Int returns the int64 value of a parameter.
func (ParsedParams) String ¶
func (p ParsedParams) String(key string) string
String returns the string value of a parameter.
type ScopeAllGroupAdmins ¶
type ScopeAllGroupAdmins struct{}
ScopeAllGroupAdmins makes the command available to all group admins.
type ScopeAllGroups ¶
type ScopeAllGroups struct{}
ScopeAllGroups makes the command available in all group chats.
type ScopeAllPrivate ¶
type ScopeAllPrivate struct{}
ScopeAllPrivate makes the command available in all private chats.
type ScopeChannel ¶
ScopeChannel makes the command available in a specific channel/supergroup. The bot must be an admin in the channel. Use ScopeChannelUsername if you only have the username.
type ScopeChannelAdmins ¶
ScopeChannelAdmins makes the command available to admins in a specific channel/supergroup.
type ScopeChannelUsername ¶
type ScopeChannelUsername struct {
Username string // Without @ prefix
}
ScopeChannelUsername makes the command available in a channel by username. The username is resolved to channel ID and access hash at sync time.
type ScopeChat ¶
type ScopeChat struct {
ChatID int64
}
ScopeChat makes the command available in a specific basic group. For supergroups/channels, use ScopeChannel.
type ScopeChatAdmins ¶
type ScopeChatAdmins struct {
ChatID int64
}
ScopeChatAdmins makes the command available to admins in a specific basic group. For supergroups/channels, use ScopeChannelAdmins.
type ScopeChatMember ¶
ScopeChatMember makes the command available to a specific user in a basic group chat. For supergroups, use ScopeChatMemberChannel.
type ScopeChatMemberChannel ¶
type ScopeChatMemberChannel struct {
ChannelID int64
ChannelAccessHash int64
UserID int64
UserAccessHash int64
}
ScopeChatMemberChannel makes the command available to a specific user in a channel/supergroup.
type ScopeDefault ¶
type ScopeDefault struct{}
ScopeDefault makes the command available in all private chats.
type ScopeUser ¶
ScopeUser makes the command available to a specific user in private chat. Use ScopeUsername if you only have the username.
type ScopeUsername ¶
type ScopeUsername struct {
Username string // Without @ prefix
}
ScopeUsername makes the command available to a user by username. The username is resolved to user ID and access hash at sync time.