A simple framework for building Telegram bots using the MTProto protocol via gotd/td.
- Event handling with filters (channels, users, message types)
- Command parsing with typed parameter validation
- Album (grouped media) handling
- Command menu sync with scoped visibility
- Bot profile management
- Session management
go get github.com/en9inerd/telekitpackage main
import (
"context"
"log"
"github.com/en9inerd/telekit"
)
func main() {
bot, err := telekit.New(telekit.Config{
APIID: 12345,
APIHash: "your-api-hash",
BotToken: "your-bot-token",
})
if err != nil {
log.Fatal(err)
}
bot.Command("start", nil, func(ctx *telekit.Context) error {
return ctx.Reply("Hello!")
})
bot.OnChannelPost(channelID, func(ctx *telekit.Context) error {
// Handle new channel post
return nil
})
if err := bot.Run(context.Background()); err != nil {
log.Fatal(err)
}
}The package documentation is auto-generated using gomarkdoc.
import "github.com/en9inerd/telekit"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)
}
- Variables
- func EntitiesToHTML(text string, entities []tg.MessageEntityClass) string
- type Bot
- func New(cfg Config) (*Bot, error)
- 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, commands []CommandRegistration) 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
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")
)var (
ErrBotNotRunning = errors.New("telekit: bot is not running")
ErrAlreadyRunning = errors.New("telekit: bot is already running")
)func EntitiesToHTML(text string, entities []tg.MessageEntityClass) stringEntitiesToHTML converts Telegram message entities to HTML. Properly handles overlapping/nested entities.
Bot is the main Telegram bot client.
type Bot struct {
// contains filtered or unexported fields
}func New(cfg Config) (*Bot, error)New creates a new Bot with the given configuration.
func (b *Bot) API() *tg.ClientAPI returns the raw tg.Client for advanced operations.
func (b *Bot) Command(name string, params Params, fn HandlerFunc)Command registers a command handler with optional parameter schema.
func (b *Bot) CommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)CommandFrom registers a command handler that only responds to specific users.
func (b *Bot) CommandWithDesc(def CommandDef, fn HandlerFunc)CommandWithDesc registers a command with description (for menu sync).
func (b *Bot) CommandWithFilter(def CommandDef, filter Filter, fn HandlerFunc)CommandWithFilter registers a command handler with a custom filter.
func (b *Bot) DeleteProfilePhotos(ctx context.Context) errorDeleteProfilePhotos deletes the bot's profile photos.
func (b *Bot) LockedCommand(name string, params Params, fn HandlerFunc)LockedCommand registers a command with mutual exclusion.
func (b *Bot) LockedCommandFrom(name string, params Params, userIDs []int64, fn HandlerFunc)LockedCommandFrom registers a locked command for specific users.
func (b *Bot) LockedCommandWithDesc(def CommandDef, fn HandlerFunc)LockedCommandWithDesc registers a locked command with description.
func (b *Bot) OnAlbum(filter Filter, fn HandlerFunc)OnAlbum registers a handler for albums (grouped media).
func (b *Bot) OnCallback(filter CallbackFilter, fn CallbackFunc)OnCallback registers a handler for callback queries (inline button clicks).
func (b *Bot) OnCallbackPrefix(prefix string, fn CallbackFunc)OnCallbackPrefix registers a handler for callback queries with a specific data prefix.
func (b *Bot) OnChannelDelete(channelID int64, fn DeleteFunc)OnChannelDelete registers a handler for deleted channel messages.
func (b *Bot) OnChannelEdit(channelID int64, fn HandlerFunc)OnChannelEdit registers a handler for edited channel posts.
func (b *Bot) OnChannelPost(channelID int64, fn HandlerFunc)OnChannelPost registers a handler for new channel posts.
func (b *Bot) OnDelete(filter DeleteFilter, fn DeleteFunc)OnDelete registers a handler for deleted messages.
func (b *Bot) OnEdit(filter Filter, fn HandlerFunc)OnEdit registers a handler for edited messages.
func (b *Bot) OnMessage(filter Filter, fn HandlerFunc)OnMessage registers a handler for new messages.
func (b *Bot) OnPrivateMessage(userIDs []int64, fn HandlerFunc)OnPrivateMessage registers a handler for private messages from specific users.
func (b *Bot) OnReady(fn func(ctx context.Context))OnReady sets a callback that's called when the bot is connected and ready.
func (b *Bot) ResetCommands(ctx context.Context) errorResetCommands removes all bot commands from Telegram. It resets commands for all scope+langCode combinations that were previously saved.
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 (b *Bot) ResolveChannelInfo(ctx context.Context, username string) (*ChannelInfo, error)ResolveChannelInfo resolves a channel by username and returns full channel info.
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 (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 (b *Bot) Run(ctx context.Context) errorRun starts the bot and blocks until the context is cancelled.
func (b *Bot) SelfID() int64SelfID returns the bot's user ID.
func (b *Bot) SetCommandsForScope(ctx context.Context, scope CommandScope, langCode string, commands []CommandRegistration) errorSetCommandsForScope sets commands for a specific scope and language. Username-based scopes (ScopeChannelUsername, ScopeUsername) are resolved automatically.
func (b *Bot) SetProfilePhoto(ctx context.Context, photoURL string) errorSetProfilePhoto sets the bot's profile photo from a URL.
func (b *Bot) SetProfilePhotoFromBytes(ctx context.Context, data []byte, filename string) errorSetProfilePhotoFromBytes sets the bot's profile photo from raw bytes.
func (b *Bot) SyncCommands(ctx context.Context) errorSyncCommands 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.
func (b *Bot) UpdateBotInfo(ctx context.Context, info BotInfo) errorUpdateBotInfo updates the bot's profile information. Only non-empty fields are updated.
BotInfo holds bot profile information.
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
}CallbackContext provides access to callback query data.
type CallbackContext struct {
context.Context
// contains filtered or unexported fields
}func (c *CallbackContext) API() *tg.ClientAPI returns the raw tg.Client for advanced operations.
func (c *CallbackContext) Answer(text string, alert bool) errorAnswer sends an answer to the callback query (toast/alert).
func (c *CallbackContext) AnswerEmpty() errorAnswerEmpty acknowledges the callback without showing anything.
func (c *CallbackContext) ChatID() int64ChatID returns the chat ID where the button was clicked.
func (c *CallbackContext) Data() stringData returns the callback data string.
func (c *CallbackContext) MessageID() intMessageID returns the message ID containing the button.
func (c *CallbackContext) Query() *tg.UpdateBotCallbackQueryQuery returns the raw callback query.
func (c *CallbackContext) UserID() int64UserID returns the user who clicked the button.
CallbackFilter defines conditions for callback query handlers.
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
}CallbackFunc is the function signature for callback query handlers.
type CallbackFunc func(ctx *CallbackContext) errorChannelInfo contains resolved channel information.
type ChannelInfo struct {
ID int64
AccessHash int64
Username string // empty for private channels
Title string
}CommandDef defines a command with its metadata.
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
}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.
type CommandLock struct {
// contains filtered or unexported fields
}func NewCommandLock() *CommandLockNewCommandLock creates a new CommandLock.
func (l *CommandLock) TryAcquire(userID int64, acquire bool) boolTryAcquire 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 (l *CommandLock) Unlock(userID int64)Unlock releases the lock for user.
CommandRegistration holds command info for syncing to Telegram.
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
}CommandScope defines where a command should be available.
type CommandScope interface {
// contains filtered or unexported methods
}Config holds the configuration for the bot.
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
}Context provides access to the current update and utility methods.
type Context struct {
context.Context
// contains filtered or unexported fields
}func (c *Context) API() *tg.ClientAPI returns the raw tg.Client for advanced operations.
func (c *Context) ChatID() int64ChatID returns the chat ID where the message was sent.
func (c *Context) Entities() []tg.MessageEntityClassEntities returns the message entities (formatting).
func (c *Context) IsChannel() boolIsChannel returns true if the message is from a channel.
func (c *Context) IsGroup() boolIsGroup returns true if the message is from a group.
func (c *Context) IsOutgoing() boolIsOutgoing returns true if this is an outgoing message.
func (c *Context) IsPrivate() boolIsPrivate returns true if the message is from a private chat.
func (c *Context) Media() tg.MessageMediaClassMedia returns the message media (photo, video, etc.).
func (c *Context) Message() *tg.MessageMessage returns the current message.
func (c *Context) MessageID() intMessageID returns the message ID.
func (c *Context) Messages() []*tg.MessageMessages returns all messages (for albums, otherwise single message).
func (c *Context) Param(key string) anyParam returns a single parameter value.
func (c *Context) Params() ParsedParamsParams returns the parsed command parameters.
func (c *Context) Reply(text string) errorReply sends a reply to the current message.
func (c *Context) Send(text string) errorSend sends a message to the current chat.
func (c *Context) SendTo(userID int64, text string) errorSendTo sends a message to a specific user ID.
func (c *Context) SenderID() int64SenderID returns the sender's user ID.
func (c *Context) Text() stringText returns the message text.
func (c *Context) Update() tg.UpdateClassUpdate returns the raw update.
DeleteContext provides access to deleted message info.
type DeleteContext struct {
context.Context
// contains filtered or unexported fields
}func (c *DeleteContext) API() *tg.ClientAPI returns the raw tg.Client for advanced operations.
func (c *DeleteContext) ChannelID() int64ChannelID returns the channel ID (for channel deletes).
func (c *DeleteContext) ChatID() int64ChatID returns the chat ID (for non-channel deletes).
func (c *DeleteContext) MessageIDs() []intMessageIDs returns the IDs of deleted messages.
DeleteFilter defines conditions for delete handlers.
type DeleteFilter struct {
// Chats filters by chat IDs.
Chats []int64
// Custom is a custom filter function.
Custom func(ctx *DeleteContext) bool
}DeleteFunc is the function signature for deleted message handlers.
type DeleteFunc func(ctx *DeleteContext) errorFilter defines conditions for when a handler should be invoked.
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
}HandlerFunc is the function signature for event handlers.
type HandlerFunc func(ctx *Context) errorParamSchema defines validation rules for a command parameter.
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
}ParamType defines the type of a command parameter.
type ParamType stringconst (
TypeString ParamType = "string"
TypeInt ParamType = "int"
TypeBool ParamType = "bool"
TypeEnum ParamType = "enum"
)Params is a map of parameter names to their schemas.
type Params map[string]ParamSchemaParsedParams holds validated parameter values.
type ParsedParams map[string]anyfunc (p ParsedParams) Bool(key string) boolBool returns the bool value of a parameter.
func (p ParsedParams) Has(key string) boolHas returns true if the parameter was provided.
func (p ParsedParams) Int(key string) int64Int returns the int64 value of a parameter.
func (p ParsedParams) String(key string) stringString returns the string value of a parameter.
ScopeAllGroupAdmins makes the command available to all group admins.
type ScopeAllGroupAdmins struct{}ScopeAllGroups makes the command available in all group chats.
type ScopeAllGroups struct{}ScopeAllPrivate makes the command available in all private chats.
type ScopeAllPrivate struct{}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 ScopeChannel struct {
ChannelID int64
AccessHash int64
}ScopeChannelAdmins makes the command available to admins in a specific channel/supergroup.
type ScopeChannelAdmins struct {
ChannelID int64
AccessHash int64
}ScopeChannelUsername makes the command available in a channel by username. The username is resolved to channel ID and access hash at sync time.
type ScopeChannelUsername struct {
Username string // Without @ prefix
}ScopeChat makes the command available in a specific basic group. For supergroups/channels, use ScopeChannel.
type ScopeChat struct {
ChatID int64
}ScopeChatAdmins makes the command available to admins in a specific basic group. For supergroups/channels, use ScopeChannelAdmins.
type ScopeChatAdmins struct {
ChatID int64
}ScopeChatMember makes the command available to a specific user in a basic group chat. For supergroups, use ScopeChatMemberChannel.
type ScopeChatMember struct {
ChatID int64
UserID int64
UserAccessHash int64
}ScopeChatMemberChannel makes the command available to a specific user in a channel/supergroup.
type ScopeChatMemberChannel struct {
ChannelID int64
ChannelAccessHash int64
UserID int64
UserAccessHash int64
}ScopeDefault makes the command available in all private chats.
type ScopeDefault struct{}ScopeUser makes the command available to a specific user in private chat. Use ScopeUsername if you only have the username.
type ScopeUser struct {
UserID int64
AccessHash int64
}ScopeUsername makes the command available to a user by username. The username is resolved to user ID and access hash at sync time.
type ScopeUsername struct {
Username string // Without @ prefix
}Generated by gomarkdoc
MIT