telekit

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 29 Imported by: 0

README

telekit

A simple framework for building Telegram bots using the MTProto protocol via gotd/td.

Features

  • 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

Installation

go get github.com/en9inerd/telekit

Usage

package 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)
	}
}

Documentation

The package documentation is auto-generated using gomarkdoc.

telekit

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)
}

Index

Variables

Configuration errors

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")
)

Runtime errors

var (
    ErrBotNotRunning  = errors.New("telekit: bot is not running")
    ErrAlreadyRunning = errors.New("telekit: bot is already running")
)

func EntitiesToHTML

func EntitiesToHTML(text string, entities []tg.MessageEntityClass) string

EntitiesToHTML converts Telegram message entities to HTML. Properly handles overlapping/nested entities.

type Bot

Bot is the main Telegram bot client.

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

func New
func New(cfg Config) (*Bot, error)

New creates a new Bot with the given configuration.

func (*Bot) API
func (b *Bot) API() *tg.Client

API returns the raw tg.Client for advanced operations.

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
func (b *Bot) DeleteProfilePhotos(ctx context.Context) error

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) OnReady
func (b *Bot) OnReady(fn func(ctx context.Context))

OnReady sets a callback that's called when the bot is connected and ready.

func (*Bot) ResetCommands
func (b *Bot) ResetCommands(ctx context.Context) error

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
func (b *Bot) ResolveChannelInfo(ctx context.Context, username string) (*ChannelInfo, error)

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) Run
func (b *Bot) Run(ctx context.Context) error

Run starts the bot and blocks until the context is cancelled.

func (*Bot) SelfID
func (b *Bot) SelfID() int64

SelfID returns the bot's user ID.

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
func (b *Bot) SetProfilePhoto(ctx context.Context, photoURL string) error

SetProfilePhoto sets the bot's profile photo from a URL.

func (*Bot) SetProfilePhotoFromBytes
func (b *Bot) SetProfilePhotoFromBytes(ctx context.Context, data []byte, filename string) error

SetProfilePhotoFromBytes sets the bot's profile photo from raw bytes.

func (*Bot) SyncCommands
func (b *Bot) SyncCommands(ctx context.Context) error

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.

func (*Bot) UpdateBotInfo
func (b *Bot) UpdateBotInfo(ctx context.Context, info BotInfo) error

UpdateBotInfo updates the bot's profile information. Only non-empty fields are updated.

type BotInfo

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
}

type CallbackContext

CallbackContext provides access to callback query data.

type CallbackContext struct {
    context.Context
    // contains filtered or unexported fields
}

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

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
}

type CallbackFunc

CallbackFunc is the function signature for callback query handlers.

type CallbackFunc func(ctx *CallbackContext) error

type ChannelInfo

ChannelInfo contains resolved channel information.

type ChannelInfo struct {
    ID         int64
    AccessHash int64
    Username   string // empty for private channels
    Title      string
}

type CommandDef

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
}

type CommandLock

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
func NewCommandLock() *CommandLock

NewCommandLock creates a new CommandLock.

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

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
}

type CommandScope

CommandScope defines where a command should be available.

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

type Config

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
}

type Context

Context provides access to the current update and utility methods.

type Context struct {
    context.Context
    // contains filtered or unexported fields
}

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

API returns the raw tg.Client for advanced operations.

func (*Context) ChatID
func (c *Context) ChatID() int64

ChatID returns the chat ID where the message was sent.

func (*Context) Entities
func (c *Context) Entities() []tg.MessageEntityClass

Entities returns the message entities (formatting).

func (*Context) IsChannel
func (c *Context) IsChannel() bool

IsChannel returns true if the message is from a channel.

func (*Context) IsGroup
func (c *Context) IsGroup() bool

IsGroup returns true if the message is from a group.

func (*Context) IsOutgoing
func (c *Context) IsOutgoing() bool

IsOutgoing returns true if this is an outgoing message.

func (*Context) IsPrivate
func (c *Context) IsPrivate() bool

IsPrivate returns true if the message is from a private chat.

func (*Context) Media
func (c *Context) Media() tg.MessageMediaClass

Media returns the message media (photo, video, etc.).

