functions

package
v1.0.0-beta24 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: GPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Admin      = "admin"
	Creator    = "creator"
	Member     = "member"
	Restricted = "restricted"
	Left       = "left"
)

Variables

This section is empty.

Functions

func AddChatMembers

func AddChatMembers(ctx context.Context, raw *tg.Client, chatPeer tg.InputPeerClass, users []tg.InputUserClass, forwardLimit int) (bool, error)

AddChatMembers adds multiple users to a chat.

Example:

users := []tg.InputUserClass{
    &tg.InputUser{UserID: 12345678, AccessHash: 1234567890},
    &tg.InputUser{UserID: 87654321, AccessHash: 9876543210},
}
success, err := functions.AddChatMembers(ctx, client.Raw, chatPeer, users, 50)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • chatPeer: The chat peer to add users to
  • users: List of users to add
  • forwardLimit: Maximum number of messages to forward from old chat

Returns true if successful, or an error.

func ArchiveChats

func ArchiveChats(ctx context.Context, client *tg.Client, peers []tg.InputPeerClass) (bool, error)

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

Example:

peers := []tg.InputPeerClass{chatPeer1, chatPeer2}
success, err := functions.ArchiveChats(ctx, client.Raw, peers)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • peers: List of peers to archive

Returns true if successful, or an error.

func BanChatMember

func BanChatMember(ctx context.Context, client *tg.Client, chatPeer tg.InputPeerClass, userPeer *tg.InputPeerUser, untilDate int) (tg.UpdatesClass, error)

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

Example:

userPeer := &tg.InputPeerUser{UserID: 12345678, AccessHash: 1234567890}
updates, err := functions.BanChatMember(ctx, client.Raw, chatPeer, userPeer, 0)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • chatPeer: The chat peer to ban user from
  • userPeer: The user peer to ban
  • untilDate: Unix timestamp until when the ban is active (0 for permanent)

Returns updates confirming the action or an error.

func BuyResaleStarGift

func BuyResaleStarGift(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, slug string, toID any) (tg.PaymentsPaymentResultClass, error)

BuyResaleStarGift purchases a resale star gift by slug for a recipient.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • slug: The unique slug of the resale gift
  • toID: Recipient as tg.InputPeerClass, int64 (userID), or string (username)

Returns the payment result or an error.

func CreateChannel

func CreateChannel(ctx context.Context, client *tg.Client, p *storage.PeerStorage, title, about string, broadcast bool) (*tg.Channel, error)

CreateChannel creates a new channel (supergroup or broadcast).

Example:

channel, err := functions.CreateChannel(ctx, client.Raw, client.PeerStorage, "My Channel", "Channel description", false)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Created channel ID: %d\n", channel.ID)

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • p: Peer storage for resolving peer references
  • title: The channel title
  • about: The channel description
  • broadcast: Whether this is a broadcast channel (false for supergroup)

Returns the created channel or an error.

func CreateChat

func CreateChat(ctx context.Context, client *tg.Client, p *storage.PeerStorage, title string, users []tg.InputUserClass) (*tg.Chat, error)

CreateChat creates a new group chat.

Example:

users := []tg.InputUserClass{
    &tg.InputUser{UserID: 12345678, AccessHash: 1234567890},
}
chat, err := functions.CreateChat(ctx, client.Raw, client.PeerStorage, "My Group", users)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Created chat ID: %d\n", chat.ID)

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • p: Peer storage for resolving peer references
  • title: The chat title
  • users: List of users to add to the chat

Returns the created chat or an error.

func DecodeStringToSession

func DecodeStringToSession(sessionString string) (*storage.Session, error)

DecodeStringToSession decodes the provided base64 encoded session string to session.Data.

Parameters:

  • sessionString: The base64 encoded session string to decode

Returns decoded session or an error.

func DeleteMessages

func DeleteMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, messageIDs []int) error

DeleteMessages deletes messages in a chat with given chat ID and message IDs.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID containing the messages
  • messageIDs: List of message IDs to delete

