adapter

package
v1.0.0-beta23 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: GPL-3.0 Imports: 22 Imported by: 0

Documentation

Overview

Package adapter provides the CommandRegistry for registering Telegram bot commands.

Package adapter provides conversation management functionality for the gotg framework. It enables handling multi-step conversations with users through state tracking and message filtering capabilities.

Index

Constants

View Source
const (
	FilterSearch   = functions.FilterSearch
	FilterRecent   = functions.FilterRecent
	FilterAdmins   = functions.FilterAdmins
	FilterBots     = functions.FilterBots
	FilterKicked   = functions.FilterKicked
	FilterBanned   = functions.FilterBanned
	FilterContacts = functions.FilterContacts
)
View Source
const (
	ActionSend   = "send"
	ActionEdit   = "edit"
	ActionDelete = "delete"
)
View Source
const (
	StatusSucceeded = "succeeded"
	StatusFailed    = "failed"
)
View Source
const (
	HTML       = "HTML"
	Markdown   = "Markdown"
	MarkdownV2 = "MarkdownV2"
	ModeNone   = ""
)

Parse mode constants

Variables

This section is empty.

Functions

func SetTranslator

func SetTranslator(t Translator)

Types

type BotCmd

type BotCmd struct {
	// Command is the command name without the leading slash (e.g., "start", not "/start").
	// Must be lowercase, 1-32 characters, and contain only letters, digits, and underscores.
	Command string
	// Description is a short description shown in the command menu, 1-256 characters.
	Description string
}

BotCmd represents a single bot command with its command string and description. Commands are shown in the Telegram client's command menu when users type "/".

Example:

cmd := BotCmd{
    Command:     "start",
    Description: "Start the bot",
}

type CallbackOptions

type CallbackOptions struct {
	// Alert shows the answer as a popup alert instead of a toast notification.
	Alert bool
	// CacheTime is the time in seconds for which the result of a callback query
	// may be cached on the client side.
	CacheTime int
	// URL is the URL to open as a game or in-browser app.
	URL string
}

CallbackOptions contains optional parameters for answering callback queries.

type ChatMembersFilter

type ChatMembersFilter = functions.ChatMembersFilter

type CommandRegistry

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

CommandRegistry builds and registers Telegram bot commands using a fluent API. It allows setting different commands for group chats and private chats.

Telegram supports different command sets based on the chat type:

  • Group commands: shown in groups and supergroups
  • Private commands: shown in private chats with the bot

Example:

err := NewCommandRegistry(raw, ctx).
    AddGroup(
        BotCmd{Command: "help", Description: "Show help"},
        BotCmd{Command: "settings", Description: "Bot settings"},
    ).
    AddPrivate(
        BotCmd{Command: "start", Description: "Start the bot"},
    ).
    WithLangCode("en").
    Register()
if err != nil {
    log.Fatal(err)
}

func NewCommandRegistry

func NewCommandRegistry(raw *tg.Client, ctx context.Context) *CommandRegistry

NewCommandRegistry creates a new command registry builder.

Parameters:

  • raw: The raw tg.Client from gotd/td for making API calls.
  • ctx: The context for the API requests, can be context.Background() or a timeout context.

Example:

registry := NewCommandRegistry(client.API(), context.Background())

func (*CommandRegistry) AddGroup

func (r *CommandRegistry) AddGroup(cmds ...BotCmd) *CommandRegistry

AddGroup adds commands for group and supergroup chats. These commands appear in the command menu when users type "/" in groups.

Group commands are typically for features that make sense in a group context:

  • Games and interactive features
  • Group management commands
  • Commands that affect the whole group

Example:

NewCommandRegistry(raw, ctx).
    AddGroup(
        BotCmd{Command: "startmirror", Description: "بدء لعبة المرآة"},
        BotCmd{Command: "startcity", Description: "بدء لعبة المدينة الفاسدة"},
        BotCmd{Command: "roulette", Description: "بدء لعبة الروليت"},
        BotCmd{Command: "players", Description: "عرض لاعبي اللعبة الحالية"},
    ).
    Register()

func (*CommandRegistry) AddGroupMap

func (r *CommandRegistry) AddGroupMap(cmds map[string]string) *CommandRegistry

AddGroupMap adds commands from a map for group chats. This is convenient when commands are defined in a configuration or i18n structure.

Example:

groupCmds := map[string]string{
    "startmirror": "بدء لعبة المرآة",
    "startcity":   "بدء لعبة المدينة الفاسدة",
    "roulette":    "بدء لعبة الروليت",
}

NewCommandRegistry(raw, ctx).
    AddGroupMap(groupCmds).
    Register()

func (*CommandRegistry) AddPrivate

func (r *CommandRegistry) AddPrivate(cmds ...BotCmd) *CommandRegistry

AddPrivate adds commands for private chats with the bot. These commands appear in the command menu when users type "/" in direct messages.

Private commands are typically for:

  • Bot onboarding (/start)
  • User-specific settings
  • Personal features

Example:

NewCommandRegistry(raw, ctx).
    AddPrivate(
        BotCmd{Command: "start", Description: "تشغيل البوت"},
        BotCmd{Command: "help", Description: "المساعدة"},
        BotCmd{Command: "settings", Description: "الإعدادات"},
    ).
    Register()

func (*CommandRegistry) AddPrivateMap

func (r *CommandRegistry) AddPrivateMap(cmds map[string]string) *CommandRegistry

AddPrivateMap adds commands from a map for private chats. This is convenient when commands are defined in a configuration or i18n structure.

Example:

privateCmds := map[string]string{
    "start":    "تشغيل البوت",
    "help":     "المساعدة",
    "settings": "الإعدادات",
}

NewCommandRegistry(raw, ctx).
    AddPrivateMap(privateCmds).
    Register()

func (*CommandRegistry) Clear

func (r *CommandRegistry) Clear() error

Clear removes all registered commands for both group and private chats. This is useful for resetting the bot's command menu or before registering a new set of commands.

Example:

registry := NewCommandRegistry(raw, ctx)

// Remove all existing commands
if err := registry.Clear(); err != nil {
    log.Printf("failed to clear commands: %v", err)
}

// Register new commands
registry.
    AddPrivate(BotCmd{Command: "start", Description: "Start fresh"}).
    Register()

func (*CommandRegistry) MustRegister

func (r *CommandRegistry) MustRegister()

MustRegister registers commands and panics on error. Use this when you're confident registration should never fail (e.g., during initialization with hardcoded commands).

For production code, prefer Register() and handle the error gracefully.

Example:

func main() {
    // ... setup client ...

    NewCommandRegistry(raw, ctx).
        AddGroup(
            BotCmd{Command: "help", Description: "Show help"},
        ).
        AddPrivate(
            BotCmd{Command: "start", Description: "Start the bot"},
        ).
        MustRegister() // Panics if registration fails

    client.Idle()
}

func (*CommandRegistry) Register

func (r *CommandRegistry) Register() error

Register sends all accumulated commands to Telegram. Call this after adding all commands with AddGroup/AddPrivate methods.

Register returns an error if any API call fails. On success, the commands will immediately appear in the Telegram client's command menu.

Errors can occur if:

  • The bot token is invalid
  • Network issues prevent the API call
  • Command format is invalid (e.g., uppercase letters, special characters)

Example:

err := NewCommandRegistry(raw, ctx).
    AddGroup(BotCmd{Command: "help", Description: "Show help"}).
    AddPrivate(BotCmd{Command: "start", Description: "Start the bot"}).
    Register()
if err != nil {
    log.Printf("failed to register commands: %v", err)
}