func (*Context) Message
func (c *Context) Message() *tg.Message

Message returns the current message.

func (*Context) MessageID
func (c *Context) MessageID() int

MessageID returns the message ID.

func (*Context) Messages
func (c *Context) Messages() []*tg.Message

Messages returns all messages (for albums, otherwise single message).

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

Param returns a single parameter value.

func (*Context) Params
func (c *Context) Params() ParsedParams

Params returns the parsed command parameters.

func (*Context) Reply
func (c *Context) Reply(text string) error

Reply sends a reply to the current message.

func (*Context) Send
func (c *Context) Send(text string) error

Send sends a message to the current chat.

func (*Context) SendTo
func (c *Context) SendTo(userID int64, text string) error

SendTo sends a message to a specific user ID.

func (*Context) SenderID
func (c *Context) SenderID() int64

SenderID returns the sender's user ID.

func (*Context) Text
func (c *Context) Text() string

Text returns the message text.

func (*Context) Update
func (c *Context) Update() tg.UpdateClass

Update returns the raw update.

type DeleteContext

DeleteContext provides access to deleted message info.

type DeleteContext struct {
    context.Context
    // contains filtered or unexported fields
}

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

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
}

type DeleteFunc

DeleteFunc is the function signature for deleted message handlers.

type DeleteFunc func(ctx *DeleteContext) error

type Filter

Filter 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
}

type HandlerFunc

HandlerFunc is the function signature for event handlers.

type HandlerFunc func(ctx *Context) error

type ParamSchema

ParamSchema 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
}

type ParamType

ParamType defines the type of a command parameter.

type ParamType string

const (
    TypeString ParamType = "string"
    TypeInt    ParamType = "int"
    TypeBool   ParamType = "bool"
    TypeEnum   ParamType = "enum"
)

type Params

Params is a map of parameter names to their schemas.

type Params map[string]ParamSchema

type ParsedParams

ParsedParams holds validated parameter values.

type ParsedParams map[string]any

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

ScopeAllGroupAdmins makes the command available to all group admins.

type ScopeAllGroupAdmins struct{}

type ScopeAllGroups

ScopeAllGroups makes the command available in all group chats.

type ScopeAllGroups struct{}

type ScopeAllPrivate

ScopeAllPrivate makes the command available in all private chats.

type ScopeAllPrivate struct{}

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 ScopeChannel struct {
    ChannelID  int64
    AccessHash int64
}

type ScopeChannelAdmins

ScopeChannelAdmins makes the command available to admins in a specific channel/supergroup.

type ScopeChannelAdmins struct {
    ChannelID  int64
    AccessHash int64
}

type ScopeChannelUsername

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
}

type ScopeChat

ScopeChat makes the command available in a specific basic group. For supergroups/channels, use ScopeChannel.

type ScopeChat struct {
    ChatID int64
}

type ScopeChatAdmins

ScopeChatAdmins makes the command available to admins in a specific basic group. For supergroups/channels, use ScopeChannelAdmins.

type ScopeChatAdmins struct {
    ChatID int64
}

type ScopeChatMember

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
}

type ScopeChatMemberChannel

ScopeChatMemberChannel makes the command available to a specific user in a channel/supergroup.

type ScopeChatMemberChannel struct {
    ChannelID         int64
    ChannelAccessHash int64
    UserID            int64
    UserAccessHash    int64
}

type ScopeDefault

ScopeDefault makes the command available in all private chats.

type ScopeDefault struct{}

type ScopeUser

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
}

type ScopeUsername

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

License

MIT

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

Constants

This section is empty.

Variables

View Source
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

View Source
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 New

func New(cfg Config) (*Bot, error)

New creates a new Bot with the given configuration.

func (*Bot) API

func (b *Bot) API() *tg.Client

API returns the raw tg.Client for advanced operations.

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

func (b *Bot) DeleteProfilePhotos(ctx context.Context) error

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) OnReady

func (b *Bot) OnReady(fn func(ctx context.Context))

OnReady sets a callback that's called when the bot is connected and ready.

func (*Bot) ResetCommands

func (b *Bot) ResetCommands(ctx context.Context) error

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

func (b *Bot) ResolveChannelInfo(ctx context.Context, username string) (*ChannelInfo, error)

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) Run