Returns an error if the operation fails.

func DemoteChatMember

func DemoteChatMember(ctx context.Context, client *tg.Client, chat, user *storage.Peer, rights tg.ChatAdminRights, title string) (bool, error)

DemoteChatMember demotes an admin to regular member in a chat.

Example:

rights := tg.ChatAdminRights{} // Empty rights to remove all admin privileges
success, err := functions.DemoteChatMember(ctx, client.Raw, chatPeer, userPeer, rights, "")
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for API call
  • client: The raw Telegram client
  • chat: The chat peer storage
  • user: The user peer storage to demote
  • rights: Admin rights to remove (set to empty)
  • title: Custom admin rank/title to remove

Returns true if successful, or an error.

func Disable2FA

func Disable2FA(ctx context.Context, raw *tg.Client, currentPassword string) error

Disable2FA removes the 2FA cloud password from the account.

The current password is required for verification via SRP.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • currentPassword: The current 2FA password for verification

Returns an error if 2FA is not enabled or the operation fails.

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

func Dump

func Dump(val any, key ...string) string

Dump returns a pretty-printed JSON representation of any value. If key is provided, the output is prefixed with [key]. Types implementing Dumpable will have DumpValue() serialized instead.

func EditMessage

func EditMessage(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, chatID int64, request *tg.MessagesEditMessageRequest, businessConnectionID ...string) (*tg.Message, error)

EditMessage edits a message in a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • chatID: The chat ID containing the message
  • request: The edit message request parameters

Returns the edited message or an error.

func Enable2FA

func Enable2FA(ctx context.Context, raw *tg.Client, newPassword string, opts *PasswordOpts) error

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

This should only be called when the account does not already have 2FA enabled. Use Update2FA to change an existing password.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • newPassword: The new 2FA password to set
  • opts: Optional hint and recovery email (can be nil)

Returns an error if 2FA is already enabled or the operation fails.

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

func EncodeSessionToString

func EncodeSessionToString(session *storage.Session) (string, error)

EncodeSessionToString encodes the provided session to a string in base64 using json bytes.

Parameters:

  • session: The session object to encode

Returns encoded session string or an error.

func ExportInvoice

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

ExportInvoice exports an invoice for use with payment providers.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • inputMedia: The invoice media to export

Returns exported invoice or an error.

func ExtractParticipantRights

func ExtractParticipantRights(participant tg.ChannelParticipantClass) *tg.ChatAdminRights

ExtractParticipantRights extracts admin rights from a channel participant. Returns nil if the participant is not an admin/creator or has no rights.

Parameters:

  • participant: The channel participant to extract rights from

Returns ChatAdminRights if present, nil otherwise.

func ExtractParticipantStatus

func ExtractParticipantStatus(participant tg.ChannelParticipantClass) string

ExtractParticipantStatus extracts the status string from a channel participant.

Parameters:

  • participant: The channel participant to extract status from

Returns status string (Creator, Admin, Member, Restricted, or Left).

func ExtractParticipantTitle

func ExtractParticipantTitle(participant tg.ChannelParticipantClass) string

ExtractParticipantRank extracts the rank string from a channel participant. Returns empty string for participants without rank.

Parameters:

  • participant: The channel participant to extract rank from

Returns rank string if present, empty otherwise.

func ExtractParticipantUserID

func ExtractParticipantUserID(participant tg.ChannelParticipantClass) int64

ExtractParticipantUserID extracts the user ID from a channel participant.

Parameters:

  • participant: The channel participant to extract user ID from

Returns user ID, or 0 if not found.

func ForwardMessages

func ForwardMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, fromChatID, toChatID int64, request *tg.MessagesForwardMessagesRequest) (tg.UpdatesClass, error)

ForwardMessages forwards messages from one chat to another.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • fromChatID: The source chat ID to forward from
  • toChatID: The destination chat ID to forward to
  • request: The forward messages request parameters