func (*CommandRegistry) WithLangCode

func (r *CommandRegistry) WithLangCode(lang string) *CommandRegistry

WithLangCode sets the language code for the commands. Use this to register different commands for different languages. An empty string (default) means the commands apply to all languages.

Common language codes: "en", "ar", "ru", "es", "de", "fa", "tr".

Example:

// Register English commands
NewCommandRegistry(raw, ctx).
    WithLangCode("en").
    AddPrivate(BotCmd{Command: "start", Description: "Start the bot"}).
    Register()

// Register Arabic commands
NewCommandRegistry(raw, ctx).
    WithLangCode("ar").
    AddPrivate(BotCmd{Command: "start", Description: "تشغيل البوت"}).
    Register()

type Context

type Context struct {
	// raw tg client which will be used make send requests.
	Raw *tg.Client
	// self user who authorized the session.
	Self *tg.User
	// Sender is a message sending helper.
	Sender *message.Sender
	// Entities consists of mapped users, chats and channels from the update.
	Entities *tg.Entities
	// TelegramClient is the high-level telegram.Client used for DC-routed operations
	// such as editing inline messages on the correct DC.
	TelegramClient *telegram.Client
	// GetDCPool returns a cached tg.Invoker for the given DC ID.
	// Pools are created once and reused for the bot's lifetime.
	GetDCPool func(ctx context.Context, dcID int) (tg.Invoker, error)
	// original context of client.
	context.Context

	DefaultParseMode string
	PeerStorage      *storage.PeerStorage
	Conv             *conv.Manager
	OnOutgoing       func(*FakeOutgoingUpdate)
	// Logger is the logger instance passed from the dispatcher.
	Logger *log.Logger
	// Translator for i18n support
	Translator interface {
		Get(userID int64, key string, args ...any) string
		GetCtx(userID int64, key string, ctx any) string
		SetLang(userID int64, lang any)
		GetLang(userID int64) any
	}
	// contains filtered or unexported fields
}

Context consists of context.Context, tg.Client, Self etc.

func NewContext

func NewContext(ctx context.Context, client *tg.Client, peerStorage *storage.PeerStorage, self *tg.User, sender *message.Sender, entities *tg.Entities, setReply bool, conv *conv.Manager, logger *log.Logger, telegramClient ...*telegram.Client) *Context

NewContext creates a new Context object with provided parameters.

func (*Context) AddChatMembers

func (ctx *Context) AddChatMembers(chatID int64, userIDs []int64, forwardLimit int) (bool, error)

AddChatMembers adds multiple users to a chat.

func (*Context) AddStickerToSet

func (ctx *Context) AddStickerToSet(req *tg.StickersAddStickerToSetRequest) (*tg.MessagesStickerSet, error)

func (*Context) AnswerCallback

func (ctx *Context) AnswerCallback(request *tg.MessagesSetBotCallbackAnswerRequest) (bool, error)

AnswerCallback invokes method messages.setBotCallbackAnswer#d58f130a returning error if any. Set the callback answer to a user button press

func (*Context) ArchiveChats

func (ctx *Context) ArchiveChats(chatIDs []int64) (bool, error)

ArchiveChats moves chats to the archive folder (folder ID 1).

func (*Context) BanChatMember

func (ctx *Context) BanChatMember(chatID, userID int64, untilDate int) (tg.UpdatesClass, error)

BanChatMember bans a user from a chat until a specified date.

func (*Context) BuyResaleStarGift

func (ctx *Context) BuyResaleStarGift(slug string, toID any) (tg.PaymentsPaymentResultClass, error)

BuyResaleStarGift purchases a resale star gift by slug for a recipient. toID can be tg.InputPeerClass, int64 (userID), or string (username).

func (*Context) CreateChannel

func (ctx *Context) CreateChannel(title, about string, broadcast bool) (*tg.Channel, error)

CreateChannel creates a new channel (supergroup or broadcast).

func (*Context) CreateChat

func (ctx *Context) CreateChat(title string, userIDs []int64) (*tg.Chat, error)

CreateChat creates a new group chat.

func (*Context) CreateStickerSet

func (ctx *Context) CreateStickerSet(req *tg.StickersCreateStickerSetRequest) (*tg.MessagesStickerSet, error)

func (*Context) DeleteMessages

func (ctx *Context) DeleteMessages(chatID int64, messageIDs []int) error

DeleteMessages deletes messages in a chat.

func (*Context) DeleteStickerSet

func (ctx *Context) DeleteStickerSet(shortName string) error

func (*Context) DemoteChatMember

func (ctx *Context) DemoteChatMember(chatID, userID int64, opts *EditAdminOpts) (bool, error)

DemoteChatMember demotes an admin to regular member in a chat.

func (*Context) Disable2FA

func (ctx *Context) Disable2FA(currentPassword string) error

Disable2FA removes the 2FA cloud password from the account.

See https://core.telegram.org/api/srp for reference.

func (*Context) DownloadMedia

func (ctx *Context) DownloadMedia(media tg.MessageMediaClass, downloadOutput DownloadOutputClass, opts *DownloadMediaOpts) (tg.StorageFileTypeClass, error)

DownloadMedia downloads media from a message.

func (*Context) EditCaption

func (ctx *Context) EditCaption(chatID int64, messageID int, caption string, entities []tg.MessageEntityClass) (*types.Message, error)

EditCaption edits the caption of a media message.

Parameters:

  • chatID: The chat ID containing the message
  • messageID: The ID of the message to edit
  • caption: The new caption text
  • entities: Optional formatting entities for the caption

Returns the edited Message or an error.

func (*Context) EditMessage

func (ctx *Context) EditMessage(chatID int64, request *tg.MessagesEditMessageRequest, businessConnectionID ...string) (*types.Message, error)

EditMessage edits a previously sent message.

Use this method to edit message text, media, caption, entities, or reply markup. Not all message types can be edited - see Telegram's API documentation for details.

Parameters:

  • chatID: The chat ID containing the message
  • request: Telegram's MessagesEditMessageRequest with edits to apply

Returns the edited Message or an error.

func (*Context) EditReplyMarkup

func (ctx *Context) EditReplyMarkup(chatID int64, messageID int, markup tg.ReplyMarkupClass) (*types.Message, error)

EditReplyMarkup edits only the reply markup (inline keyboard) of a message.

Parameters:

  • chatID: The chat ID containing the message
  • messageID: The ID of the message to edit
  • markup: The new reply markup (inline keyboard or force reply)

Returns the edited Message or an error.

func (*Context) Enable2FA

func (ctx *Context) Enable2FA(newPassword string, opts *functions.PasswordOpts) error

Enable2FA enables Two-Factor Authentication by setting a new cloud password.

See https://core.telegram.org/api/srp#setting-a-new-2fa-password for reference.

func (*Context) ExportInvoice

func (ctx *Context) ExportInvoice(inputMedia tg.InputMediaClass) (*tg.PaymentsExportedInvoice, error)

ExportInvoice exports an invoice for payment providers.

func (*Context) ExportSessionString

func (ctx *Context) ExportSessionString() (string, error)

ExportSessionString exports the current session as a string.

func (*Context) ForwardMessage deprecated

func (ctx *Context) ForwardMessage(fromChatID, toChatID int64, request *tg.MessagesForwardMessagesRequest) (tg.UpdatesClass, error)

ForwardMessage forwards messages from one chat to another.

Deprecated: use ForwardMessages instead.

func (*Context) ForwardMessages

func (ctx *Context) ForwardMessages(fromChatID, toChatID int64, request *tg.MessagesForwardMessagesRequest) (tg.UpdatesClass, error)

