MTGo Context API
Context wraps a Telegram update and provides convenience methods for responding. Each handler receives a *Context.
Fields
| Field | Type | Description |
|---|---|---|
Ctx | context.Context | Underlying context |
Client | *Client | MTGo client instance |
Update | tg.UpdateClass | Raw Telegram update |
Stopped | bool | Whether propagation is stopped |
PluginData | map[string]any | Shared data between plugins |
Message | *types.Message | Incoming message |
EditedMessage | *types.Message | Edited message |
BusinessMessage | *types.Message | Business connection message |
EditedBusinessMessage | *types.Message | Edited business message |
DeletedMessages | *tg.UpdateDeleteMessages | Deleted messages |
DeletedBusinessMessages | *tg.UpdateBotDeleteBusinessMessage | Deleted business messages |
CallbackQuery | *tg.UpdateBotCallbackQuery | Callback query |
InlineQuery | *tg.UpdateInlineBot | Inline query |
ChosenInlineResult | *tg.UpdateBotChosenInlineResult | Chosen inline result |
UserStatus | *tg.UpdateUserStatus | User status update |
ChatMember | *tg.UpdateChatParticipant | Chat member update |
MessageReaction | *tg.UpdateMessageReactions | Message reaction |
MessageReactionCount | *tg.UpdateMessageReactionCount | Reaction count update |
Poll | *tg.UpdateMessagePoll | Poll update |
BusinessConnection | *tg.UpdateBotBusinessConnect | Business connection |
Story | *tg.UpdateStory | Story update |
ChatBoost | *tg.UpdateBotChatBoost | Chat boost |
ChatJoinRequest | *tg.UpdateBotChatJoinRequest | Join request |
PreCheckoutQuery | *tg.UpdateBotPrecheckoutQuery | Pre-checkout query |
ShippingQuery | *tg.UpdateBotShippingQuery | Shipping query |
PurchasedPaidMedia | *tg.UpdateBotPurchasedPaidMedia | Paid media purchase |
ManagedBot | *tg.UpdateBotWebhookJSON | Managed bot update |
Error | error | Error from connection |
Connected | bool | Connection established |
Disconnected | bool | Connection lost |
Started | bool | Client fully started |
Core
NewContext
func NewContext(ctx context.Context) *ContextCreates a new context. Usually called internally by the dispatcher.
StopPropagation
func (c *Context) StopPropagation()Stops the update from being passed to subsequent handlers.
func handler(c *mtgo.Context) error {
c.StopPropagation()
return nil
}ResolvePeer
func (c *Context) ResolvePeer(id int64) interface{}Resolves a peer ID to a Telegram peer object.
Sender
func (c *Context) Sender() *types.UserReturns the user who sent the update.
user := ctx.Sender()
fmt.Printf("From: %s (ID: %d)\n", user.FirstName, user.ID)T
func (c *Context) T(key string, args ...any) stringReturns a translated string for the given key. Supports template arguments.
Message
Reply
func (c *Context) Reply(text string, opts ...*params.SendMessage) (*types.Message, error)Replies to the current message in the same chat.
| Parameter | Type | Description |
|---|---|---|
text | string | Message text |
opts | ...*params.SendMessage | Optional send parameters |
msg, err := ctx.Reply("Hello!")Edit
func (c *Context) Edit(text string, opts ...*params.EditMessage) (*types.Message, error)Edits the current message. Alias for EditText.
msg, err := ctx.Edit("Updated text")EditText
func (c *Context) EditText(text string, opts ...*params.EditMessage) (*types.Message, error)Edits the text of the current message.
EditCaption
func (c *Context) EditCaption(caption string, opts ...*params.EditMessage) (*types.Message, error)Edits the caption of the current message.
msg, err := ctx.EditCaption("New caption")EditMedia
func (c *Context) EditMedia(media tg.InputMediaClass, opts ...*params.EditMessage) (*types.Message, error)Replaces the media in the current message.
EditReplyMarkup
func (c *Context) EditReplyMarkup(replyMarkup tg.ReplyMarkupClass) (*types.Message, error)Changes the inline keyboard of the current message.
msg, err := ctx.EditReplyMarkup(&tg.ReplyInlineMarkup{
Rows: []tg.KeyboardButtonRow{
{Buttons: []tg.KeyboardButtonClass{
&tg.KeyboardButtonCallback{Text: "Done", Data: []byte("done")},
}},
},
})Delete
func (c *Context) Delete(opts ...*params.DeleteMessages) (int, error)Deletes the current message. Returns the number of messages deleted.
count, err := ctx.Delete()Forward
func (c *Context) Forward(chatID int64, opts ...*params.ForwardMessages) (*types.Message, error)Forwards the current message to another chat.
fwd, err := ctx.Forward(-1001234567890)Copy
func (c *Context) Copy(chatID int64, opts ...*params.CopyMessage) (int64, error)Copies the current message to another chat without the forward header.
newID, err := ctx.Copy(-1001234567890)Send
func (c *Context) Send(chatID int64, text string, opts ...*params.SendMessage) (*types.Message, error)Sends a text message to a specific chat.
msg, err := ctx.Send(-1001234567890, "Broadcast message")SendMedia
func (c *Context) SendMedia(chatID int64, media tg.InputMediaClass, caption string, opts ...*params.SendMessage) (*types.Message, error)Sends media to a specific chat.
msg, err := ctx.SendMedia(chatID, &tg.InputMediaUploadedPhoto{
File: uploadedFile,
}, "Photo caption")SendGame
func (c *Context) SendGame(chatID int64, gameShortName string, opts ...*params.SendMessage) (*types.Message, error)Sends a game to a chat.
React
func (c *Context) React(reaction ...tg.ReactionClass) errorAdds a reaction to the current message.
err := ctx.React(&tg.ReactionEmoji{Emoticon: "👍"})SendPaidReaction
func (c *Context) SendPaidReaction(amount int64) errorSends a paid reaction (Telegram Stars).
err := ctx.SendPaidReaction(50)Read / View
func (c *Context) Read() error
func (c *Context) View() errorMarks the current chat as read. View is an alias for Read.
err := ctx.Read()DownloadMedia
func (c *Context) DownloadMedia() ([]byte, error)Downloads the media attached to the current message.
data, err := ctx.DownloadMedia()
if err != nil {
return err
}
os.WriteFile("download.dat", data, 0644)DownloadMediaToFile
func (c *Context) DownloadMediaToFile(filePath string, fileSize int64) errorDownloads the current message media to a file on disk.
err := ctx.DownloadMediaToFile("photo.jpg", 0)Pin / Unpin
func (c *Context) Pin(opts ...*params.PinMessage) error
func (c *Context) Unpin() errorPins or unpins the current message.
err := ctx.Pin()
err = ctx.Unpin()SendChatAction
func (c *Context) SendChatAction(action tg.SendMessageActionClass) errorSends a chat action indicator (typing, uploading, etc.).
err := ctx.SendChatAction(&tg.SendMessageTypingAction{})GetMediaGroup
func (c *Context) GetMediaGroup() ([]*types.Message, error)Returns all messages in the current album/media group.
messages, err := ctx.GetMediaGroup()Vote
func (c *Context) Vote(options [][]byte) errorVotes in the current poll.
err := ctx.Vote([][]byte{[]byte("0")})StopPoll
func (c *Context) StopPoll() errorStops the current poll.
RetractVote
func (c *Context) RetractVote() errorRetracts the vote in the current poll.
DeleteChatHistory
func (c *Context) DeleteChatHistory(revoke bool) (int, error)Deletes the entire chat history. If revoke is true, deletes for both sides.
count, err := ctx.DeleteChatHistory(true)GetChatHistoryCount
func (c *Context) GetChatHistoryCount() (int, error)Returns the total message count in the current chat.
ForwardMediaGroup
func (c *Context) ForwardMediaGroup(chatID int64, opts ...*params.ForwardMessages) ([]*types.Message, error)Forwards a media group (album) to another chat.
ReadMentions
func (c *Context) ReadMentions() errorMarks mentions as read in the current chat.
ReadReactions
func (c *Context) ReadReactions() errorMarks reactions as read in the current chat.
Chat
GetChat
func (c *Context) GetChat() (*types.Chat, error)Returns information about the current chat.
chat, err := ctx.GetChat()
fmt.Printf("Chat: %s (ID: %d)\n", chat.Title, chat.ID)LeaveChat
func (c *Context) LeaveChat() errorLeaves the current chat.
Ban
func (c *Context) Ban(userID int64) errorBans a user from the current chat.
err := ctx.Ban(12345678)Unban
func (c *Context) Unban(userID int64) errorRemoves a ban on a user.
Restrict
func (c *Context) Restrict(userID int64, rights *tg.ChatBannedRights) errorRestricts a user with specific banned rights.
err := ctx.Restrict(userID, &tg.ChatBannedRights{
UntilDate: time.Now().Add(24 * time.Hour).Unix(),
SendMessages: true,
SendMedia: true,
})Promote
func (c *Context) Promote(userID int64, rights *tg.ChatAdminRights) errorPromotes a user to admin with specified rights.
err := ctx.Promote(userID, &tg.ChatAdminRights{
ChangeInfo: true,
DeleteMessages: true,
BanUsers: true,
})SetAdministratorTitle
func (c *Context) SetAdministratorTitle(userID int64, title string) errorSets a custom admin title for a promoted user.
err := ctx.SetAdministratorTitle(12345678, "Moderator")GetMember
func (c *Context) GetMember(userID int64) (*types.ChatMember, error)Gets a chat member's information.
member, err := ctx.GetMember(12345678)GetMembers
func (c *Context) GetMembers(limit, offset int) ([]*types.ChatMember, error)Returns chat members with pagination.
members, err := ctx.GetMembers(100, 0)SetTitle
func (c *Context) SetTitle(title string) errorChanges the chat title.
SetDescription
func (c *Context) SetDescription(about string) errorChanges the chat description/about text.
SetPhoto
func (c *Context) SetPhoto(photo tg.InputChatPhotoClass) errorSets a new chat photo.
DeleteChatPhoto
func (c *Context) DeleteChatPhoto() errorRemoves the chat photo.
SetTTL
func (c *Context) SetTTL(ttl int) errorSets the message TTL (Time-To-Live) for the chat.
SetPermissions
func (c *Context) SetPermissions(permissions *tg.ChatBannedRights) errorSets default chat permissions.
ExportInviteLink
func (c *Context) ExportInviteLink() (string, error)Generates a new primary invite link for the chat.
link, err := ctx.ExportInviteLink()
fmt.Printf("Invite: %s\n", link)Archive / Unarchive
func (c *Context) Archive() error
func (c *Context) Unarchive() errorArchives or unarchives the current chat.
MarkUnread
func (c *Context) MarkUnread(unread bool) errorMarks the chat as unread or read in the folder.
SetProtectedContent
func (c *Context) SetProtectedContent(enabled bool) errorEnables or disables content protection (no forwarding/screenshots).
UnpinAllMessages
func (c *Context) UnpinAllMessages() (int, error)Unpins all messages. Returns count of unpinned messages.
Mute / Unmute
func (c *Context) Mute() error
func (c *Context) Unmute() errorMutes or unmutes notifications for the current chat.
AddMembers
func (c *Context) AddMembers(userIDs []int64) errorAdds members to the current chat.
err := ctx.AddMembers([]int64{111, 222, 333})SetSlowMode
func (c *Context) SetSlowMode(seconds int) errorSets slow mode delay. Use 0 to disable.
GetChatEventLog
func (c *Context) GetChatEventLog(query string, limit int) ([]*types.ChatEvent, error)Retrieves chat event log (admin log) entries.
SearchMessages
func (c *Context) SearchMessages(query string, opts ...*SearchMessagesOption) ([]*types.Message, error)Searches messages in the current chat.
messages, err := ctx.SearchMessages("hello", &SearchMessagesOption{Limit: 10})GetHistory
func (c *Context) GetHistory(limit int, offsetID int32) ([]*types.Message, error)Retrieves chat message history.
messages, err := ctx.GetHistory(50, 0)GetCommonChats
func (c *Context) GetCommonChats(userID int64, limit int) ([]*types.Chat, error)Returns chats shared with a user.
Callback
Answer
func (c *Context) Answer(text string, showAlert bool) errorAnswers a callback query with an optional alert.
err := ctx.Answer("Processing...", false)AnswerCallbackQuery
func (c *Context) AnswerCallbackQuery(text string, showAlert bool) errorAlias for Answer.
AnswerCallback
func (c *Context) AnswerCallback(text string, showAlert bool) errorAlias for Answer.
CallbackEditText
func (c *Context) CallbackEditText(text string, opts ...*params.EditMessage) (*types.Message, error)Edits the message associated with the callback query.
msg, err := ctx.CallbackEditText("You selected: Option A")CallbackEditCaption
func (c *Context) CallbackEditCaption(caption string, opts ...*params.EditMessage) (*types.Message, error)Edits the caption of the callback message.
CallbackEditMedia
func (c *Context) CallbackEditMedia(media tg.InputMediaClass, opts ...*params.EditMessage) (*types.Message, error)Edits the media of the callback message.
CallbackEditReplyMarkup
func (c *Context) CallbackEditReplyMarkup(replyMarkup tg.ReplyMarkupClass) (*types.Message, error)Edits the inline keyboard of the callback message.
Inline
AnswerInlineQuery
func (c *Context) AnswerInlineQuery(results []tg.InputBotInlineResultClass, opts ...*AnswerInlineQueryOption) errorAnswers an inline query with results.
err := ctx.AnswerInlineQuery([]tg.InputBotInlineResultClass{
&tg.InputBotInlineResultArticle{
ID: "1",
Title: "Result",
Content: &tg.InputTextMessageContent{Message: "Hello!"},
},
})AnswerInline
func (c *Context) AnswerInline(results []tg.InputBotInlineResultClass, opts ...*AnswerInlineQueryOption) errorAlias for AnswerInlineQuery.
AnswerShipping
func (c *Context) AnswerShipping(queryID int64, ok bool, options []*tg.ShippingOption) errorAnswers a shipping query.
AnswerPreCheckout
func (c *Context) AnswerPreCheckout(queryID int64, ok bool, errorMessage string) errorAnswers a pre-checkout query.
err := ctx.AnswerPreCheckout(queryID, true, "")Account
GetBusinessConnection
func (c *Context) GetBusinessConnection(connectionID string) (*tg.BotBusinessConnection, error)Retrieves business connection information.
Payments
GetPaymentForm
func (c *Context) GetPaymentForm(chatID int64, messageID int32, opts ...*GetPaymentFormOption) (tg.PaymentFormClass, error)Retrieves a payment form for an invoice.
SendPaymentForm
func (c *Context) SendPaymentForm(formID int64, chatID int64, messageID int32, creds tg.InputPaymentCredentialsClass, opts ...*SendPaymentFormOption) (tg.PaymentResultClass, error)Submits payment credentials for an invoice.
GetStarsBalance
func (c *Context) GetStarsBalance(chatID int64) (int64, error)Returns the Telegram Stars balance for a chat.
balance, err := ctx.GetStarsBalance(chatID)
fmt.Printf("Stars balance: %d\n", balance)SendGift
func (c *Context) SendGift(userID int64, giftID int64, message string) errorSends a gift to a user.
Premium
ApplyBoost
func (c *Context) ApplyBoost(chatID int64, opts ...*ApplyBoostOption) ([]*tg.MyBoost, error)Applies a boost to a chat.
GetBoostsStatus
func (c *Context) GetBoostsStatus(chatID int64) (*tg.PremiumBoostsStatus, error)Returns boost status for a chat.
GetBoosts
func (c *Context) GetBoosts(opts ...*GetBoostsOption) ([]*tg.MyBoost, error)Returns the user's active boosts.
Stories
SendStory
func (c *Context) SendStory(chatID int64, media tg.InputMediaClass, opts ...*SendStoryOption) (*types.Story, error)Posts a new story.
story, err := ctx.SendStory(chatID, &tg.InputMediaUploadedPhoto{
File: uploadedFile,
})EditStoryCaption
func (c *Context) EditStoryCaption(chatID int64, storyID int32, caption string) (*types.Story, error)Edits a story's caption.
EditStoryMedia
func (c *Context) EditStoryMedia(chatID int64, storyID int32, media tg.InputMediaClass) (*types.Story, error)Replaces a story's media.
DeleteStories
func (c *Context) DeleteStories(chatID int64, storyIDs []int32) errorDeletes stories by ID.
GetStories
func (c *Context) GetStories(userID int64, storyIDs []int32) ([]*types.Story, error)Retrieves stories by user and IDs.
GetChatStories
func (c *Context) GetChatStories(chatID int64) ([]*types.Story, error)Retrieves all stories from a chat.
GetStoryViews
func (c *Context) GetStoryViews(chatID int64, storyIDs []int32) ([]*tg.StoryViewsTL, error)Returns view counts for stories.
ForwardStory
func (c *Context) ForwardStory(target int64, source int64, storyID int32) (*types.Message, error)Forwards a story to a chat.
ReadChatStories
func (c *Context) ReadChatStories(chatID int64, storyIDs []int32) errorMarks stories as read.