Returns updates confirming the action or an error.

func GenerateRandomID

func GenerateRandomID() int64

GenerateRandomID generates a cryptographically random int64. This is thread-safe (crypto/rand is safe for concurrent use) and avoids the weak math/rand generator (Issue #112, gosec G404).

func GetAccessHashFromResolved

func GetAccessHashFromResolved(users []tg.UserClass, userID int64) int64

GetAccessHashFromResolved extracts access hash for a user from resolved users.

func GetAccessHashFromResolvedChats

func GetAccessHashFromResolvedChats(chats []tg.ChatClass, channelID int64) int64

GetAccessHashFromResolvedChats extracts access hash for a channel from resolved chats.

func GetActiveSessions

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

GetActiveSessions returns all active authorized sessions for the current account.

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

func GetChannelMessages

func GetChannelMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, peer tg.InputChannelClass, messageIds []tg.InputMessageClass) (tg.MessageClassArray, error)

GetChannelMessages fetches messages from a channel.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • peer: The channel peer to fetch messages from
  • messageIds: List of message IDs to fetch

Returns list of messages or an error.

func GetChat

func GetChat(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64) (tg.ChatClass, error)

GetChat returns basic chat information for the provided chat ID. Uses MessagesGetChats for efficient single-chat lookup.

Example:

chat, err := functions.GetChat(ctx, client.Raw, chatID)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Title: %s, Participants: %d\n",
    chat.Title(), len(chat.ParticipantsCount))

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • chatID: The chat ID to get basic information for

Returns basic Chat or Channel information (no full details).

func GetChatIDFromPeer

func GetChatIDFromPeer(peer tg.PeerClass) int64

GetChatIDFromPeer returns a chat/user id from the provided tg.PeerClass.

Parameters:

  • peer: The peer object to extract ID from

Returns chat/user ID.

GetChatInviteLink generates an invite link for a chat.

Parameters:

  • ctx: Context for API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID to generate invite link for
  • req: Telegram's MessagesExportChatInviteRequest (use &tg.MessagesExportChatInviteRequest{} for default)

Returns exported chat invite or an error.

func GetChatMember

func GetChatMember(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID, userID int64) (tg.ChannelParticipantClass, error)

GetChatMember fetches information about a chat member. For channels, returns tg.ChannelParticipantClass with member details. For regular chats, use GetChatMemberInChat instead.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The channel ID to query
  • userID: The user ID to look up

Returns participant information or an error.

func GetChatMembers

func GetChatMembers(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, opts ...*GetChatMembersOpts) ([]tg.ChannelParticipantClass, error)

GetChatMembers returns a list of members from a chat or channel. For channels/supergroups, it calls channels.getParticipants with pagination. For basic groups, it fetches all participants via messages.getFullChat.

func GetChatMessages

func GetChatMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, messageIds []tg.InputMessageClass) (tg.MessageClassArray, error)

GetChatMessages fetches messages from a regular chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • messageIds: List of message IDs to fetch

Returns list of messages or an error.

func GetEditMessageUpdate

func GetEditMessageUpdate(upds tg.UpdatesClass, p *storage.PeerStorage) *tg.Message

GetEditMessageUpdate extracts the edited message from updates.

Parameters:

  • upds: The updates class to extract from
  • p: Peer storage for resolving peer references

Returns the edited message or nil.

func GetFullChat

func GetFullChat(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64) (tg.ChatFullClass, error)

GetFullChat returns full chat details for the provided chat ID. Uses ChannelsGetFullChannel for channels or MessagesGetFullChat for groups.

Example:

fullChat, err := functions.GetFullChat(ctx, client.Raw, client.PeerStorage, chatID)
if err != nil {
    log.Fatal(err)
}
switch fc := fullChat.(type) {
case *tg.ChannelFull:
    fmt.Printf("About: %s\n", fc.About)
case *tg.ChatFull:
    fmt.Printf("Participants: %d\n", len(fc.Participants.(*tg.ChatParticipants).Participants))
}

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID to get full information for