ForwardMessages forwards messages from one chat to another.

func (*Context) GetActiveSessions

func (ctx *Context) GetActiveSessions() ([]tg.Authorization, error)

GetActiveSessions returns all active authorized sessions for the current account.

See https://core.telegram.org/method/account.getAuthorizations for reference.

func (*Context) GetChat

func (ctx *Context) GetChat(chatID int64) (tg.ChatClass, error)

GetChat returns tg.ChatClass of the provided chat id.

func (ctx *Context) GetChatInviteLink(chatID int64, req ...*tg.MessagesExportChatInviteRequest) (tg.ExportedChatInviteClass, error)

GetChatInviteLink generates an invite link for a chat.

func (*Context) GetChatMember

func (ctx *Context) GetChatMember(chatID, userID int64) (*types.Participant, error)

GetChatMember fetches information about a chat member.

func (*Context) GetChatMembers

func (ctx *Context) GetChatMembers(chatID int64, opts ...*functions.GetChatMembersOpts) ([]*types.Participant, error)

func (*Context) GetFullChat

func (ctx *Context) GetFullChat(chatID int64) (tg.ChatFullClass, error)

GetFullChat returns full chat details for the provided chat ID.

func (*Context) GetFullUser

func (ctx *Context) GetFullUser(userID int64) (*tg.UserFull, error)

GetFullUser returns full user profile for the provided user ID.

func (*Context) GetInlineBotResults

func (ctx *Context) GetInlineBotResults(chatID int64, botUsername string, request *tg.MessagesGetInlineBotResultsRequest) (*tg.MessagesBotResults, error)

GetInlineBotResults fetches inline results from a bot.

Parameters:

  • chatID: The chat ID where the query originates
  • botUsername: The username of the bot to query (with or without @ prefix)
  • request: The request containing query parameters

Returns the bot results or an error.

func (*Context) GetMessages

func (ctx *Context) GetMessages(chatID int64, messageIDs []tg.InputMessageClass) ([]tg.MessageClass, error)

GetMessages fetches messages from a chat by their IDs.

func (*Context) GetPeerStories

func (ctx *Context) GetPeerStories(chatID int64) (*tg.StoriesPeerStories, error)

GetPeerStories fetches all active stories for a given peer by chat ID.

This resolves the peer from storage and calls the stories.getPeerStories method.

Example:

peerStories, err := ctx.GetPeerStories(chatID)
if err != nil {
    log.Fatal(err)
}
for _, story := range peerStories.Stories.Stories {
    log.Printf("Story: %v", story)
}

Parameters:

  • chatID: The chat/user ID whose stories to fetch

Returns StoriesPeerStories containing the stories, or an error.

func (*Context) GetPeerStoriesByInputPeer

func (ctx *Context) GetPeerStoriesByInputPeer(peer tg.InputPeerClass) (*tg.StoriesPeerStories, error)

GetPeerStoriesByInputPeer fetches all active stories for a pre-resolved input peer.

Use this when you already have a resolved InputPeerClass (e.g. from ResolveUsername).

Example:

resolved, err := ctx.ResolveUsername("username")
if err != nil {
    log.Fatal(err)
}
peerStories, err := ctx.GetPeerStoriesByInputPeer(resolved.GetInputPeer())
if err != nil {
    log.Fatal(err)
}

Parameters:

  • peer: The resolved input peer

Returns StoriesPeerStories containing the stories, or an error.

func (*Context) GetResaleStarGifts

func (ctx *Context) GetResaleStarGifts(req *tg.PaymentsGetResaleStarGiftsRequest) (*tg.PaymentsResaleStarGifts, error)

GetResaleStarGifts retrieves the list of resale star gifts.

func (*Context) GetStarGifts

func (ctx *Context) GetStarGifts(hash int) (tg.PaymentsStarGiftsClass, error)

GetStarGifts retrieves the list of available star gifts.

func (*Context) GetStickerSet

func (ctx *Context) GetStickerSet(input tg.InputStickerSetClass) (*tg.MessagesStickerSet, error)

func (*Context) GetStickerSetByShortName

func (ctx *Context) GetStickerSetByShortName(shortName string) (*tg.MessagesStickerSet, error)

func (*Context) GetStoriesByID

func (ctx *Context) GetStoriesByID(chatID int64, ids []int) (*tg.StoriesStories, error)

GetStoriesByID fetches specific stories by their IDs from a given peer.

Example:

stories, err := ctx.GetStoriesByID(chatID, []int{1, 2, 3})
if err != nil {
    log.Fatal(err)
}
for _, story := range stories.Stories {
    log.Printf("Story: %v", story)
}

Parameters:

  • chatID: The chat/user ID whose stories to fetch
  • ids: The story IDs to fetch

Returns StoriesStories containing the requested stories, or an error.

func (*Context) GetStoriesByIDWithInputPeer

func (ctx *Context) GetStoriesByIDWithInputPeer(peer tg.InputPeerClass, ids []int) (*tg.StoriesStories, error)

GetStoriesByIDWithInputPeer fetches specific stories by their IDs using a pre-resolved input peer.

Use this when you already have a resolved InputPeerClass (e.g. from ResolveUsername).

Example:

resolved, err := ctx.ResolveUsername("username")
if err != nil {
    log.Fatal(err)
}
stories, err := ctx.GetStoriesByIDWithInputPeer(resolved.GetInputPeer(), []int{42})
if err != nil {
    log.Fatal(err)
}

Parameters:

  • peer: The resolved input peer
  • ids: The story IDs to fetch

Returns StoriesStories containing the requested stories, or an error.

func (*Context) GetUser

func (ctx *Context) GetUser(userID int64) (*tg.User, error)

GetUser returns basic user information for the provided user ID.

func (*Context) GetUserProfilePhotos

func (ctx *Context) GetUserProfilePhotos(userID int64, opts *tg.PhotosGetUserPhotosRequest) ([]tg.PhotoClass, error)

GetUserProfilePhotos retrieves profile photos for a user.

func (*Context) IsBot

func (ctx *Context) IsBot() bool

IsBot returns true if the current session belongs to a bot account.

func (*Context) Leave

func (ctx *Context) Leave(chatID int64) (tg.UpdatesClass, error)

Leave leaves the current user from a channel or chat.

func (*Context) PinMessage

func (ctx *Context) PinMessage(chatID int64, messageID int) (tg.UpdatesClass, error)

PinMessage pins a message in a chat.

func (*Context) PromoteChatMember

func (ctx *Context) PromoteChatMember(chatID, userID int64, opts *EditAdminOpts) (bool, error)

PromoteChatMember promotes a user to admin in a chat.

func (*Context) RegisterBotCommands

func (ctx *Context) RegisterBotCommands() *CommandRegistry

RegisterBotCommands creates a new CommandRegistry from the Context. This is a convenience method to register bot commands directly from handlers.

The Context provides both the raw tg.Client and the context.Context needed for the registry, so you don't need to pass them separately.

Example:

func startCmd(u *adapter.Update) error {
    // Register commands from within a handler
    err := u.Ctx.RegisterBotCommands().
        AddPrivate(
            adapter.BotCmd{Command: "start", Description: "Start the bot"},
            adapter.BotCmd{Command: "help", Description: "Show help"},
        ).
        AddGroup(
            adapter.BotCmd{Command: "play", Description: "Start a game"},
        ).
        Register()
    if err != nil {
        u.Log.Error("failed to register commands", "error", err)
    }
    return u.Reply("Commands registered!")
}

func (*Context) RemoveStickerFromSet

func (ctx *Context) RemoveStickerFromSet(doc *tg.Document) (*tg.MessagesStickerSet, error)

