Skip to content

MTGo Messages API

The Messages API provides comprehensive control over Telegram message operations including sending, editing, copying, pinning, reading, reacting, searching, forwarding, and deleting messages.

All methods are on the *Client type and accept context.Context as the first argument.

Imports

go
import (
    "context"
    "github.com/mtgo-labs/mtgo"
    "github.com/mtgo-labs/mtgo/params"
    "github.com/mtgo-labs/mtgo/types"
    "github.com/gotd/td/tg"
)

Sending

SendMessage

Sends a text message to a chat.

go
func (c *Client) SendMessage(ctx context.Context, chatID int64, text string, opts ...*params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context for cancellation and timeouts
chatIDint64YesTarget chat ID (user, group, or channel)
textstringYesMessage text to send
opts...*params.SendMessageNoOptional send parameters (reply markup, parse mode, etc.)

Returns

TypeDescription
*types.MessageThe sent message object on success
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundThe chatID does not correspond to an existing chat
ErrPeerFloodToo many messages sent to this peer recently
ErrChatWriteForbiddenNo permission to write in this chat
ErrUserBannedInChannelUser is banned from this channel
ErrMessageTooLongMessage text exceeds the maximum allowed length
ErrButtonTextTooLongInline button text exceeds limits

Example

go
msg, err := client.SendMessage(ctx, chatID, "Hello from MTGo!")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sent message ID: %d\n", msg.ID)

Example with options

go
msg, err := client.SendMessage(ctx, chatID, "**Bold text**",
    &params.SendMessage{
        ParseMode:  params.ParseModeMarkdown,
        ReplyTo:    &params.ReplyTo{MessageID: 42},
        LinkPreview: &params.LinkPreview{Disabled: true},
    },
)
if err != nil {
    log.Fatal(err)
}

SendContact

Sends a contact card to a chat.

go
func (c *Client) SendContact(ctx context.Context, chatID int64, phoneNumber, firstName, lastName string, opts *params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
phoneNumberstringYesContact phone number with country code
firstNamestringYesContact first name
lastNamestringYesContact last name (can be empty string)
opts*params.SendMessageNoOptional send parameters

Returns

TypeDescription
*types.MessageThe sent message containing the contact
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission
ErrPhoneNumberInvalidInvalid phone number format

Example

go
msg, err := client.SendContact(ctx, chatID, "+1234567890", "Alice", "Smith",
    &params.SendMessage{ReplyTo: &params.ReplyTo{MessageID: 10}},
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sent contact to %s %s\n", "Alice", "Smith")

SendLocation

Sends a geographic location to a chat.

go
func (c *Client) SendLocation(ctx context.Context, chatID int64, lat, lng float64, opts *params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
latfloat64YesLatitude coordinate
lngfloat64YesLongitude coordinate
opts*params.SendMessageNoOptional send parameters (supports LivePeriod)

Returns

TypeDescription
*types.MessageThe sent location message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission

Example

go
msg, err := client.SendLocation(ctx, chatID, 40.7128, -74.0060,
    &params.SendMessage{LivePeriod: 60},
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sent live location, message ID: %d\n", msg.ID)

SendVenue

Sends a venue (location with name and address) to a chat.

go
func (c *Client) SendVenue(ctx context.Context, chatID int64, lat, lng float64, title, address string, opts *params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
latfloat64YesLatitude coordinate
lngfloat64YesLongitude coordinate
titlestringYesVenue name / title
addressstringYesVenue physical address
opts*params.SendMessageNoOptional send parameters

Returns

TypeDescription
*types.MessageThe sent venue message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission

Example

go
msg, err := client.SendVenue(ctx, chatID,
    48.8584, 2.2945,
    "Eiffel Tower",
    "Champ de Mars, 5 Avenue Anatole France, Paris",
    nil,
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sent venue: %s\n", "Eiffel Tower")

SendDice

Sends an animated dice or game emoji to a chat.

go
func (c *Client) SendDice(ctx context.Context, chatID int64, opts ...*SendDiceOption) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
opts...*SendDiceOptionNoOptional dice parameters (emoji type, reply markup)

Returns

TypeDescription
*types.MessageThe sent dice message with the random result
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission

Example

go
// Standard dice
msg, err := client.SendDice(ctx, chatID)
if err != nil {
    log.Fatal(err)
}

// Darts emoji
msg, err = client.SendDice(ctx, chatID, &SendDiceOption{Emoji: "🎯"})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Dice result value: %d\n", msg.ReplyMarkup)

SendPoll

Sends a poll with options to a chat.

go
func (c *Client) SendPoll(ctx context.Context, chatID int64, question string, options []string, opts *params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
questionstringYesPoll question text
options[]stringYesSlice of poll answer options (minimum 2)
opts*params.SendMessageNoOptional send parameters (supports poll-specific options)

Returns

TypeDescription
*types.MessageThe sent poll message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission
ErrPollOptionsInvalidFewer than 2 options provided

Example

go
msg, err := client.SendPoll(ctx, chatID,
    "What is your favorite language?",
    []string{"Go", "Rust", "Python", "TypeScript"},
    &params.SendMessage{Anonymous: true},
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Poll sent, message ID: %d\n", msg.ID)

SendMedia

Sends a media attachment (photo, video, document, etc.) to a chat.

go
func (c *Client) SendMedia(ctx context.Context, chatID int64, media tg.InputMediaClass, caption string, opts ...*params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
mediatg.InputMediaClassYesMedia input object (photo, video, document, audio, etc.)
captionstringYesMedia caption text (can be empty)
opts...*params.SendMessageNoOptional send parameters

Returns

TypeDescription
*types.MessageThe sent media message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission
ErrMediaInvalidInvalid media input
ErrFileReferenceExpiredFile reference has expired, re-upload needed

Example

go
media := &tg.InputMediaPhoto{
    ID: &tg.InputPhotoFileLocation{
        ID:            photoID,
        AccessHash:    accessHash,
        FileReference: fileRef,
    },
}

msg, err := client.SendMedia(ctx, chatID, media, "Photo caption",
    &params.SendMessage{ParseMode: params.ParseModeHTML},
)
if err != nil {
    log.Fatal(err)
}

SendGame

Sends a game message to a chat.

go
func (c *Client) SendGame(ctx context.Context, chatID int64, gameShortName string, opts ...*params.SendMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
gameShortNamestringYesShort name of the game (registered via BotFather)
opts...*params.SendMessageNoOptional send parameters (supports inline keyboard)

Returns

TypeDescription
*types.MessageThe sent game message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatWriteForbiddenNo write permission
ErrGameNotFoundGame short name not registered

Example

go
msg, err := client.SendGame(ctx, chatID, "my_cool_game",
    &params.SendMessage{
        ReplyMarkup: &tg.ReplyInlineMarkup{
            Rows: []tg.KeyboardButtonRow{
                {Buttons: []tg.KeyboardButtonClass{
                    &tg.KeyboardButtonGame{Text: "Play Now"},
                }},
            },
        },
    },
)
if err != nil {
    log.Fatal(err)
}

SendChatAction

Sends a "typing" or other chat action indicator to a chat.

go
func (c *Client) SendChatAction(ctx context.Context, chatID int64, action tg.SendMessageActionClass) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesTarget chat ID
actiontg.SendMessageActionClassYesAction type (typing, upload photo, record video, etc.)

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID

Example

go
err := client.SendChatAction(ctx, chatID, &tg.SendMessageTypingAction{})
if err != nil {
    log.Fatal(err)
}

// Show upload progress
err = client.SendChatAction(ctx, chatID, &tg.SendMessageUploadPhotoAction{Progress: 50})
if err != nil {
    log.Fatal(err)
}

Available Actions

Action ClassDescription
SendMessageTypingActionUser is typing a message
SendMessageCancelActionCancel the current action
SendMessageRecordVideoActionRecording a video
SendMessageUploadVideoActionUploading a video
SendMessageRecordAudioActionRecording voice message
SendMessageUploadAudioActionUploading voice message
SendMessageUploadPhotoActionUploading a photo
SendMessageUploadDocumentActionUploading a file
SendMessageGeoLocationActionSelecting a location
SendMessageChooseContactActionSelecting a contact
SendMessageGamePlayActionPlaying a game
SendMessageRecordRoundActionRecording a round video
SendMessageUploadRoundActionUploading a round video
SendMessageSpeakCallActionSpeaking in a group call

Editing

EditMessageText

Edits the text of an existing message.

go
func (c *Client) EditMessageText(ctx context.Context, chatID int64, messageID int32, text string, opts ...*params.EditMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to edit
textstringYesNew message text
opts...*params.EditMessageNoOptional edit parameters (parse mode, reply markup, etc.)

Returns

TypeDescription
*types.MessageThe edited message
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist in this chat
ErrMessageEditTimeExpiredMessage is too old to edit
ErrMessageAuthorYou are not the author of this message
ErrMessageNotModifiedNew text is identical to the current text

Example

go
edited, err := client.EditMessageText(ctx, chatID, msgID, "Updated text",
    &params.EditMessage{
        ParseMode: params.ParseModeHTML,
    },
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Edited message ID: %d\n", edited.ID)

EditMessageCaption

Edits the caption of a media message.

go
func (c *Client) EditMessageCaption(ctx context.Context, chatID int64, messageID int32, caption string, opts ...*params.EditMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the media message to edit
captionstringYesNew caption text
opts...*params.EditMessageNoOptional edit parameters

Returns

TypeDescription
*types.MessageThe edited message
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist
ErrMessageEditTimeExpiredMessage is too old to edit
ErrMessageAuthorNot the message author
ErrMessageNotModifiedCaption unchanged

Example

go
edited, err := client.EditMessageCaption(ctx, chatID, msgID, "New caption text", nil)
if err != nil {
    log.Fatal(err)
}

EditMessageMedia

Edits the media attachment of an existing message.

go
func (c *Client) EditMessageMedia(ctx context.Context, chatID int64, messageID int32, media tg.InputMediaClass, opts ...*params.EditMessage) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to edit
mediatg.InputMediaClassYesNew media input object
opts...*params.EditMessageNoOptional edit parameters

Returns

TypeDescription
*types.MessageThe edited message with updated media
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist
ErrMessageEditTimeExpiredMessage is too old to edit
ErrMessageAuthorNot the message author
ErrMediaInvalidInvalid media input

Example

go
newMedia := &tg.InputMediaPhoto{
    ID: &tg.InputPhotoFileLocation{
        ID:            newPhotoID,
        AccessHash:    accessHash,
        FileReference: fileRef,
    },
}

edited, err := client.EditMessageMedia(ctx, chatID, msgID, newMedia)
if err != nil {
    log.Fatal(err)
}

EditMessageReplyMarkup

Edits only the reply markup (inline keyboard) of an existing message.

go
func (c *Client) EditMessageReplyMarkup(ctx context.Context, chatID int64, messageID int32, replyMarkup tg.ReplyMarkupClass) (*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to edit
replyMarkuptg.ReplyMarkupClassYesNew reply markup (inline keyboard)

Returns

TypeDescription
*types.MessageThe edited message
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist
ErrMessageAuthorNot the message author
ErrMessageNotModifiedReply markup unchanged

Example

go
edited, err := client.EditMessageReplyMarkup(ctx, chatID, msgID,
    &tg.ReplyInlineMarkup{
        Rows: []tg.KeyboardButtonRow{
            {Buttons: []tg.KeyboardButtonClass{
                &tg.KeyboardButtonCallback{
                    Text: "Clicked!",
                    Data: []byte("btn_clicked"),
                },
            }},
        },
    },
)
if err != nil {
    log.Fatal(err)
}

Copying

CopyMessage

Copies a message from one chat to another without a forward link.

go
func (c *Client) CopyMessage(ctx context.Context, toChatID, fromChatID int64, messageID int32, opts ...*params.CopyMessage) (int64, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
toChatIDint64YesDestination chat ID
fromChatIDint64YesSource chat ID
messageIDint32YesID of the message to copy
opts...*params.CopyMessageNoOptional copy parameters (caption, parse mode, etc.)

Returns

TypeDescription
int64ID of the new copied message
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundSource or destination chat does not exist
ErrMessageNotFoundMessage ID does not exist in the source chat
ErrChatWriteForbiddenNo write permission in destination chat

Example

go
newMsgID, err := client.CopyMessage(ctx, destChatID, srcChatID, 42,
    &params.CopyMessage{
        Caption: "Forwarded content",
    },
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Copied as message ID: %d\n", newMsgID)

CopyMediaGroup

Copies an entire album (media group) from one chat to another.

go
func (c *Client) CopyMediaGroup(ctx context.Context, toChatID, fromChatID int64, messageIDs []int32, opts ...*params.CopyMessage) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
toChatIDint64YesDestination chat ID
fromChatIDint64YesSource chat ID
messageIDs[]int32YesIDs of the media group messages to copy
opts...*params.CopyMessageNoOptional copy parameters

Returns

TypeDescription
[]*types.MessageSlice of newly copied messages
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundSource or destination chat does not exist
ErrMessageNotFoundOne or more message IDs not found
ErrChatWriteForbiddenNo write permission in destination chat
ErrMediaGroupInvalidMessages do not form a valid media group

Example

go
messages, err := client.CopyMediaGroup(ctx, destChatID, srcChatID, []int32{100, 101, 102})
if err != nil {
    log.Fatal(err)
}
for _, m := range messages {
    fmt.Printf("Copied message ID: %d\n", m.ID)
}

Pinning

PinMessage

Pins a message in a chat.

go
func (c *Client) PinMessage(ctx context.Context, chatID int64, messageID int32, opts ...*params.PinMessage) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to pin
opts...*params.PinMessageNoOptional pin parameters (notify, single pin, etc.)

Returns

TypeDescription
intResult code (0 on success)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrMessageNotFoundMessage ID does not exist
ErrChatAdminRequiredPinning requires admin privileges
ErrPinLimitExceededToo many pinned messages

Example

go
result, err := client.PinMessage(ctx, chatID, 42,
    &params.PinMessage{Notify: true},
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Pin result: %d\n", result)

UnpinMessage

Unpins a specific message from a chat.

go
func (c *Client) UnpinMessage(ctx context.Context, chatID int64, messageID int32) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID
messageIDint32YesID of the message to unpin

Returns

TypeDescription
intResult code (0 on success)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrMessageNotFoundMessage is not pinned
ErrChatAdminRequiredUnpinning requires admin privileges

Example

go
result, err := client.UnpinMessage(ctx, chatID, 42)
if err != nil {
    log.Fatal(err)
}

UnpinAllMessages

Unpins all pinned messages in a chat.

go
func (c *Client) UnpinAllMessages(ctx context.Context, chatID int64) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID

Returns

TypeDescription
intResult code (0 on success)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrChatAdminRequiredRequires admin privileges

Example

go
result, err := client.UnpinAllMessages(ctx, chatID)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("All messages unpinned, result: %d\n", result)

Reading

ReadHistory

Marks all messages in a chat as read up to a specific message.

go
func (c *Client) ReadHistory(ctx context.Context, chatID int64, maxID int32) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID to mark as read
maxIDint32YesMaximum message ID to mark as read (0 for all)

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID

Example

go
err := client.ReadHistory(ctx, chatID, 0)
if err != nil {
    log.Fatal(err)
}
fmt.Println("All messages marked as read")

ReadMentions

Marks all mentions in a chat as read.

go
func (c *Client) ReadMentions(ctx context.Context, chatID int64) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID

Example

go
err := client.ReadMentions(ctx, chatID)
if err != nil {
    log.Fatal(err)
}

ReadReactions

Marks all reactions in a chat as read.

go
func (c *Client) ReadReactions(ctx context.Context, chatID int64) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID

Example

go
err := client.ReadReactions(ctx, chatID)
if err != nil {
    log.Fatal(err)
}

Reactions

SendReaction

Sends an emoji reaction to a message.

go
func (c *Client) SendReaction(ctx context.Context, chatID int64, messageID int32, reaction ...tg.ReactionClass) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to react to
reaction...tg.ReactionClassYesOne or more reaction objects (variadic)

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist
ErrReactionInvalidInvalid reaction emoji
ErrReactionLimitExceededToo many reactions on this message

Example

go
err := client.SendReaction(ctx, chatID, msgID,
    &tg.ReactionEmoji{Emoticon: "👍"},
)
if err != nil {
    log.Fatal(err)
}

// Multiple reactions
err = client.SendReaction(ctx, chatID, msgID,
    &tg.ReactionEmoji{Emoticon: "🔥"},
    &tg.ReactionEmoji{Emoticon: "❤️"},
)

SendPaidReaction

Sends a paid (star) reaction to a message.

go
func (c *Client) SendPaidReaction(ctx context.Context, chatID int64, messageID int32, amount int64) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of the message to react to
amountint64YesNumber of paid reactions (stars) to send

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundMessage ID does not exist
ErrPaymentStarsNeededInsufficient star balance
ErrReactionInvalidInvalid amount

Example

go
err := client.SendPaidReaction(ctx, chatID, msgID, 50)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Sent 50 star reaction")

VotePoll

Votes on a poll option.

go
func (c *Client) VotePoll(ctx context.Context, chatID int64, messageID int32, options [][]byte) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the poll message exists
messageIDint32YesID of the poll message
options[][]byteYesByte-encoded option indices to vote for

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundPoll message does not exist
ErrPollVoteNotAllowedVoting not allowed (poll closed or quiz already answered)
ErrPollOptionsInvalidInvalid option indices

Example

go
err := client.VotePoll(ctx, chatID, pollMsgID, [][]byte{{0}, {2}})
if err != nil {
    log.Fatal(err)
}
fmt.Println("Voted for options 0 and 2")

StopPoll

Stops an active poll, preventing further votes.

go
func (c *Client) StopPoll(ctx context.Context, chatID int64, messageID int32) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the poll exists
messageIDint32YesID of the poll message

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundPoll message does not exist
ErrMessageAuthorNot the poll creator
ErrPollAlreadyClosedPoll is already closed

Example

go
err := client.StopPoll(ctx, chatID, pollMsgID)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Poll closed")

RetractVote

Retracts (removes) a vote from a poll.

go
func (c *Client) RetractVote(ctx context.Context, chatID int64, messageID int32) error

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the poll exists
messageIDint32YesID of the poll message

Returns

TypeDescription
errorNon-nil on failure

Errors

ErrorCondition
ErrMessageNotFoundPoll message does not exist
ErrPollVoteNotAllowedNo vote to retract or poll is closed

Example

go
err := client.RetractVote(ctx, chatID, pollMsgID)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Vote retracted")

Searching

SearchMessages

Searches for messages within a specific chat.

go
func (c *Client) SearchMessages(ctx context.Context, chatID int64, query string, opts ...*SearchMessagesOption) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID to search within
querystringYesSearch query string
opts...*SearchMessagesOptionNoOptional search parameters (limit, offset, filter, etc.)

Returns

TypeDescription
[]*types.MessageSlice of matching messages
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrSearchQueryEmptyQuery string is empty

Example

go
messages, err := client.SearchMessages(ctx, chatID, "hello world",
    &SearchMessagesOption{Limit: 50},
)
if err != nil {
    log.Fatal(err)
}
for _, m := range messages {
    fmt.Printf("Found message %d: %s\n", m.ID, m.Text())
}

SearchGlobal

Searches for messages across all chats.

go
func (c *Client) SearchGlobal(ctx context.Context, query string, opts ...*SearchGlobalOption) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
querystringYesSearch query string
opts...*SearchGlobalOptionNoOptional search parameters (limit, offset, etc.)

Returns

TypeDescription
[]*types.MessageSlice of matching messages from all chats
errorNon-nil on failure

Errors

ErrorCondition
ErrSearchQueryEmptyQuery string is empty
ErrSearchQueryTooLongQuery exceeds maximum length

Example

go
messages, err := client.SearchGlobal(ctx, "important announcement",
    &SearchGlobalOption{Limit: 20},
)
if err != nil {
    log.Fatal(err)
}
for _, m := range messages {
    fmt.Printf("[Chat %d] Message %d: %s\n", m.ChatID(), m.ID, m.Text())
}

SearchMessagesCount

Returns the count of messages matching a query in a specific chat.

go
func (c *Client) SearchMessagesCount(ctx context.Context, chatID int64, query string, opts ...*SearchMessagesOption) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID to search within
querystringYesSearch query string
opts...*SearchMessagesOptionNoOptional search parameters

Returns

TypeDescription
intNumber of matching messages
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrSearchQueryEmptyQuery string is empty

Example

go
count, err := client.SearchMessagesCount(ctx, chatID, "meeting")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d messages about 'meeting'\n", count)

SearchGlobalCount

Returns the count of messages matching a query across all chats.

go
func (c *Client) SearchGlobalCount(ctx context.Context, query string, opts ...*SearchGlobalOption) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
querystringYesSearch query string
opts...*SearchGlobalOptionNoOptional search parameters

Returns

TypeDescription
intNumber of matching messages globally
errorNon-nil on failure

Errors

ErrorCondition
ErrSearchQueryEmptyQuery string is empty
ErrSearchQueryTooLongQuery exceeds maximum length

Example

go
count, err := client.SearchGlobalCount(ctx, "deploy")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d messages globally about 'deploy'\n", count)

Forwarding & Deletion

ForwardMessages

Forwards messages from one chat to another. Forwarded messages include a "forwarded from" header.

go
func (c *Client) ForwardMessages(ctx context.Context, toChatID, fromChatID int64, messageIDs []int32, opts ...*params.ForwardMessages) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
toChatIDint64YesDestination chat ID
fromChatIDint64YesSource chat ID
messageIDs[]int32YesIDs of messages to forward
opts...*params.ForwardMessagesNoOptional forward parameters (drop author, etc.)

Returns

TypeDescription
[]*types.MessageSlice of forwarded messages
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundSource or destination chat does not exist
ErrMessageNotFoundOne or more message IDs not found
ErrChatWriteForbiddenNo write permission in destination
ErrForwardNotAllowedMessage author has disabled forwarding

Example

go
forwarded, err := client.ForwardMessages(ctx, destChatID, srcChatID, []int32{10, 11, 12},
    &params.ForwardMessages{DropAuthor: true},
)
if err != nil {
    log.Fatal(err)
}
for _, m := range forwarded {
    fmt.Printf("Forwarded message ID: %d\n", m.ID)
}

ForwardMediaGroup

Forwards an entire album (media group) from one chat to another.

go
func (c *Client) ForwardMediaGroup(ctx context.Context, toChatID, fromChatID int64, messageIDs []int32, opts ...*params.ForwardMessages) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
toChatIDint64YesDestination chat ID
fromChatIDint64YesSource chat ID
messageIDs[]int32YesIDs of the media group messages
opts...*params.ForwardMessagesNoOptional forward parameters

Returns

TypeDescription
[]*types.MessageSlice of forwarded media messages
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundSource or destination chat does not exist
ErrMessageNotFoundOne or more message IDs not found
ErrChatWriteForbiddenNo write permission in destination
ErrMediaGroupInvalidMessages do not form a valid media group
ErrForwardNotAllowedForwarding disabled by author

Example

go
forwarded, err := client.ForwardMediaGroup(ctx, destChatID, srcChatID, []int32{200, 201, 202})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Forwarded %d media items\n", len(forwarded))

DeleteMessages

Deletes one or more messages from a chat.

go
func (c *Client) DeleteMessages(ctx context.Context, chatID int64, messageIDs []int32, opts ...*params.DeleteMessages) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where messages exist
messageIDs[]int32YesIDs of messages to delete
opts...*params.DeleteMessagesNoOptional delete parameters (revoke for both sides)

Returns

TypeDescription
intResult code (0 on success)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrMessageNotFoundOne or more message IDs not found
ErrMessageDeleteForbiddenNo permission to delete these messages
ErrMessageTooOldMessages are too old to delete

Example

go
result, err := client.DeleteMessages(ctx, chatID, []int32{100, 101, 102},
    &params.DeleteMessages{Revoke: true},
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Delete result: %d\n", result)

DeleteChatHistory

Deletes the entire chat history for a specific chat.

go
func (c *Client) DeleteChatHistory(ctx context.Context, chatID int64, maxID int32, revoke bool) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID to clear history for
maxIDint32YesMaximum message ID to delete up to (0 for all)
revokeboolYesIf true, delete for both sides

Returns

TypeDescription
intResult code (0 on success)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrMessageDeleteForbiddenNo permission to delete history

Example

go
result, err := client.DeleteChatHistory(ctx, chatID, 0, true)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Chat history deleted, result: %d\n", result)

History

GetChatHistory

Retrieves message history from a chat.

go
func (c *Client) GetChatHistory(ctx context.Context, chatID int64, limit int, offsetID int32) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID to retrieve history from
limitintYesMaximum number of messages to return
offsetIDint32YesMessage ID to start from (0 for most recent)

Returns

TypeDescription
[]*types.MessageSlice of historical messages (newest first)
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrHistoryAccessDeniedNo access to chat history

Example

go
messages, err := client.GetChatHistory(ctx, chatID, 50, 0)
if err != nil {
    log.Fatal(err)
}
for _, m := range messages {
    fmt.Printf("[%d] %s\n", m.ID, m.Text())
}

Pagination example

go
var allMessages []*types.Message
offsetID := int32(0)

for {
    messages, err := client.GetChatHistory(ctx, chatID, 100, offsetID)
    if err != nil {
        log.Fatal(err)
    }
    if len(messages) == 0 {
        break
    }
    allMessages = append(allMessages, messages...)
    offsetID = messages[len(messages)-1].ID
}
fmt.Printf("Fetched %d total messages\n", len(allMessages))

GetChatHistoryCount

Returns the total number of messages in a chat.

go
func (c *Client) GetChatHistoryCount(ctx context.Context, chatID int64) (int, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID

Returns

TypeDescription
intTotal message count in the chat
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrHistoryAccessDeniedNo access to chat history

Example

go
count, err := client.GetChatHistoryCount(ctx, chatID)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Chat has %d messages\n", count)

GetMediaGroup

Retrieves all messages belonging to the same media group (album).

go
func (c *Client) GetMediaGroup(ctx context.Context, chatID int64, messageID int32) ([]*types.Message, error)

Parameters

NameTypeRequiredDescription
ctxcontext.ContextYesRequest context
chatIDint64YesChat ID where the message exists
messageIDint32YesID of any message in the media group

Returns

TypeDescription
[]*types.MessageAll messages in the album/media group
errorNon-nil on failure

Errors

ErrorCondition
ErrChatNotFoundInvalid chat ID
ErrMessageNotFoundMessage ID does not exist
ErrMediaGroupInvalidMessage is not part of a media group

Example

go
messages, err := client.GetMediaGroup(ctx, chatID, 42)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Album contains %d items\n", len(messages))
for _, m := range messages {
    fmt.Printf("  Message %d\n", m.ID)
}

Released under the Apache-2.0 License.