Returns full chat information or an error.

func GetFullUser

func GetFullUser(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, userID int64) (*tg.UserFull, error)

GetFullUser returns tg.UserFull of provided user ID.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • userID: The user ID to get full info for

Returns full user information or an error.

func GetInputFileLocation

func GetInputFileLocation(media tg.MessageMediaClass) (tg.InputFileLocationClass, error)

GetInputFileLocation returns tg.InputFileLocationClass, which can be used to download media.

Parameters:

  • media: The media object to get location for

Returns input file location or an error.

func GetInputPeerClassFromID

func GetInputPeerClassFromID(p *storage.PeerStorage, id int64) tg.InputPeerClass

GetInputPeerClassFromID finds provided user id in session storage and returns it if found.

Parameters:

  • p: Peer storage to search in
  • iD: The user/chat ID to look up

Returns input peer class or nil if not found.

func GetMediaFileName

func GetMediaFileName(media tg.MessageMediaClass) (string, error)

GetMediaFileName returns media's filename in format "{name}.{extension}".

Parameters:

  • media: The media object to get filename from

Returns filename or an error.

func GetMediaFileNameWithID

func GetMediaFileNameWithID(media tg.MessageMediaClass) (string, error)

GetMediaFileNameWithID returns media's filename in format "{id}-{name}.{extension}".

Parameters:

  • media: The media object to get filename from

Returns formatted filename or an error.

func GetMessageFromMessageClass

func GetMessageFromMessageClass(m tg.MessageClass) *tg.Message

GetMessageFromMessageClass extracts message from message class.

Parameters:

  • m: The message class to extract from

Returns the message or nil.

func GetMessages

func GetMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, messageIDs []tg.InputMessageClass) (tg.MessageClassArray, error)

GetMessages fetches messages from a chat by their IDs.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID to fetch messages from
  • messageIDs: List of message IDs to fetch

Returns list of messages or an error.

func GetNewMessageUpdate

func GetNewMessageUpdate(msgData *tg.Message, upds tg.UpdatesClass, p *storage.PeerStorage) *tg.Message

GetNewMessageUpdate extracts the new message from updates.

Parameters:

  • msgData: The message data to populate
  • upds: The updates class to extract from
  • p: Peer storage for resolving peer references

Returns the new message or nil.

func GetOpt

func GetOpt[T comparable](opts ...T) (T, bool)

GetOpt returns the first option from a variadic parameter list along with a boolean indicating validity.

This function handles optional parameters in a variadic way, following Go idioms:

  • Returns (value, true) if a valid option is provided
  • Returns (zero, false) if no option or invalid option (zero value or nil pointer) is provided
  • Panics if more than one option is provided (misuse prevention)

Valid option means:

  • Not the zero value for the type T
  • Not a nil pointer (when T is a pointer type)

Type parameter T must be comparable (supports == and != operators).

Parameters:

  • opts: Variadic options (0 or 1 expected, panics on >1)

Returns:

  • T: The option value if valid, otherwise zero value
  • bool: True if option is valid, false otherwise

Example:

timeout, ok := GetOpt[time.Duration](opts...)
if ok {
    // use timeout
} else {
    // use default timeout
}

Example with pointer type:

cfg, ok := GetOpt[*Config](opts...)
if ok {
    // use cfg (non-nil)
} else {
    // use default config
}

func GetOptDef

func GetOptDef[T comparable](def T, opts ...T) T

GetOptDef returns the first option from a variadic parameter list, or the default value if none provided.

This function is a convenience wrapper around GetOpt for cases where you always want a value. It returns the default value when:

  • No option is provided
  • The provided option is invalid (zero value or nil pointer)

Type parameter T must be comparable (supports == and != operators).

Parameters:

  • def: Default value to return if no valid option is provided
  • opts: Variadic options (0 or 1 expected, panics on >1)