func (*Context) ResolveInputPeerByID

func (ctx *Context) ResolveInputPeerByID(id int64) (tg.InputPeerClass, error)

ResolveInputPeerByID resolves a peer ID to an InputPeer.

func (*Context) ResolvePeerByID

func (ctx *Context) ResolvePeerByID(id int64) *storage.Peer

ResolvePeerByID resolves a peer ID to a storage.Peer with metadata.

func (*Context) ResolveUsername

func (ctx *Context) ResolveUsername(username string) (types.EffectiveChat, error)

ResolveUsername resolves a @username to get peer information.

func (*Context) RevokeAllOtherSessions

func (ctx *Context) RevokeAllOtherSessions() error

RevokeAllOtherSessions terminates all other active sessions except the current one.

See https://core.telegram.org/method/auth.resetAuthorizations for reference.

func (*Context) RevokeSession

func (ctx *Context) RevokeSession(hash int64) error

RevokeSession terminates an active authorized session by its hash.

See https://core.telegram.org/method/account.resetAuthorization for reference.

func (*Context) SendInlineBotResult

func (ctx *Context) SendInlineBotResult(chatID int64, request *tg.MessagesSendInlineBotResultRequest) (tg.UpdatesClass, error)

SendInlineBotResult sends an inline bot result to a chat. Used to send a result obtained from GetInlineBotResults.

Parameters:

  • chatID: The chat ID to send the result to
  • request: The send request containing the result to send

Returns updates confirming the action or an error.

func (*Context) SendMedia

func (ctx *Context) SendMedia(chatID int64, request *tg.MessagesSendMediaRequest, businessConnectionID ...string) (*types.Message, error)

SendMedia sends media (photo, video, document, etc.) to a chat.

Use this method to send any type of media including photos, videos, documents, audio files, and other media types supported by Telegram.

Parameters:

  • chatID: The chat ID to send the media to
  • request: Telegram's MessagesSendMediaRequest containing media and metadata

Returns the sent Message or an error.

func (*Context) SendMessage

func (ctx *Context) SendMessage(chatID int64, request *tg.MessagesSendMessageRequest, businessConnectionID ...string) (*types.Message, error)

SendMessage sends a text message to a chat.

This is the primary method for sending messages. It supports text messages, formatting entities, inline keyboards, and more through the request parameter.

Parameters:

  • chatID: The chat ID to send the message to
  • request: Telegram's MessagesSendMessageRequest containing message content

Returns the sent Message or an error.

func (*Context) SendMultiMedia

func (ctx *Context) SendMultiMedia(chatID int64, request *tg.MessagesSendMultiMediaRequest, businessConnectionID ...string) (*types.Message, error)

SendMultiMedia sends multiple media items as an album or grouped media.

Use this method to send 2-10 media items as an album. Media items will be grouped together in the chat and displayed as a swipeable album.

Parameters:

  • chatID: The chat ID to send the album to
  • request: Telegram's MessagesSendMultiMediaRequest containing media items

Returns the sent Message album or an error.

func (*Context) SendReaction

func (ctx *Context) SendReaction(chatID int64, request *tg.MessagesSendReactionRequest) (*types.Message, error)

SendReaction sends or removes emoji reactions to a message.

Reactions allow users to quickly respond to messages with emoji. Set reaction to an empty slice to remove all reactions.

Parameters:

  • chatID: The chat ID containing the message
  • request: Telegram's MessagesSendReactionRequest containing reactions

Returns the Message with updated reactions or an error.

func (*Context) SetBotCommands

func (ctx *Context) SetBotCommands(group, private []BotCmd) error

SetBotCommands is a convenience method to quickly set bot commands. Use this for simple cases where you just want to register commands without chaining multiple builder methods.

For more control, use RegisterBotCommands() instead.

Example:

err := ctx.SetBotCommands(
    []adapter.BotCmd{
        {Command: "play", Description: "Start a game"},
    },
    []adapter.BotCmd{
        {Command: "start", Description: "Start the bot"},
    },
)

func (*Context) SetInlineBotResult

func (ctx *Context) SetInlineBotResult(request *tg.MessagesSetInlineBotResultsRequest) (bool, error)

SetInlineBotResult answers an inline query with results. For bots only. This is the method to respond to inline queries.

Parameters:

  • request: The inline bot results request containing query ID and results

Returns true if successful, or an error.

Example:

results := &tg.MessagesSetInlineBotResultsRequest{
    QueryID: queryID,
    Results: []tg.InputBotInlineResultClass{...},
}
success, err := ctx.SetInlineBotResult(results)

func (*Context) SetPreCheckoutResults

func (ctx *Context) SetPreCheckoutResults(success bool, queryID int64, err string) (bool, error)

SetPreCheckoutResults responds to a pre-checkout query.

func (*Context) TransferStarGift

func (ctx *Context) TransferStarGift(chatID int64, starGift tg.InputSavedStarGiftClass) (tg.UpdatesClass, error)

TransferStarGift transfers a star gift to a chat.

func (*Context) UnPinAllMessages

func (ctx *Context) UnPinAllMessages(chatID int64) error

UnPinAllMessages unpins all messages in a chat.

func (*Context) UnPinMessage

func (ctx *Context) UnPinMessage(chatID int64, messageID int) error

UnPinMessage unpins a specific message in a chat.

func (*Context) UnarchiveChats

func (ctx *Context) UnarchiveChats(chatIDs []int64) (bool, error)

UnarchiveChats moves chats out of the archive folder (folder ID 0).

func (*Context) UnbanChatMember

func (ctx *Context) UnbanChatMember(chatID, userID int64) (bool, error)

UnbanChatMember unbans a previously banned user from a channel.

func (*Context) Update2FA

func (ctx *Context) Update2FA(currentPassword, newPassword string, opts *functions.PasswordOpts) error

Update2FA changes an existing 2FA cloud password to a new one.

See https://core.telegram.org/api/srp#setting-a-new-2fa-password for reference.

type ConvOpts

type ConvOpts struct {
	// Reply indicates whether to reply to the user's message. When true,
	// the sent message will reply to the original triggering message.
	Reply bool
	// ReplyMarkup provides inline or reply keyboard markup for the message.
	// This enables interactive buttons and custom keyboards.
	ReplyMarkup tg.ReplyMarkupClass
	// ParseMode specifies the text formatting (e.g., "html", "markdown").
	// Controls how the message text should be parsed and formatted.
	ParseMode string
	// Media attaches a media file (photo, video, document, etc.) to the message.
	// When set, the message becomes a media message rather than text-only.
	Media tg.InputMediaClass
	// Caption is the text caption for media messages. Ignored when Media is nil.
	Caption string
	// Timeout sets the duration before the conversation state automatically expires.
	// A zero value means no timeout (state persists until manually cleared).
	Timeout time.Duration
	// Filter specifies which incoming updates should be accepted during the conversation.
	// Only updates matching the filter will be processed and returned to the handler.
	Filter conv.Filter
}

ConvOpts defines optional configuration parameters for starting a conversation. It provides control over message formatting, reply behavior, media attachment, and conversation timeout settings.

type DownloadMediaOpts

type DownloadMediaOpts struct {
	Threads  int
	Verify   *bool
	PartSize int
}

DownloadMediaOpts contains optional parameters for Context.DownloadMedia.

type DownloadOutputClass

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

DownloadOutputClass is an interface for media download destinations.

type DownloadOutputParallel

type DownloadOutputParallel struct {
	io.WriterAt
}

DownloadOutputParallel downloads media using parallel chunk downloads.

type DownloadOutputPath