func (b *Bot) Run(ctx context.Context) error

Run starts the bot and blocks until the context is cancelled.

func (*Bot) SelfID

func (b *Bot) SelfID() int64

SelfID returns the bot's user ID.

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

func (b *Bot) SetProfilePhoto(ctx context.Context, photoURL string) error

SetProfilePhoto sets the bot's profile photo from a URL.

func (*Bot) SetProfilePhotoFromBytes

func (b *Bot) SetProfilePhotoFromBytes(ctx context.Context, data []byte, filename string) error

SetProfilePhotoFromBytes sets the bot's profile photo from raw bytes.

func (*Bot) SyncCommands

func (b *Bot) SyncCommands(ctx context.Context) error

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.

func (*Bot) UpdateBotInfo

func (b *Bot) UpdateBotInfo(ctx context.Context, info BotInfo) error

UpdateBotInfo updates the bot's profile information. Only non-empty fields are updated.

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

type CallbackContext struct {
	context.Context
	// contains filtered or unexported fields
}

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

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 NewCommandLock

func NewCommandLock() *CommandLock

NewCommandLock creates a new CommandLock.

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

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

Context provides access to the current update and utility methods.

func (*Context) API

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

API returns the raw tg.Client for advanced operations.

func (*Context) ChatID

func (c *Context) ChatID() int64

ChatID returns the chat ID where the message was sent.

func (*Context) Entities

func (c *Context) Entities() []tg.MessageEntityClass

Entities returns the message entities (formatting).

func (*Context) IsChannel

func (c *Context) IsChannel() bool

IsChannel returns true if the message is from a channel.

func (*Context) IsGroup

func (c *Context) IsGroup() bool

IsGroup returns true if the message is from a group.

func (*Context) IsOutgoing

func (c *Context) IsOutgoing() bool

IsOutgoing returns true if this is an outgoing message.

func (*Context) IsPrivate

func (c *Context) IsPrivate() bool

IsPrivate returns true if the message is from a private chat.

func (*Context) Media

func (c *Context) Media() tg.MessageMediaClass

Media returns the message media (photo, video, etc.).

func (*Context) Message

func (c *Context) Message() *tg.Message

Message returns the current message.

func (*Context) MessageID

func (c *Context) MessageID() int

MessageID returns the message ID.

func (*Context) Messages

func (c *Context) Messages() []*tg.Message

Messages returns all messages (for albums, otherwise single message).

func (*Context) Param

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

Param returns a single parameter value.

func (*Context) Params

func (c *Context) Params() ParsedParams

Params returns the parsed command parameters.

func (*Context) Reply

func (c *Context) Reply(text string) error

Reply sends a reply to the current message.

func (*Context) Send

func (c *Context) Send(text string) error

Send sends a message to the current chat.

func (*Context) SendTo

func (c *Context) SendTo(userID int64, text string) error

SendTo sends a message to a specific user ID.

func (*Context) SenderID

func (c *Context) SenderID() int64

SenderID returns the sender's user ID.

func (*Context) Text

func (c *Context) Text() string

Text returns the message text.

func (*Context) Update

func (c *Context) Update() tg.UpdateClass

Update returns the raw update.

type DeleteContext

type DeleteContext struct {
	context.Context
	// contains filtered or unexported fields
}

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

type HandlerFunc func(ctx *Context) error

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 ParamType

type ParamType string

ParamType defines the type of a command parameter.

const (
	TypeString ParamType = "string"
	TypeInt    ParamType = "int"
	TypeBool   ParamType = "bool"
	TypeEnum   ParamType = "enum"
)

type Params

type Params map[string]ParamSchema

Params is a map of parameter names to their schemas.

type ParsedParams

type ParsedParams map[string]any

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

type ScopeChannel struct {
	ChannelID  int64
	AccessHash int64
}

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

type ScopeChannelAdmins struct {
	ChannelID  int64
	AccessHash int64
}

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

type ScopeChatMember struct {
	ChatID         int64
	UserID         int64
	UserAccessHash int64
}

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

type ScopeUser struct {
	UserID     int64
	AccessHash int64
}

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.

Jump to

Keyboard shortcuts

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