Returns:

  • T: The option value if valid, otherwise the default value

Example:

// With default
timeout := GetOptDef(30*time.Second, opts...)

// With explicit option
opts := []time.Duration{60 * time.Second}
timeout := GetOptDef(30*time.Second, opts...) // returns 60s

// With zero value (uses default)
opts := []time.Duration{0}
timeout := GetOptDef(30*time.Second, opts...) // returns 30s

func GetPeerStories

func GetPeerStories(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64) (*tg.StoriesPeerStories, error)

GetPeerStories fetches all active stories for a given peer.

This wraps the raw stories.getPeerStories MTProto method, resolving the peer from storage if needed.

Example:

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

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat/user ID whose stories to fetch

Returns StoriesPeerStories containing the stories, or an error.

func GetPeerStoriesByInputPeer

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

GetPeerStoriesByInputPeer fetches all active stories for a given input peer directly.

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

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peer: The resolved input peer

Returns StoriesPeerStories containing the stories, or an error.

func GetResaleStarGifts

GetResaleStarGifts retrieves the list of resale star gifts.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • req: The request parameters (sort, filter, pagination)

Returns the resale star gifts response or an error.

func GetStarGifts

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

GetStarGifts retrieves the list of available star gifts.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • hash: Hash for caching (pass 0 to always fetch fresh)

Returns the star gifts response or an error.

func GetStoriesByID

func GetStoriesByID(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, ids []int) (*tg.StoriesStories, error)

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

This wraps the raw stories.getStoriesByID MTProto method, resolving the peer from storage if needed.

Example:

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

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • 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 GetStoriesByIDWithInputPeer

func GetStoriesByIDWithInputPeer(ctx context.Context, raw *tg.Client, 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).

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peer: The resolved input peer
  • ids: The story IDs to fetch

Returns StoriesStories containing the requested stories, or an error.

func GetUpdateClassFromUpdatesClass

func GetUpdateClassFromUpdatesClass(updates tg.UpdatesClass, p *storage.PeerStorage) (u []tg.UpdateClass)

GetUpdateClassFromUpdatesClass extracts update classes from updates.

Parameters:

  • updates: The updates class to extract from
  • p: Peer storage for resolving peer references

Returns list of update classes.

func GetUser

func GetUser(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, userID int64) (*tg.User, error)

GetUser returns tg.User of provided user ID.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • userID: The user ID to get info for

Returns user information or an error.

func GetUserProfilePhotos

func GetUserProfilePhotos(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, userID int64, opts *tg.PhotosGetUserPhotosRequest) ([]tg.PhotoClass, error)

GetUserProfilePhotos fetches photos from a user's profile.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • userID: The user ID to get photos from
  • opts: Optional parameters for photos request

Returns list of photos or an error.

func LeaveChannel

func LeaveChannel(ctx context.Context, client *tg.Client, chatPeer tg.InputPeerClass) (tg.UpdatesClass, error)

LeaveChannel leaves the current user from a channel or chat.

Example:

success, err := functions.LeaveChannel(ctx, client.Raw, chatPeer)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for API call
  • client: The raw Telegram client
  • chatPeer: The channel/chat peer to leave from

Returns true if successful, or an error.

func PinMessage

func PinMessage(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, messageID int) (tg.UpdatesClass, error)

PinMessage pins a message in a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID containing the message
  • messageID: The message ID to pin

Returns updates confirming the action or an error.

func PromoteChatMember

func PromoteChatMember(ctx context.Context, client *tg.Client, chat, user *storage.Peer, rights tg.ChatAdminRights, title string) (bool, error)

PromoteChatMember promotes a user to admin in a chat.

Example:

rights := tg.ChatAdminRights{
    ChangeInfo:     true,
    BanUsers:       true,
    DeleteMessages: true,
    PinMessages:    true,
}
success, err := functions.PromoteChatMember(ctx, client.Raw, chatPeer, userPeer, rights, "Moderator")
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • chat: The chat peer storage
  • user: The user peer storage to promote
  • rights: Admin rights to grant
  • title: Custom admin rank/title