type DownloadOutputPath string

DownloadOutputPath downloads media to a file path.

type DownloadOutputStream

type DownloadOutputStream struct {
	io.Writer
}

DownloadOutputStream downloads media to any io.Writer.

type EditAdminOpts

type EditAdminOpts struct {
	AdminRights tg.ChatAdminRights
	AdminTitle  string
}

EditAdminOpts contains options for editing admin rights.

type EditMediaOpts

type EditMediaOpts struct {
	NoWebpage            bool
	InvertMedia          bool
	Peer                 tg.InputPeerClass
	ID                   int
	Message              string
	Media                tg.InputMediaClass
	ReplyMarkup          tg.ReplyMarkupClass
	Entities             []tg.MessageEntityClass
	ScheduleDate         int
	ScheduleRepeatPeriod int
	QuickReplyShortcutID int
	Caption              string
	ParseMode            string
	BusinessConnectionID string
}

EditMediaOpts contains optional parameters for editing media messages. Clones all fields from tg.MessagesEditMessageRequest.

type EditOpts

type EditOpts struct {
	NoWebpage            bool
	InvertMedia          bool
	Peer                 tg.InputPeerClass
	ID                   int
	Message              string
	Media                tg.InputMediaClass
	ReplyMarkup          tg.ReplyMarkupClass
	Entities             []tg.MessageEntityClass
	ScheduleDate         int
	ScheduleRepeatPeriod int
	QuickReplyShortcutID int
	ParseMode            string
	BusinessConnectionID string
}

EditOpts contains optional parameters for editing messages. Clones all fields from tg.MessagesEditMessageRequest.

type FakeOutgoingUpdate

type FakeOutgoingUpdate struct {
	Action    string
	Status    string
	Message   *types.Message
	MessageID int
	ChatID    int64
	Peer      tg.InputPeerClass
	Error     error
}

FakeOutgoingUpdate is a synthetic update emitted when the client sends, edits, or deletes a message. Raw MTProto does not push outgoing message updates; this struct fills that gap.

type FormatHelper

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

FormatHelper provides text formatting convenience methods. Use Update.Format() to get a formatter instance.

func (*FormatHelper) Blockquote

func (f *FormatHelper) Blockquote(text string) string

Blockquote wraps text with blockquote formatting markers.

func (*FormatHelper) Bold

func (f *FormatHelper) Bold(text string) string

Bold wraps text with bold formatting markers.

func (*FormatHelper) Code

func (f *FormatHelper) Code(text string) string

Code wraps text with code formatting markers.

func (*FormatHelper) CustomEmoji

func (f *FormatHelper) CustomEmoji(emoji string, emojiID int64) string

CustomEmoji creates a custom emoji link.

func (*FormatHelper) ExpandableBlockquote

func (f *FormatHelper) ExpandableBlockquote(text string) string

ExpandableBlockquote wraps text with expandable blockquote formatting markers.

func (*FormatHelper) Italic

func (f *FormatHelper) Italic(text string) string

Italic wraps text with italic formatting markers.

func (f *FormatHelper) Link(text, url string) string

Link creates a hyperlink with the specified URL.

func (*FormatHelper) Mention

func (f *FormatHelper) Mention(displayName string, userID int64) string

Mention creates a mention link for a Telegram user.

func (*FormatHelper) Pre

func (f *FormatHelper) Pre(text string) string

Pre wraps text with pre-formatted code block markers.

func (*FormatHelper) PreWithLanguage

func (f *FormatHelper) PreWithLanguage(text, language string) string

PreWithLanguage wraps text with pre-formatted code block markers with syntax highlighting.

func (*FormatHelper) Spoiler

func (f *FormatHelper) Spoiler(text string) string

Spoiler wraps text with spoiler formatting markers.

func (*FormatHelper) Strikethrough

func (f *FormatHelper) Strikethrough(text string) string

Strikethrough wraps text with strikethrough formatting markers.

func (*FormatHelper) Underline

func (f *FormatHelper) Underline(text string) string

Underline wraps text with underline formatting markers.

type GetChatMembersOpts

type GetChatMembersOpts = functions.GetChatMembersOpts

type SendMediaOpts

type SendMediaOpts struct {
	Peer                   tg.InputPeerClass
	ReplyTo                tg.InputReplyToClass
	Media                  tg.InputMediaClass
	RandomID               int64
	ScheduleDate           int
	SendAs                 tg.InputPeerClass
	QuickReplyShortcut     tg.InputQuickReplyShortcutClass
	Effect                 int64
	AllowPaidFloodskip     bool
	Silent                 bool
	Background             bool
	ClearDraft             bool
	Noforwards             bool
	UpdateStickersetsOrder bool
	InvertMedia            bool
	AllowPaidStars         int64
	SuggestedPost          tg.SuggestedPost
	Message                string
	Entities               []tg.MessageEntityClass
	ReplyMarkup            tg.ReplyMarkupClass
	Caption                string
	ParseMode              string
	WithoutReply           bool
	ReplyMessageID         int
	BusinessConnectionID   string
}

SendMediaOpts contains optional parameters for sending media. Clones all fields from tg.MessagesSendMediaRequest.

type SendOpts

type SendOpts struct {
	NoWebpage              bool
	Silent                 bool
	Background             bool
	ClearDraft             bool
	Noforwards             bool
	UpdateStickersetsOrder bool
	InvertMedia            bool
	AllowPaidFloodskip     bool
	Peer                   tg.InputPeerClass
	ReplyTo                tg.InputReplyToClass
	Message                string
	RandomID               int64
	ReplyMarkup            tg.ReplyMarkupClass
	Entities               []tg.MessageEntityClass
	ScheduleDate           int
	ScheduleRepeatPeriod   int
	SendAs                 tg.InputPeerClass
	QuickReplyShortcut     tg.InputQuickReplyShortcutClass
	Effect                 int64
	AllowPaidStars         int64
	SuggestedPost          tg.SuggestedPost
	ParseMode              string
	WithoutReply           bool
	ReplyMessageID         int
	BusinessConnectionID   string
}

SendOpts contains optional parameters for sending messages. Embeds tg.MessagesSendMessageRequest for direct access to all Telegram API fields.

type Translator

type Translator interface {
	Get(userID int64, key string, args ...any) string
	GetCtx(userID int64, key string, ctx *i18n.Args) string
	SetLang(userID int64, lang any)
	GetLang(userID int64) any
}

type Update

type Update struct {
	// EffectiveMessage is the tg.Message of current update.
	EffectiveMessage *types.Message
	// CallbackQuery is the tg.UpdateBotCallbackQuery of current update.
	CallbackQuery *tg.UpdateBotCallbackQuery
	// InlineCallbackQuery is the tg.UpdateInlineBotCallbackQuery of current update (for inline message buttons).
	InlineCallbackQuery *tg.UpdateInlineBotCallbackQuery
	// InlineQuery is the wrapped inline query of current update.
	InlineQuery *types.InlineQuery
	// ChatJoinRequest is the tg.UpdatePendingJoinRequests of current update.
	ChatJoinRequest *tg.UpdatePendingJoinRequests
	// ChatParticipant is the tg.UpdateChatParticipant of current update.
	ChatParticipant *tg.UpdateChatParticipant
	// ChannelParticipant is the tg.UpdateChannelParticipant of current update.
	ChannelParticipant *tg.UpdateChannelParticipant
	// ChosenInlineResult is the wrapped chosen inline result of current update.
	ChosenInlineResult *types.ChosenInlineResult
	// DeletedMessages is the tg.UpdateDeleteMessages of current update.
	DeletedMessages *tg.UpdateDeleteMessages
	// DeletedChannelMessages is the tg.UpdateDeleteChannelMessages of current update.
	DeletedChannelMessages *tg.UpdateDeleteChannelMessages
	// MessageReaction is the tg.UpdateBotMessageReaction of current update.
	MessageReaction *tg.UpdateBotMessageReaction
	// ChatBoost is the tg.UpdateBotChatBoost of current update.
	ChatBoost *tg.UpdateBotChatBoost
	// BusinessConnection is the tg.UpdateBotBusinessConnect of current update.
	BusinessConnection *tg.UpdateBotBusinessConnect
	// BusinessMessage is the tg.UpdateBotNewBusinessMessage of current update.
	BusinessMessage *tg.UpdateBotNewBusinessMessage
	// BusinessEditedMessage is the tg.UpdateBotEditBusinessMessage of current update.
	BusinessEditedMessage *tg.UpdateBotEditBusinessMessage
	// BusinessDeletedMessages is the tg.UpdateBotDeleteBusinessMessage of current update.
	BusinessDeletedMessages *tg.UpdateBotDeleteBusinessMessage
	// BusinessCallbackQuery is the tg.UpdateBusinessBotCallbackQuery of current update.
	BusinessCallbackQuery *tg.UpdateBusinessBotCallbackQuery
	// EffectiveOutgoing contains metadata for synthetic outgoing updates (send/edit/delete).
	EffectiveOutgoing *FakeOutgoingUpdate
	// Log is the logger for this update. Use u.Log.Info("msg", "key", val) etc.
	Log *log.Logger
	// UpdateClass is the current update in raw form.
	UpdateClass tg.UpdateClass
	// Entities of an update, i.e. mapped users, chats and channels.
	Entities *tg.Entities

	// Sender is a message sending helper.
	Self *tg.User
	// Context of the current update.
	Ctx *Context
	// IsEdited indicates the effective message was an edit, not a new message.
	IsEdited bool
	// contains filtered or unexported fields
}

Update contains all data related to an update.

func GetNewUpdate

func GetNewUpdate(ctx *Context, update tg.UpdateClass) *Update

GetNewUpdate creates a new Update with provided parameters.

func (*Update) Answer

func (u *Update) Answer(text string, opts ...*CallbackOptions) (bool, error)

Answer answers the callback query (works for both regular and inline message callbacks). text: The notification text (use empty string for silent). opts: Optional *CallbackOptions for alert, cacheTime, url.

Example:

u.Answer("Done!", nil)
u.Answer("Error!", &CallbackOptions{Alert: true})

func (*Update) AnswerInlineQuery

func (u *Update) AnswerInlineQuery(results []tg.InputBotInlineResultClass, opts *types.AnswerOpts) (bool, error)

AnswerInlineQuery answers the inline query with results. results: The slice of inline results to show. opts: Optional *types.AnswerOpts for cacheTime, isPersonal, nextOffset, etc.

Example:

results := []tg.InputBotInlineResultClass{...}
u.AnswerInlineQuery(results, nil)
u.AnswerInlineQuery(results, &types.AnswerOpts{CacheTime: 60, IsPersonal: true})

func (*Update) AnswerInlineQueryWithGallery

func (u *Update) AnswerInlineQueryWithGallery(results []tg.InputBotInlineResultClass, opts *types.AnswerOpts) (bool, error)

AnswerInlineQueryWithGallery answers the inline query with results in gallery format. Use this for photo/video results that should display as a grid.

func (*Update) Args

func (u *Update) Args() []string

Args parses and returns the arguments from the update. For messages, splits the message text by whitespace. For callback queries, splits the callback data by whitespace. For inline queries, splits the query text by whitespace. Returns an empty slice if no applicable content exists.

func (*Update) CancelConv

func (u *Update) CancelConv() (bool, bool, error)

CancelConv is an alias for EndConv that provides more semantic clarity when a conversation is being cancelled rather than naturally ended. Both methods behave identically.

func (*Update) ChannelID

func (u *Update) ChannelID() int64

ChannelID returns the channel ID for this update. For messages and callback queries, extracts from the peer ID. Returns 0 if no channel can be determined.

func (*Update) ChatID

func (u *Update) ChatID() int64

ChatID returns the chat ID for this update. For messages and callback queries, extracts from the peer ID. Returns 0 if no chat can be determined.

func (*Update) ChatType

func (u *Update) ChatType() string

ChatType returns the type of chat for this update. Returns "private" for users, "group" for chats, "channel" for channels, or an empty string if the chat type cannot be determined.

func (*Update) ConnectionID

func (u *Update) ConnectionID() string

ConnectionID returns the business connection ID for this update. Returns empty string if the update is not business-related.

func (*Update) Data

func (u *Update) Data() string

Data returns the callback data as a string for callback queries. Works for both regular callback queries and inline message callback queries. Returns an empty string if the update is not a callback query or data is nil.

Example:

data := u.Data()
if data != "" {
    fmt.Printf("Callback data: %s\n", data)
}

func (*Update) Delete

func (u *Update) Delete() error

Delete deletes the effective message for this update. Returns an error if the deletion fails.

func (*Update) Dump

func (u *Update) Dump(val any, key ...string) string

Dump returns pretty-printed JSON of any value with optional key prefix.

func (*Update) DumpValue

func (u *Update) DumpValue() any

DumpValue returns the raw UpdateClass for JSON serialization.

func (*Update) Edit

func (u *Update) Edit(text any, opts ...*EditOpts) (*types.Message, error)

Edit edits the current update's message text. Text can be a string or any type that can be formatted with %v. Uses the client's default parse mode from ClientOpts.ParseMode. For callback queries, edits the message that triggered the callback.

func (*Update) EditCaption

func (u *Update) EditCaption(text any, opts ...*EditOpts) (*types.Message, error)

EditCaption edits the caption of the current update's media message. Text can be a string or any type that can be formatted with %v. Uses the client's default parse mode from ClientOpts.ParseMode.

func (*Update) EditInlineCaption

func (u *Update) EditInlineCaption(caption any, opts ...*EditOpts) error

EditInlineCaption edits an inline message's caption. Works for inline callback queries and chosen inline results.

func (*Update) EditInlineMedia

func (u *Update) EditInlineMedia(media tg.InputMediaClass, opts ...*EditMediaOpts) error

EditInlineMedia edits the media of an inline message. Works for inline callback queries and chosen inline results.

func (*Update) EditInlineReplyMarkup

func (u *Update) EditInlineReplyMarkup(markup tg.ReplyMarkupClass) error

EditInlineReplyMarkup edits only the reply markup of an inline message. Works for inline callback queries and chosen inline results.

func (*Update) EditInlineText

func (u *Update) EditInlineText(text any, opts ...*EditOpts) error

EditInlineText edits an inline message's text. Works for inline callback queries and chosen inline results.

func (*Update) EditMedia

func (u *Update) EditMedia(media tg.InputMediaClass, opts ...*EditMediaOpts) (*types.Message, error)

EditMedia edits the media of the current update's message. Accepts tg.InputMediaClass (e.g., InputMediaPhoto, InputMediaDocument).

Example using InputMedia:

editedMsg, err := u.EditMedia(&tg.InputMediaPhoto{
    ID: &tg.InputPhoto{ID: photoID, AccessHash: accessHash},
}, &adapter.EditMediaOpts{
    Caption: "New photo",
})

For using fileID strings, see EditMediaWithFileID.

func (*Update) EditMediaWithFileID

func (u *Update) EditMediaWithFileID(fileID string, opts ...*EditMediaOpts) (*types.Message, error)