Returns true if successful, or an error.

func ResolveInputPeerByID

func ResolveInputPeerByID(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, id int64) (tg.InputPeerClass, error)

ResolveInputPeerByID tries to resolve given id to InputPeer.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • id: The peer ID to resolve

Returns input peer class or error if peer could not be resolved.

func ReturnEditMessageWithError

func ReturnEditMessageWithError(p *storage.PeerStorage, upds tg.UpdatesClass, err error) (*tg.Message, error)

ReturnEditMessageWithError returns edited message with error handling.

Internal helper function.

Parameters:

  • p: Peer storage for resolving peer references
  • upds: The updates class to extract from
  • err: The error to check

Returns the edited message or error.

func ReturnNewMessageWithError

func ReturnNewMessageWithError(msgData *tg.Message, upds tg.UpdatesClass, p *storage.PeerStorage, err error) (*tg.Message, error)

ReturnNewMessageWithError returns new message with error handling.

Internal helper function.

Parameters:

  • msgData: The message data to populate
  • upds: The updates class to extract from
  • p: Peer storage for resolving peer references
  • err: The error to check

Returns the new message or error.

func RevokeAllOtherSessions

func RevokeAllOtherSessions(ctx context.Context, raw *tg.Client) error

RevokeAllOtherSessions terminates all other active sessions except the current one.

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

func RevokeSession

func RevokeSession(ctx context.Context, raw *tg.Client, hash int64) error

RevokeSession terminates an active authorized session by its hash.

The session hash can be obtained from GetActiveSessions. Cannot revoke the current session — use auth.logOut for that.

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

func SavePeersFromClassArray

func SavePeersFromClassArray(p *storage.PeerStorage, cs []tg.ChatClass, us []tg.UserClass)

SavePeersFromClassArray saves chat and user peers from a class array to storage.

Parameters:

  • p: Peer storage to save to
  • cs: List of chat classes to save
  • us: List of user classes to save

Returns nothing.

func SendMedia

func SendMedia(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, chatID int64, request *tg.MessagesSendMediaRequest, businessConnectionID ...string) (*tg.Message, error)

SendMedia sends a media message to a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • chatID: The chat ID to send media to
  • request: The media send request parameters

Returns the sent message or an error.

func SendMessage

func SendMessage(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, chatID int64, request *tg.MessagesSendMessageRequest, businessConnectionID ...string) (*tg.Message, error)

SendMessage sends a text message to a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • chatID: The chat ID to send message to
  • request: The message send request parameters

Returns the sent message or an error.

func SendMultiMedia

func SendMultiMedia(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, chatID int64, request *tg.MessagesSendMultiMediaRequest, businessConnectionID ...string) (*tg.Message, error)

SendMultiMedia sends multiple media items (album) to a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • chatID: The chat ID to send album to
  • request: The multi-media send request parameters

Returns the sent message or an error.

func SendReaction

func SendReaction(ctx context.Context, raw *tg.Client, peerStorage *storage.PeerStorage, chatID int64, request *tg.MessagesSendReactionRequest) (*tg.Message, error)

SendReaction sends a reaction to a message.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • peerStorage: Peer storage for resolving peer references
  • chatID: The chat ID containing the message
  • request: The reaction send request parameters

Returns the updated message or an error.

func SetPreCheckoutResults

func SetPreCheckoutResults(ctx context.Context, raw *tg.Client, success bool, queryID int64, errMsg string) (bool, error)

SetPreCheckoutResults sets pre-checkout query results for a bot.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • success: Whether to checkout succeeded
  • queryID: The pre-checkout query ID
  • errMsg: Optional error message

Returns true if successful, or an error.

func TransferStarGift

func TransferStarGift(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, starGift tg.InputSavedStarGiftClass) (tg.UpdatesClass, error)