EditMediaWithFileID edits the media of the current update's message using a fileID string. The fileID should be obtained from a previous Message's FileID(), Document().FileID(), or Photo().FileID() method.

Example:

fileID := newMsg.FileID()
editedMsg, err := u.EditMediaWithFileID(fileID, &adapter.EditMediaOpts{
    Caption: "Updated media!",
})

func (*Update) EditMessage

func (u *Update) EditMessage(chatID int64, messageID int, text string, opts ...*EditOpts) (*types.Message, error)

EditMessage edits a message in the specified chat. Text can be a string or any type that can be formatted with %v. Uses the client's default parse mode from ClientOpts.ParseMode.

Parameters:

  • chatID: The target chat ID (use 0 to use the current update's chat)
  • messageID: The ID of the message to edit
  • text: New message text
  • opts: Optional EditOpts for entities, reply markup, etc.

Returns the edited Message or an error.

Example:

msg, err := u.EditMessage(0, 123, "Updated text")  // Edit in current chat
msg, err := u.EditMessage(chatID, 123, "<b>Updated</b>", &EditOpts{
    ParseMode: "HTML",
})

func (*Update) EditMessageMedia

func (u *Update) EditMessageMedia(chatID int64, messageID int, media tg.InputMediaClass, caption string, opts ...*EditMediaOpts) (*types.Message, error)

EditMessageMedia edits the media of a specific message in the specified chat. Accepts tg.InputMediaClass (e.g., InputMediaPhoto, InputMediaDocument). This differs from EditMedia() which edits the current update's effective message.

Parameters:

  • chatID: The target chat ID (use 0 to use the current update's chat)
  • messageID: The ID of the message to edit
  • media: The new media (tg.InputMediaClass)
  • caption: New caption text
  • opts: Optional EditMediaOpts

Returns the edited Message or an error.

Example using InputMedia:

msg, err := u.EditMessageMedia(0, 123, &tg.InputMediaPhoto{
    ID: &tg.InputPhoto{ID: photoID, AccessHash: accessHash},
}, "New caption")  // Edit in current chat

Example using fileID (convert with types.InputMediaFromFileID):

media, _ := types.InputMediaFromFileID(fileID, "caption")
msg, err := u.EditMessageMedia(chatID, 123, media, "caption")

func (*Update) EditReplyMarkup

func (u *Update) EditReplyMarkup(markup tg.ReplyMarkupClass) (*types.Message, error)

EditReplyMarkup edits only the reply markup of the current update's message. For callback queries, edits the message that triggered the callback.

func (*Update) EffectiveChat

func (u *Update) EffectiveChat() types.EffectiveChat

EffectiveChat returns the responsible EffectiveChat for the current update.

func (*Update) EffectiveChosenInlineResult

func (u *Update) EffectiveChosenInlineResult() *types.ChosenInlineResult

EffectiveChosenInlineResult returns the wrapped ChosenInlineResult for the current update. Returns nil if the update is not a chosen inline result.

func (*Update) EffectiveInlineQuery

func (u *Update) EffectiveInlineQuery() *types.InlineQuery

EffectiveInlineQuery returns the wrapped InlineQuery for the current update. Returns nil if the update is not an inline query.

func (*Update) EffectiveReply

func (u *Update) EffectiveReply() *types.Message

EffectiveReply returns the message that this message is replying to. It lazily fetches the reply message if not already populated.

func (*Update) EffectiveUser

func (u *Update) EffectiveUser() *types.User

EffectiveUser returns the types.User who is responsible for the update.

func (*Update) EndConv

func (u *Update) EndConv() (bool, bool, error)

EndConv terminates the active conversation for the current chat and user. It clears both the conversation state and any associated filter.

Returns:

  • cleared: True if the conversation state was successfully cleared
  • existed: True if a conversation was active (false if none existed)
  • err: Any error encountered during the operation

func (*Update) FirstName

func (u *Update) FirstName() string

FirstName returns the first name of the effective user. Returns an empty string if no user exists.

func (*Update) Format

func (u *Update) Format(mode string) *FormatHelper

Format returns a new FormatHelper for formatting text. The mode determines the formatting style: "HTML", "Markdown", "MarkdownV2", or "" (none).

func (*Update) FullName

func (u *Update) FullName() string

FullName returns the full name (first name + last name) of the effective user. Returns an empty string if no user exists.

func (*Update) GetChannel

func (u *Update) GetChannel() *types.Channel

GetChannel returns the responsible types.Channel for the current update.

func (*Update) GetChat

func (u *Update) GetChat() *types.Chat

GetChat returns the responsible types.Chat for the current update.

func (u *Update) GetChatInviteLink(req ...*tg.MessagesExportChatInviteRequest) (tg.ExportedChatInviteClass, error)

GetChatInviteLink generates an invite link for a chat.

Parameters:

  • chatID: The chat ID to generate invite link for (use 0 for current update's chat)
  • req: Telegram's MessagesExportChatInviteRequest (optional, use &tg.MessagesExportChatInviteRequest{} for default)

Returns exported chat invite or an error.

func (*Update) GetFullUser

func (u *Update) GetFullUser() (*tg.UserFull, error)

GetFullUser fetches full user information for the effective user. Returns nil if no user exists or on error.

func (*Update) GetLang

func (u *Update) GetLang() any

GetLang returns the user's current language preference. This method requires i18n middleware to be initialized.

Example:

lang := u.GetLang()

func (*Update) GetUser

func (u *Update) GetUser() (*tg.User, error)

GetUser fetches user information for the effective user. Returns nil if no user exists or on error.

func (*Update) GetUserChat

func (u *Update) GetUserChat() *types.User

GetUserChat returns the responsible types.User for the current update.

func (*Update) HasMessage

func (u *Update) HasMessage() bool

func (*Update) IsBot

func (u *Update) IsBot() bool

IsBot returns true if the current session belongs to a bot account.

func (*Update) IsBusinessUpdate

func (u *Update) IsBusinessUpdate() bool

IsBusinessUpdate returns true if this update originated from a business connection.

func (*Update) IsIncoming

func (u *Update) IsIncoming() bool

IsIncoming returns true if the effective message was sent by another user (not by this client). This is the inverse of IsOutgoing.

func (*Update) IsOutgoing

func (u *Update) IsOutgoing() bool

IsOutgoing returns true if the effective message was sent by this client (self). Works for both user accounts (via tg.Message.Out) and bot accounts (via FromID == Self.ID fallback, since bots always receive Out=false).

func (*Update) IsReply

func (u *Update) IsReply() bool

IsReply returns true if the effective message is a reply to another message.

func (*Update) LangCode

func (u *Update) LangCode() string

LangCode returns the language code of the effective user. Returns an empty string if no user exists.

func (*Update) LastName

func (u *Update) LastName() string

LastName returns the last name of the effective user. Returns an empty string if no user exists.

func (*Update) Mention

func (u *Update) Mention(args ...any) string

Mention generates an HTML mention link for a Telegram user.

Behavior: - No arguments: uses the Update's default UserID() and FullName(). - One argument:

  • int/int64 → overrides userID, keeps default name.
  • string → overrides name, keeps default userID.

- Two arguments: first is userID (int/int64), second is name (string). - The name can be any string, including numeric names. - Returns a string in the format: <a href='tg://user?id=USERID'>NAME</a>

func (*Update) MessageID

func (u *Update) MessageID() int

MessageID returns the message ID for this update (alias for MsgID).

func (*Update) MsgID

func (u *Update) MsgID() int

MsgID returns the message ID for this update. For messages, returns the message ID. For callback queries, returns the message ID that triggered the callback. Returns 0 if no message ID exists.

func (*Update) Pin

func (u *Update) Pin() (tg.UpdatesClass, error)

Pin pins the effective message in the chat. Returns updates confirming the action or an error.

func (*Update) Reply

func (u *Update) Reply(text any, opts ...*SendOpts) (*types.Message, error)

Reply sends a reply to the current update's message. Text can be a string or any type that can be formatted with %v. Uses the client's default parse mode from ClientOpts.ParseMode.

func (*Update) ReplyMedia

func (u *Update) ReplyMedia(media tg.InputMediaClass, opts ...*SendMediaOpts) (*types.Message, error)

ReplyMedia sends a media reply to the current update's message. Accepts tg.InputMediaClass (e.g., InputMediaPhoto, InputMediaDocument). Uses the client's default parse mode from ClientOpts.ParseMode for caption formatting.

Example using InputMedia:

newMsg, err := u.ReplyMedia(&tg.InputMediaPhoto{
    ID: &tg.InputPhoto{ID: photoID, AccessHash: accessHash},
}, &adapter.SendMediaOpts{
    Caption: "Photo caption",
})

For using fileID strings, see ReplyMediaWithFileID.

func (*Update) ReplyMediaWithFileID

func (u *Update) ReplyMediaWithFileID(fileID string, opts ...*SendMediaOpts) (*types.Message, error)

ReplyMediaWithFileID sends a media reply to the current update's message using a fileID string. The fileID should be obtained from a previous Message's FileID(), Document().FileID(), or Photo().FileID() method. Default parse mode for caption is HTML.

Example:

fileID := msg.FileID()  // or msg.Document().FileID() or msg.Photo().FileID()
newMsg, err := u.ReplyMediaWithFileID(fileID, &adapter.SendMediaOpts{
    Caption: "Here's the media you requested",
})

func (*Update) SendMedia

func (u *Update) SendMedia(media tg.InputMediaClass, caption string, opts ...*SendMediaOpts) (*types.Message, error)

SendMedia sends media (photo, document, video, etc.) to the chat associated with this update. Accepts tg.InputMediaClass (e.g., InputMediaPhoto, InputMediaDocument). Uses the client's default parse mode from ClientOpts.ParseMode for caption formatting.

NOTE: This method does NOT reply by default. To reply to a specific message, set ReplyMessageID in SendMediaOpts.

Parameters:

  • media: The media to send (tg.InputMediaClass)
  • caption: Optional caption text
  • opts: Optional SendMediaOpts

Returns the sent Message or an error.

Example using InputMedia:

msg, err := u.SendMedia(&tg.InputMediaPhoto{
    ID: &tg.InputPhoto{ID: photoID, AccessHash: accessHash},
}, "Photo caption")

Example using fileID (convert with types.InputMediaFromFileID):

media, _ := types.InputMediaFromFileID(fileID, "caption")
msg, err := u.SendMedia(media, "caption")

Example replying to a specific message:

msg, err := u.SendMedia(media, "caption", &SendMediaOpts{
    ReplyMessageID: 123,
})

func (*Update) SendMessage

func (u *Update) SendMessage(chatID int64, text string, opts ...*SendOpts) (*types.Message, error)

SendMessage sends a text message to the specified chat. Text can be a string or any type that can be formatted with %v. Uses the client's default parse mode from ClientOpts.ParseMode.

NOTE: This method does NOT reply by default. To reply to a specific message, set ReplyMessageID in SendOpts.

Parameters:

  • chatID: The target chat ID (use 0 to use the current update's chat)
  • text: The message text
  • opts: Optional SendOpts for formatting, reply markup, etc.

Returns the sent Message or an error.

Example:

msg, err := u.SendMessage(0, "Hello, world!")  // Send to current chat (no reply)
msg, err := u.SendMessage(chatID, "<b>Bold text</b>", &SendOpts{
    ParseMode: "HTML",
})
// Reply to a specific message:
msg, err := u.SendMessage(chatID, "Reply text", &SendOpts{
    ReplyMessageID: 123,
})

func (*Update) SendMultiMedia

func (u *Update) SendMultiMedia(media []tg.InputMediaClass, opts ...*SendMediaOpts) (*types.Message, error)

SendMultiMedia sends multiple media items as an album to the chat associated with this update. Albums can contain up to 10 media items.

NOTE: This method does NOT reply by default. To reply to a specific message, set ReplyMessageID in SendMediaOpts.

Parameters:

  • media: Slice of InputMediaClass items
  • opts: Optional SendMediaOpts (applied to all items)

Returns the sent Message or an error.

Example:

msgs, err := u.SendMultiMedia([]tg.InputMediaClass{
    &tg.InputMediaPhoto{ID: &tg.InputPhoto{...}},
    &tg.InputMediaPhoto{ID: &tg.InputPhoto{...}},
}, nil)

Example replying to a specific message:

msgs, err := u.SendMultiMedia(media, &SendMediaOpts{
    ReplyMessageID: 123,
})

func (*Update) SetLang

func (u *Update) SetLang(lang any)

SetLang sets the language preference for the effective user. This requires i18n middleware to be initialized.

Parameters:

  • lang: The language code (e.g., "en", "es") or language.Tag

func (*Update) StartConv

func (u *Update) StartConv(step string, text string, opts ...*ConvOpts) (*types.Message, error)

StartConv initiates a new conversation step with the user. It stores the conversation state and sends an optional message to the user. The conversation is identified by the current chat and user ID from the update.

Parameters:

  • step: A unique identifier for this conversation step (e.g., "awaiting_name")
  • text: The message text to send to the user
  • opts: Optional configuration for message sending and conversation behavior

Returns the sent message and any error encountered.

func (*Update) StartConvWithData

func (u *Update) StartConvWithData(step string, text string, data map[string]any, opts ...*ConvOpts) (*types.Message, error)

StartConvWithData initiates a new conversation step with custom data payload. Unlike StartConv, this method stores additional data that can be retrieved when the user responds, enabling stateful multi-step conversations.

Parameters:

  • step: A unique identifier for this conversation step
  • text: The message text to send to the user
  • data: Arbitrary data to store with the conversation state (will be JSON marshaled)
  • opts: Optional configuration for message sending and conversation behavior

Returns the sent message and any error encountered.

func (*Update) T

func (u *Update) T(key string, args ...any) string

T returns a translation for the given key. Supports both simple args and context (Args) for pluralization, gender, etc. This method requires i18n middleware to be initialized.

Examples:

// Simple translation with positional args
text := u.T("greeting", userName)

// Translation with context (pluralization, gender)
text := u.T("items_count", &i18n.Args{Count: 5})

// Translation with named args
text := u.T("welcome", &i18n.Args{Args: map[string]any{"name": userName}})

func (*Update) Text

func (u *Update) Text() string

Text returns the text content of the effective message. Returns an empty string if no message exists.

func (*Update) UnPin

func (u *Update) UnPin() error

UnPin unpins the effective message in the chat. Returns an error if the operation fails.

func (*Update) UnPinAll

func (u *Update) UnPinAll() error

UnPinAll unpins all messages in the current chat. Returns an error if the operation fails.

func (*Update) UserID

func (u *Update) UserID() int64

UserID returns the effective user ID for this update. Returns 0 if no user can be determined.

func (*Update) Username

func (u *Update) Username() string

Username returns the username of the effective user. Returns an empty string if no user exists or username is not set.

func (*Update) Usernames

func (u *Update) Usernames() []tg.Username

Usernames returns all usernames (including collected) of the effective user. Returns nil if no user exists.

Jump to

Keyboard shortcuts

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