TransferStarGift transfers a star gift to a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID to send gift to
  • starGift: The star gift to transfer

Returns updates confirming the action or an error.

func UnPinAllMessages

func UnPinAllMessages(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64) error

UnPinAllMessages unpins all messages in a chat.

func UnPinMessage

func UnPinMessage(ctx context.Context, raw *tg.Client, p *storage.PeerStorage, chatID int64, messageID int) error

UnPinMessage unpins a specific message in a chat.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • p: Peer storage for resolving peer references
  • chatID: The chat ID containing the message
  • messageID: The message ID to unpin

Returns an error if the operation fails.

func UnarchiveChats

func UnarchiveChats(ctx context.Context, client *tg.Client, peers []tg.InputPeerClass) (bool, error)

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

Example:

peers := []tg.InputPeerClass{chatPeer1, chatPeer2}
success, err := functions.UnarchiveChats(ctx, client.Raw, peers)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • peers: List of peers to unarchive

Returns true if successful, or an error.

func UnbanChatMember

func UnbanChatMember(ctx context.Context, client *tg.Client, chatPeer *tg.InputPeerChannel, userPeer *tg.InputPeerUser) (bool, error)

UnbanChatMember unbans a previously banned user from a channel.

Example:

channelPeer := &tg.InputPeerChannel{ChannelID: 12345678, AccessHash: 1234567890}
userPeer := &tg.InputPeerUser{UserID: 87654321, AccessHash: 9876543210}
success, err := functions.UnbanChatMember(ctx, client.Raw, channelPeer, userPeer)
if err != nil {
    log.Fatal(err)
}

Parameters:

  • ctx: Context for the API call
  • client: The raw Telegram client
  • chatPeer: The channel peer to unban user from
  • userPeer: The user peer to unban

Returns true if successful, or an error.

func Update2FA

func Update2FA(ctx context.Context, raw *tg.Client, currentPassword, newPassword string, opts *PasswordOpts) error

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

The current password is required for verification via SRP.

Parameters:

  • ctx: Context for the API call
  • raw: The raw Telegram client
  • currentPassword: The current 2FA password for verification
  • newPassword: The new 2FA password to set
  • opts: Optional hint and recovery email (can be nil)

Returns an error if 2FA is not enabled or the operation fails.

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

Types

type ChatMembersFilter

type ChatMembersFilter int

ChatMembersFilter specifies which types of members to return from GetChatMembers.

const (
	// FilterSearch returns members matching a search query (default).
	FilterSearch ChatMembersFilter = iota
	// FilterRecent returns recently active members.
	FilterRecent
	// FilterAdmins returns only administrators.
	FilterAdmins
	// FilterBots returns only bots.
	FilterBots
	// FilterKicked returns only kicked (banned) members.
	FilterKicked
	// FilterBanned returns only restricted members.
	FilterBanned
	// FilterContacts returns only contacts.
	FilterContacts
)

type Dumpable

type Dumpable interface {
	DumpValue() any
}

Dumpable allows types to control what gets serialized by Dump.

type GetChatMembersOpts

type GetChatMembersOpts struct {
	// Query filters members by display name or username.
	// Only applicable to FilterSearch, FilterKicked, and FilterBanned.
	Query string

	// Limit is the maximum number of members to return.
	// Defaults to 200. Maximum per-request is 200.
	Limit int

	// Filter selects which type of members to retrieve.
	// Defaults to FilterSearch.
	Filter ChatMembersFilter
}

GetChatMembersOpts holds optional parameters for GetChatMembers.

type PasswordOpts

type PasswordOpts struct {
	// Hint is a text hint for the password, shown when the user
	// is asked to enter it during login.
	Hint string
	// Email is the recovery email address associated with the 2FA password.
	// Telegram will send a confirmation code to this email.
	Email string
}

PasswordOpts holds optional parameters for 2FA password operations.

Jump to

Keyboard shortcuts

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