Documentation
¶
Index ¶
- Constants
- Variables
- func ReadAuthLine(in *os.File, hide bool) (string, error)
- func ResolveAllowedSendPath(path string, roots ...string) (string, error)
- type Animation
- type Audio
- type AuthState
- type AuthStateCallback
- type AuthStateMsg
- type BasicGroupFullInfo
- type Chat
- type ChatAction
- type ChatActionCancel
- type ChatActionMsg
- type ChatActionTyping
- type ChatFolder
- type ChatFoldersMsg
- type ChatLastMessageMsg
- type ChatMember
- type ChatMemberStatus
- type ChatMemberStatusAdministrator
- type ChatMemberStatusBanned
- type ChatMemberStatusCreator
- type ChatMemberStatusLeft
- type ChatMemberStatusMember
- type ChatMemberStatusRestricted
- type ChatMuteChangedMsg
- type ChatReadInboxMsg
- type ChatReadOutboxMsg
- type ChatType
- type ChatUpdateMsg
- type Client
- func (c *Client) Close() error
- func (c *Client) CloseContext(ctx context.Context) error
- func (c *Client) CreatePrivateChat(userID int64) (*Chat, error)
- func (c *Client) DataDir() string
- func (c *Client) DeleteMessages(chatID int64, messageIDs []int64, revoke bool) error
- func (c *Client) DeviceCount() (int, error)
- func (c *Client) DiscussionMessage(chatID, messageID int64) (int64, int64, error)
- func (c *Client) DownloadFileSync(key string) (*File, error)
- func (c *Client) EditTextMessage(chatID int64, messageID int64, text string) (*Message, error)
- func (c *Client) FilesDir() string
- func (c *Client) GetBasicGroupFullInfo(chatID int64) (*BasicGroupFullInfo, error)
- func (c *Client) GetChat(chatID int64) (*Chat, error)
- func (c *Client) GetChatFolders() ([]*ChatFolder, error)
- func (c *Client) GetChatHistory(chatID, fromMessageID int64, offset, limit int32) ([]*Message, error)
- func (c *Client) GetContacts() ([]*User, error)
- func (c *Client) GetMe() (*User, error)
- func (c *Client) GetMessage(chatID, messageID int64) (*Message, error)
- func (c *Client) GetSupergroupFullInfo(chatID int64) (*SupergroupFullInfo, error)
- func (c *Client) GetSupergroupMembers(chatID int64, offset, limit int32) ([]*ChatMember, error)
- func (c *Client) GetUser(userID int64) (*User, error)
- func (c *Client) IsReady() bool
- func (c *Client) ListChats(limit int) ([]*Chat, error)
- func (c *Client) LoadChats(limit int) error
- func (c *Client) LoadFolderDialogs(folder *ChatFolder, already map[int64]struct{}) ([]*Chat, error)
- func (c *Client) LoadMoreChats(limit int) (int, error)
- func (c *Client) MoreChatsToLoad() bool
- func (c *Client) OpenChat(chatID int64) error
- func (c *Client) SearchChatMedia(chatID int64, filter MediaFilter, limit int32) ([]*Message, error)
- func (c *Client) SearchChatMessages(chatID int64, query string, fromMessageID int64, limit int32) ([]*Message, error)
- func (c *Client) SearchChats(query string, limit int32) ([]*Chat, error)
- func (c *Client) SearchMessages(query string, limit int32) ([]*Message, error)
- func (c *Client) SendFileMessage(chatID int64, path, caption string, replyToMessageID int64) (*Message, error)
- func (c *Client) SendPhotoMessage(chatID int64, path, caption string, replyToMessageID int64) (*Message, error)
- func (c *Client) SendTextMessage(chatID int64, text string, replyToMessageID int64) (*Message, error)
- func (c *Client) SetPinned(chatID, messageID int64, pinned bool) error
- func (c *Client) SetReaction(chatID, messageID int64, emoji string) error
- func (c *Client) Start() error
- func (c *Client) ViewMessages(chatID int64, messageIDs []int64) error
- func (c *Client) WaitReady()
- type ClientErrorMsg
- type ClientWarningMsg
- type Comments
- type ConnectionState
- type ConnectionStateMsg
- type Contact
- type Document
- type File
- type FileUpdateMsg
- type FormattedText
- type Listener
- type Location
- type MediaFilter
- type Message
- type MessageAnimation
- type MessageAudio
- type MessageChatAddMembers
- type MessageChatChangePhoto
- type MessageChatChangeTitle
- type MessageChatDeleteMember
- type MessageChatJoinByLink
- type MessageContact
- type MessageContent
- type MessageDeletedMsg
- type MessageDocument
- type MessageEditedMsg
- type MessageLocation
- type MessagePhoto
- type MessagePinMessage
- type MessagePoll
- type MessageSendFailedMsg
- type MessageSendSucceededMsg
- type MessageSender
- type MessageSenderChat
- type MessageSenderUser
- type MessageSticker
- type MessageText
- type MessageUnsupported
- type MessageVideo
- type MessageVideoNote
- type MessageVoiceNote
- type NewMessageMsg
- type Photo
- type PhotoSize
- type Poll
- type PollOption
- type QRLoginOptions
- type QRLoginToken
- type Reaction
- type Sticker
- type SupergroupFullInfo
- type TUIAuthorizer
- func (a *TUIAuthorizer) AcceptTermsOfService(ctx context.Context, _ tg.HelpTermsOfService) error
- func (a *TUIAuthorizer) Close()
- func (a *TUIAuthorizer) Code(ctx context.Context, _ *tg.AuthSentCode) (string, error)
- func (a *TUIAuthorizer) Password(ctx context.Context) (string, error)
- func (a *TUIAuthorizer) Phone(ctx context.Context) (string, error)
- func (a *TUIAuthorizer) SetErrorCallback(cb func(error))
- func (a *TUIAuthorizer) SetStateCallback(cb AuthStateCallback)
- func (a *TUIAuthorizer) SignUp(ctx context.Context) (auth.UserInfo, error)
- func (a *TUIAuthorizer) SubmitCode(code string)
- func (a *TUIAuthorizer) SubmitPassword(password string)
- func (a *TUIAuthorizer) SubmitPhone(phone string)
- type TextEntity
- type TextEntityType
- type TextEntityTypeBlockQuote
- type TextEntityTypeBold
- type TextEntityTypeBotCommand
- type TextEntityTypeCode
- type TextEntityTypeEmailAddress
- type TextEntityTypeHashtag
- type TextEntityTypeItalic
- type TextEntityTypeMention
- type TextEntityTypeMentionName
- type TextEntityTypePre
- type TextEntityTypePreCode
- type TextEntityTypeSpoiler
- type TextEntityTypeStrikethrough
- type TextEntityTypeTextURL
- type TextEntityTypeURL
- type TextEntityTypeUnderline
- type User
- type UserStatus
- type UserStatusEmpty
- type UserStatusLastMonth
- type UserStatusLastWeek
- type UserStatusOffline
- type UserStatusOnline
- type UserStatusRecently
- type Video
- type VideoNote
- type VoiceNote
- type WebPage
Constants ¶
const AllChatsFolderID int32 = 0
AllChatsFolderID is the ID Telegram reserves for the implicit "All chats" folder. The server only ever names it explicitly via dialogFilterDefault; otherwise the UI is expected to synthesize it.
const MaxDialogsLimit = 500
MaxDialogsLimit caps ListChats so a bad limit cannot walk the whole dialog list. The TUI first paint only loads one recency page; folder membership comes from include/pin peers, not from this cap.
Variables ¶
var ( ErrClientStarted = errors.New("telegram client already started") ErrClientClosed = errors.New("telegram client already closed") )
var ErrLoginRequired = errors.New("login required: run 'telegram-mcp login' first")
ErrLoginRequired is returned by the authorizer in non-interactive mode when the session is not authorized yet.
var ErrQRPasswordPromptRequired = errors.New("QR login requires a 2FA password prompt")
ErrQRPasswordPromptRequired is returned when QR login reaches 2FA but no password prompt was configured.
Functions ¶
func ReadAuthLine ¶
ReadAuthLine reads one line from in. When hide is true and in is a terminal, the input is not echoed (for 2FA passwords). Piped input always falls back to a normal line read so tests and scripted logins still work.
func ResolveAllowedSendPath ¶
ResolveAllowedSendPath returns the absolute, symlink-resolved form of path if it exists and is the same as, or inside, one of roots. Empty roots are ignored. The file itself must exist (a dangling last component is rejected) so a symlink cannot later be swapped for a path outside the jail.
Types ¶
type AuthStateCallback ¶
AuthStateCallback is called when the auth state changes. Used to notify the TUI about state transitions.
type AuthStateMsg ¶
type AuthStateMsg struct {
State AuthState
}
AuthStateMsg carries authorization state changes.
type BasicGroupFullInfo ¶
type BasicGroupFullInfo struct {
Description string
MemberCount int32
Members []*ChatMember
}
BasicGroupFullInfo holds full info about a basic group.
type Chat ¶
type Chat struct {
ID int64
Type ChatType
Title string
Username string
// Photo is the small avatar file; ID is a file registry key.
Photo *File
LastMessage *Message
UnreadCount int32
LastReadInboxMessageID int64
LastReadOutboxMessageID int64
// Pinned and Order define chat list ordering: pinned first,
// then by Order descending (unix time of the last message).
Pinned bool
Order int64
// Muted mirrors the peer's notification settings: an explicit
// silent flag or a mute-until date in the future.
Muted bool
}
Chat is the domain representation of a Telegram dialog.
type ChatAction ¶
type ChatAction interface {
// contains filtered or unexported methods
}
ChatAction is a user activity in a chat (typing etc).
type ChatActionCancel ¶
type ChatActionCancel struct{}
ChatActionCancel means the user stopped the action.
type ChatActionMsg ¶
type ChatActionMsg struct {
ChatId int64
UserId int64
Action ChatAction
}
ChatActionMsg is sent when someone is typing or performing an action.
type ChatActionTyping ¶
type ChatActionTyping struct{}
ChatActionTyping means the user is typing (or recording/uploading).
type ChatFolder ¶
type ChatFolder struct {
ID int32
Title string
Emoticon string
PinnedChatIDs []int64
IncludedChatIDs []int64
ExcludedChatIDs []int64
// Category flags. Only plain folders (dialogFilter) carry these;
// shared chatlist folders leave them false.
Contacts bool
NonContacts bool
Groups bool
Channels bool
Bots bool
ExcludeMuted bool
ExcludeRead bool
ExcludeArchived bool
// contains filtered or unexported fields
}
ChatFolder is the domain representation of a Telegram folder (a "dialog filter" in the MTProto schema).
Chat IDs are canonical TDLib-style IDs, the same namespace as Chat.ID.
func (*ChatFolder) NeedsPeerFetch ¶
func (f *ChatFolder) NeedsPeerFetch() bool
NeedsPeerFetch reports whether this folder has explicit include/pin peers. The folder list is those peers (plus any type-flag matches already in the recency cache), not a slice of getDialogs.
type ChatFoldersMsg ¶
type ChatFoldersMsg struct {
Folders []*ChatFolder
}
ChatFoldersMsg carries the current chat folder list, in server order.
type ChatLastMessageMsg ¶
ChatLastMessageMsg is sent when a chat's last message changes.
type ChatMember ¶
type ChatMember struct {
MemberID MessageSender
Status ChatMemberStatus
}
ChatMember is a member of a group or channel.
type ChatMemberStatus ¶
type ChatMemberStatus interface {
// contains filtered or unexported methods
}
ChatMemberStatus is the role of a chat member.
type ChatMemberStatusAdministrator ¶
type ChatMemberStatusAdministrator struct {
CustomTitle string
}
type ChatMemberStatusBanned ¶
type ChatMemberStatusBanned struct{}
type ChatMemberStatusCreator ¶
type ChatMemberStatusCreator struct {
CustomTitle string
}
type ChatMemberStatusLeft ¶
type ChatMemberStatusLeft struct{}
type ChatMemberStatusMember ¶
type ChatMemberStatusMember struct{}
type ChatMemberStatusRestricted ¶
type ChatMemberStatusRestricted struct{}
type ChatMuteChangedMsg ¶
ChatMuteChangedMsg is sent when a chat's notification settings change.
type ChatReadInboxMsg ¶
ChatReadInboxMsg is sent when the read inbox state changes.
type ChatReadOutboxMsg ¶
ChatReadOutboxMsg is sent when the read outbox state changes.
type ChatUpdateMsg ¶
type ChatUpdateMsg struct {
Chat *Chat
// FromPeer says this chat was built by resolving a PEER rather than by
// reading a dialog, and so is a partial view: it knows who the chat is
// and whether it is muted, and nothing about unread counts, pinning or
// the last message.
//
// The store has to be told, because it cannot tell from the value: a
// chat that is not pinned and a chat whose pin nobody asked about are
// the same struct. Storing one of these as though it were complete is
// what unmuted every chat the reader opened.
FromPeer bool
}
ChatUpdateMsg is sent when chat metadata changes (title, photo, etc) or when a chat is loaded from the dialog list.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client wraps a gotd telegram client with the app-facing API.
func NewClient ¶
func NewClient(cfg *config.Config, authorizer *TUIAuthorizer) *Client
NewClient constructs an update-receiving client without starting it. Register callbacks and update handlers before calling Start.
func NewClientAsync ¶
func NewClientAsync(cfg *config.Config, authorizer *TUIAuthorizer) *Client
NewClientAsync is retained for callers that have nothing to register before startup. Interactive frontends should use NewClient and Start explicitly.
func NewRPCClient ¶
func NewRPCClient(cfg *config.Config, authorizer *TUIAuthorizer) *Client
NewRPCClient constructs an RPC-only client without starting it. no-updates mode: the connection never subscribes to the update stream, so it does not compete with the TUI (or other processes sharing the same session) for realtime updates. Used by telegram-mcp serve.
func NewRPCClientAsync ¶
func NewRPCClientAsync(cfg *config.Config, authorizer *TUIAuthorizer) *Client
NewRPCClientAsync is the compatibility form of NewRPCClient.
func (*Client) Close ¶
Close shuts the client down and waits for its run loop and state-store cleanup to finish, up to a short process-shutdown bound.
func (*Client) CloseContext ¶
CloseContext is Close with a caller-provided shutdown bound.
func (*Client) CreatePrivateChat ¶
CreatePrivateChat returns a (synthetic) private chat entry for a user. No RPC is needed beyond resolving the user — the real chat is created server-side when the first message is sent.
func (*Client) DeleteMessages ¶
DeleteMessages deletes messages from a chat.
revoke asks Telegram to delete the messages for everyone rather than only for the current user. It is IGNORED for channels and supergroups: channels.deleteMessages has no such flag because channel deletions are always for everyone.
On success the deletion is published immediately so the UI does not wait for the server echo. The server sends its own update shortly after; the message store deletes by filtering on an ID set, so applying the same deletion twice is a no-op.
func (*Client) DeviceCount ¶
DeviceCount is how many sessions are currently authorised on this account, this one included.
It is the number Telegram's own clients show under "Devices", and it is worth a cell in the top bar for the reason Telegram gives it a screen: a count higher than the user expects is how an unauthorised login is noticed. A constant would not be worth the space; this varies, and when it varies it means something.
One RPC, no paging: account.getAuthorizations returns the whole list. The caller fetches it when the connection becomes ready and holds the answer — sessions are created and revoked by hand, on the scale of days, so polling for it would spend requests to watch a number that does not move.
The count is 0 on every error, which is not merely the zero value: 0 is also what "not asked yet" looks like to the only consumer, and both mean the top bar draws no device cell. A caller that wants to tell them apart has the error; a caller that does not can ignore it safely.
func (*Client) DiscussionMessage ¶
DiscussionMessage finds where a channel post's comments live: the chat and the message inside it that the comments hang off.
A post's comments are not in the channel. Telegram copies the post into the linked group and the comments are replies to that copy, so opening them means opening a different chat at a message whose id this client has never seen. This is the only call that knows the translation.
The linked group is announced as a side effect, the same way CreatePrivateChat announces a chat it resolved: the caller is about to open it, and a chat opening with no name is a chat that looks broken for as long as the resolve takes.
Announced through GetChat rather than off the Chats the response already carries. Those are peers, and a chat built from a peer carries Muted=false — which the store would merge over a group the reader had muted on purpose. That is divergence 39 exactly, and the AST guard beside it refused the shortcut when this was first written that way.
func (*Client) DownloadFileSync ¶
DownloadFileSync downloads a registered file to the files dir and returns its local state. Concurrent calls for the same key share one in-flight download via the registry's singleflight group.
func (*Client) EditTextMessage ¶
EditTextMessage edits a text message.
func (*Client) GetBasicGroupFullInfo ¶
func (c *Client) GetBasicGroupFullInfo(chatID int64) (*BasicGroupFullInfo, error)
GetBasicGroupFullInfo returns full info (incl. members) for a basic group.
func (*Client) GetChat ¶
GetChat returns a single chat by canonical chat ID.
The mute flag comes from a second call, because resolving a peer does not report it: notify settings belong to the account's view of the peer, not to the peer. Without it a chat outside the loaded dialog page would look unmuted to everything downstream, and the first message from it would ring — which is the whole reason anybody looks at this function.
func (*Client) GetChatFolders ¶
func (c *Client) GetChatFolders() ([]*ChatFolder, error)
GetChatFolders returns the user's chat folders in server order.
func (*Client) GetChatHistory ¶
func (c *Client) GetChatHistory(chatID, fromMessageID int64, offset, limit int32) ([]*Message, error)
GetChatHistory returns messages of a chat, newest first. fromMessageID paginates backwards (offsetID); offset skips messages.
func (*Client) GetContacts ¶
GetContacts returns the contact list.
func (*Client) GetMessage ¶
GetMessage fetches a single message.
func (*Client) GetSupergroupFullInfo ¶
func (c *Client) GetSupergroupFullInfo(chatID int64) (*SupergroupFullInfo, error)
GetSupergroupFullInfo returns full info for a supergroup/channel chat.
func (*Client) GetSupergroupMembers ¶
func (c *Client) GetSupergroupMembers(chatID int64, offset, limit int32) ([]*ChatMember, error)
GetSupergroupMembers returns members of a supergroup/channel.
func (*Client) ListChats ¶
ListChats fetches the dialog list from the beginning without emitting any UI events. Telegram returns at most 100 dialogs per request, so larger limits are served by paginating until limit is reached or a short page arrives.
func (*Client) LoadChats ¶
LoadChats fetches the first page of the dialog list and pushes every chat to the UI as a ChatUpdateMsg (this replaces tdlib's updateNewChat flow).
It also arms the pager: whatever it stopped at is where [LoadMoreChats] carries on from, so the reader can reach dialogs older than the first page without the client fetching an account's entire history at startup.
func (*Client) LoadFolderDialogs ¶
func (c *Client) LoadFolderDialogs(folder *ChatFolder, already map[int64]struct{}) ([]*Chat, error)
LoadFolderDialogs fetches dialogs for a folder's include and pin lists. already skips peers whose chat IDs are already in the local store so switching tabs does not re-fetch. One RPC covers up to folderPeerChunk peers — a 30-chat folder is a single round trip, not a 500-dialog walk.
func (*Client) LoadMoreChats ¶ added in v0.0.9
LoadMoreChats fetches the next page after whatever has been loaded so far, pushing each chat to the UI. It reports how many arrived; zero means the list is exhausted and asking again will not change that.
func (*Client) MoreChatsToLoad ¶ added in v0.0.9
MoreChatsToLoad reports whether the dialog list has more to give. False once a short page has arrived, so the UI can stop asking rather than issuing a request per keystroke at the bottom of the list.
func (*Client) OpenChat ¶
OpenChat is a light-weight placeholder kept for API compatibility: gotd needs no open/close chat lifecycle. It emits the chat so the store has it even for chats outside the loaded dialogs.
func (*Client) SearchChatMedia ¶
SearchChatMedia returns a chat's messages of one kind, newest first.
This is the rail's data path. Unlike [SearchChatMessages] it takes no query — the filter IS the query, and MTProto answers a filter-only search with the whole server-side index for that kind. Requiring a query here would make "this chat's files" unaskable.
limit is capped rather than rejected: the rail shows a handful of rows, and a caller asking for more than a screenful of them has made an arithmetic mistake, not a request worth failing.
func (*Client) SearchChatMessages ¶
func (c *Client) SearchChatMessages(chatID int64, query string, fromMessageID int64, limit int32) ([]*Message, error)
SearchChatMessages searches messages within a single chat, newest first, like GetChatHistory.
fromMessageID is the pagination offset: 0 starts from the latest message, and paging back means passing the ID of the oldest message already seen. limit is clamped to 1..100 (0 or negative means 100, matching the sibling search and history methods).
One RPC covers every chat kind — messages.search takes the peer, so users, basic groups, supergroups and channels all route through c.inputPeer with no channel-specific variant.
An empty query returns an error rather than a guaranteed server-side SEARCH_QUERY_EMPTY round trip.
func (*Client) SearchChats ¶
SearchChats searches chat titles by query (server-side).
func (*Client) SearchMessages ¶
SearchMessages searches messages globally by query.
func (*Client) SendFileMessage ¶
func (c *Client) SendFileMessage(chatID int64, path, caption string, replyToMessageID int64) (*Message, error)
SendFileMessage uploads a local file and sends it as a document, optionally with a caption and as a reply.
func (*Client) SendPhotoMessage ¶
func (c *Client) SendPhotoMessage(chatID int64, path, caption string, replyToMessageID int64) (*Message, error)
SendPhotoMessage uploads a local image and sends it as a photo, so it renders inline in the chat rather than as a file attachment. Images above photoSizeLimit must be sent with SendFileMessage instead.
func (*Client) SendTextMessage ¶
func (c *Client) SendTextMessage(chatID int64, text string, replyToMessageID int64) (*Message, error)
SendTextMessage sends a plain text message, optionally as a reply.
func (*Client) SetPinned ¶
SetPinned pins a message, or unpins it.
Silent, always. Pinning normally posts a service message into the chat announcing it — "X pinned a message" — and a client whose pin key also writes a line into everybody's history is a key people learn not to press. The pin itself is what was asked for; the announcement is not.
func (*Client) SetReaction ¶
SetReaction puts your reaction on a message, or takes it off.
An empty emoji REMOVES. Telegram models a reaction the same way: the request carries a list, and an empty list means "none of them are mine any more" — there is no separate removal call, and inventing one here would be two names for one request.
One reaction at a time, which is what a non-premium account is allowed. The request would take several; sending several to an account that cannot have them fails the whole call, and failing at the far end of a round trip is a worse way to learn about a limit than not offering it.
func (*Client) Start ¶
Start begins authentication and update delivery after all callbacks and update handlers have been registered.
func (*Client) ViewMessages ¶
ViewMessages marks messages as read.
type ClientErrorMsg ¶
ClientErrorMsg reports that the Telegram client itself failed, as opposed to a single RPC. Terminal is true when the run loop has exited for good, meaning nothing will arrive until the app reconnects — the session being terminated from another device looks like this.
type ClientWarningMsg ¶
type ClientWarningMsg struct {
Text string
}
ClientWarningMsg reports a permanent, non-fatal degradation of the current run. The client keeps working, but with less than its usual capability, and the user may want to know why.
type Comments ¶
type Comments struct {
// Count is how many comments there are. Zero is a real answer: the
// discussion exists and nobody has used it yet.
Count int32
// ChatID is the linked discussion group, in this client's canonical
// form, or 0 when Telegram did not name it. Without it there is
// nowhere to go, so the row says how many there are and offers no key.
ChatID int64
// Unread is whether anything has been said since this account last
// looked.
Unread bool
}
Comments is the discussion a channel post has, in the group linked to the channel.
A channel is a broadcast: nobody can answer a post in the channel itself. A linked group is where the answers go, and a client that does not say so makes a channel look like a place where nothing can be said back — which is the opposite of what the post's author set up.
type ConnectionState ¶
type ConnectionState int
ConnectionState is the simplified network state.
const ( ConnectionStateConnecting ConnectionState = iota ConnectionStateReady // ConnectionStateDisconnected means the client run loop has exited: // the connection is gone for good and will not recover on its own. // Appended last on purpose — the existing values keep their numbers, // so consumers comparing against them are unaffected. ConnectionStateDisconnected )
type ConnectionStateMsg ¶
type ConnectionStateMsg struct {
State ConnectionState
}
ConnectionStateMsg is sent when the network connection state changes.
type File ¶
File is a downloadable/downloaded file. ID is a registry key (e.g. "doc:123", "photo:456:y", "avatar:-100123").
type FileUpdateMsg ¶
type FileUpdateMsg struct {
File *File
}
FileUpdateMsg is sent when a file download completes.
type FormattedText ¶
type FormattedText struct {
Text string
Entities []*TextEntity
}
FormattedText is text with formatting entities.
func PreviewMarkdown ¶
func PreviewMarkdown(text string) *FormattedText
PreviewMarkdown parses the outgoing markdown subset and returns the FormattedText that would go on the wire.
It is the same parseMarkdown the send path uses, converted through the same entity mapping — so a composer preview built on it cannot drift from what is actually sent. A preview with its own parser is a preview that is right until the day it is not.
type Listener ¶
type Listener struct {
// contains filtered or unexported fields
}
Listener converts Telegram updates into tea messages and forwards them to the bubbletea program.
func NewListener ¶
NewListener registers update handlers on the client's dispatcher. It must be called before Client.Start; gotd's dispatcher is not safe to mutate once update delivery begins.
type MediaFilter ¶
type MediaFilter int
MediaFilter selects which of a chat's messages a filtered search asks for.
These are Telegram's own server-side indexes, not a scan of loaded history: asking for a chat's pinned messages or its files is one request that returns them however far back they are. Deriving the same lists from the pages this client happens to have loaded would produce a recent-files sample and call it the chat's files.
const ( // MediaFilterPinned is every pinned message, newest first. MediaFilterPinned MediaFilter = iota // MediaFilterFiles is documents: anything sent as a file rather than // as an inline photo. MediaFilterFiles // MediaFilterPhotos is photos and videos. MediaFilterPhotos // MediaFilterLinks is messages containing a URL. MediaFilterLinks )
func (MediaFilter) String ¶
func (f MediaFilter) String() string
String names the filter for error messages and logs.
type Message ¶
type Message struct {
ID int64
ChatID int64
SenderID MessageSender
Date int32
EditDate int32
IsOutgoing bool
IsChannelPost bool
IsForwarded bool
// IsPinned is whether this message is one of the chat's pinned ones.
// It is what lets one key toggle: a pin key that cannot tell says
// "pinned" to something already pinned, and the reader has to open the
// rail to find out what it did.
IsPinned bool
ReplyToMessageID int64
Content MessageContent
// Reactions are the emoji tallies on this message, in the order
// Telegram ranks them. Nil when nobody has reacted.
Reactions []*Reaction
// Comments is the discussion thread under a channel post, nil for a
// post with no linked group and for every message that is not one.
Comments *Comments
}
Message is the domain representation of a Telegram message.
type MessageAnimation ¶
type MessageAnimation struct {
Animation *Animation
Caption *FormattedText
}
MessageAnimation is a GIF message.
type MessageAudio ¶
type MessageAudio struct {
Audio *Audio
Caption *FormattedText
}
MessageAudio is an audio (music) message.
type MessageChatAddMembers ¶
type MessageChatAddMembers struct{}
MessageChatAddMembers is a service message about added members.
type MessageChatChangePhoto ¶
type MessageChatChangePhoto struct{}
MessageChatChangePhoto is a service message about a photo change.
type MessageChatChangeTitle ¶
type MessageChatChangeTitle struct {
Title string
}
MessageChatChangeTitle is a service message about a title change.
type MessageChatDeleteMember ¶
type MessageChatDeleteMember struct{}
MessageChatDeleteMember is a service message about a removed member.
type MessageChatJoinByLink ¶
type MessageChatJoinByLink struct{}
MessageChatJoinByLink is a service message about joining via invite link.
type MessageContact ¶
type MessageContact struct {
Contact *Contact
}
MessageContact is a shared contact message.
type MessageContent ¶
type MessageContent interface {
// contains filtered or unexported methods
}
MessageContent is the payload of a message.
type MessageDeletedMsg ¶
MessageDeletedMsg is sent when messages are deleted. ChatId is 0 for non-channel deletions (the update carries no peer).
type MessageDocument ¶
type MessageDocument struct {
Document *Document
Caption *FormattedText
}
MessageDocument is a generic file message.
type MessageEditedMsg ¶
MessageEditedMsg is sent when a message is edited.
type MessageLocation ¶
type MessageLocation struct {
Location *Location
}
MessageLocation is a geo point message.
type MessagePhoto ¶
type MessagePhoto struct {
Photo *Photo
Caption *FormattedText
}
MessagePhoto is a photo message.
type MessagePinMessage ¶
type MessagePinMessage struct{}
MessagePinMessage is a service message about a pinned message.
type MessageSendFailedMsg ¶
type MessageSendFailedMsg struct {
Message *Message
OldMessageId int64
ErrorCode int32
ErrorMessage string
}
MessageSendFailedMsg is sent when a message fails to send.
type MessageSendSucceededMsg ¶
MessageSendSucceededMsg is sent when a message is successfully sent.
type MessageSender ¶
type MessageSender interface {
// contains filtered or unexported methods
}
MessageSender identifies who sent a message.
type MessageSenderChat ¶
type MessageSenderChat struct {
ChatID int64
}
MessageSenderChat is a message sent on behalf of a chat/channel.
type MessageSenderUser ¶
type MessageSenderUser struct {
UserID int64
}
MessageSenderUser is a message sent by a user.
type MessageSticker ¶
type MessageSticker struct {
Sticker *Sticker
}
MessageSticker is a sticker message.
type MessageText ¶
type MessageText struct {
Text *FormattedText
// WebPage is the link preview Telegram attached to the text, or nil.
// It hangs off the text rather than replacing it: the preview is a
// second reading of a link the sender already wrote out.
WebPage *WebPage
}
MessageText is a plain text message.
type MessageUnsupported ¶
type MessageUnsupported struct {
Type string
}
MessageUnsupported is anything we don't map explicitly.
type MessageVideo ¶
type MessageVideo struct {
Video *Video
Caption *FormattedText
}
MessageVideo is a video message.
type MessageVideoNote ¶
type MessageVideoNote struct {
VideoNote *VideoNote
}
MessageVideoNote is a round video message.
type MessageVoiceNote ¶
type MessageVoiceNote struct {
VoiceNote *VoiceNote
Caption *FormattedText
}
MessageVoiceNote is a voice message.
type NewMessageMsg ¶
type NewMessageMsg struct {
Message *Message
}
NewMessageMsg is sent when a new message arrives.
type Poll ¶
type Poll struct {
Question string
Options []*PollOption
// TotalVoterCount is how many people have voted, which is not the sum
// of the options: a multiple-choice poll counts one voter once and
// their answers several times.
TotalVoterCount int32
// ResultsKnown is whether the server sent per-option tallies at all.
// A poll that hides its results until it closes sends none, and its
// options must then be drawn without bars — an empty bar is a result,
// not the absence of one.
ResultsKnown bool
IsAnonymous bool
IsClosed bool
MultipleChoice bool
IsQuiz bool
// CloseDate is the unix time the poll closes, 0 when it has no
// scheduled end.
CloseDate int32
}
Poll is a poll: its question, its answers, and whatever tallies the server sent with them.
type PollOption ¶
type PollOption struct {
Text string
VoterCount int32
// Percent is this option's share of the vote, apportioned by largest
// remainder so that the options of a poll sum to exactly 100.
Percent int32
// Chosen is whether the local user picked this option. Correct is
// whether a quiz counts it as the right answer — set only once the
// user has answered, since that is when Telegram sends it.
Chosen bool
Correct bool
}
PollOption is one answer of a poll.
type QRLoginOptions ¶
type QRLoginOptions struct {
// ShowQRCode is called whenever Telegram issues or refreshes a QR token.
ShowQRCode func(context.Context, QRLoginToken) error
// PasswordPrompt is called if the account requires 2FA. retry is true
// after an empty or invalid password. The returned byte slice is consumed
// and wiped before the function returns.
PasswordPrompt func(ctx context.Context, retry bool) ([]byte, error)
}
QRLoginOptions supplies the interactive parts of QR authentication.
type QRLoginToken ¶
QRLoginToken is a short-lived Telegram login token to render as a QR code.
type Reaction ¶
type Reaction struct {
// Emoji is the reaction's emoticon, empty for a custom one.
Emoji string
// CustomEmojiID identifies a custom emoji reaction, whose artwork is
// a document this client does not fetch; 0 for a standard reaction.
// A chip drawn from it says a reaction exists and admits it cannot
// show which, rather than substituting an emoji nobody sent.
CustomEmojiID int64
Count int32
// Chosen is whether the local user is one of the reactors. Telegram
// omits it from the copies of a message it sends to everyone (the
// "min" form), so a false here can mean "not known".
Chosen bool
}
Reaction is one emoji's tally on a message.
type SupergroupFullInfo ¶
SupergroupFullInfo holds full info about a supergroup or channel.
type TUIAuthorizer ¶
type TUIAuthorizer struct {
// NonInteractive makes Phone/Code/Password fail immediately with
// ErrLoginRequired instead of waiting for user input (headless mode).
NonInteractive bool
// contains filtered or unexported fields
}
TUIAuthorizer implements gotd's auth.UserAuthenticator on top of the channel-based flow used by the TUI.
func NewTUIAuthorizer ¶
func NewTUIAuthorizer(cfg *config.Config) *TUIAuthorizer
func (*TUIAuthorizer) AcceptTermsOfService ¶
func (a *TUIAuthorizer) AcceptTermsOfService(ctx context.Context, _ tg.HelpTermsOfService) error
AcceptTermsOfService implements auth.UserAuthenticator.
func (*TUIAuthorizer) Close ¶
func (a *TUIAuthorizer) Close()
func (*TUIAuthorizer) Code ¶
func (a *TUIAuthorizer) Code(ctx context.Context, _ *tg.AuthSentCode) (string, error)
Code implements auth.CodeAuthenticator.
func (*TUIAuthorizer) Password ¶
func (a *TUIAuthorizer) Password(ctx context.Context) (string, error)
Password implements auth.UserAuthenticator. The 2FA hint is fetched via account.getPassword through hintFunc, which the client wires up before the auth flow starts.
func (*TUIAuthorizer) Phone ¶
func (a *TUIAuthorizer) Phone(ctx context.Context) (string, error)
Phone implements auth.UserAuthenticator. The config-provided phone is consumed once: if the flow fails and retries, the TUI is asked instead of reusing a possibly wrong number.
func (*TUIAuthorizer) SetErrorCallback ¶
func (a *TUIAuthorizer) SetErrorCallback(cb func(error))
SetErrorCallback sets the callback for fatal auth errors (shown in the TUI).
func (*TUIAuthorizer) SetStateCallback ¶
func (a *TUIAuthorizer) SetStateCallback(cb AuthStateCallback)
SetStateCallback sets the callback for auth state changes.
func (*TUIAuthorizer) SubmitCode ¶
func (a *TUIAuthorizer) SubmitCode(code string)
func (*TUIAuthorizer) SubmitPassword ¶
func (a *TUIAuthorizer) SubmitPassword(password string)
func (*TUIAuthorizer) SubmitPhone ¶
func (a *TUIAuthorizer) SubmitPhone(phone string)
type TextEntity ¶
type TextEntity struct {
Offset int32
Length int32
Type TextEntityType
}
TextEntity is a formatting span. Offset and Length are RUNE indices into the owning FormattedText.Text, already converted from the UTF-16 code units Telegram sends — see formattedTextFromTG. Consumers may slice []rune with them directly.
type TextEntityType ¶
type TextEntityType interface {
// contains filtered or unexported methods
}
TextEntityType classifies a formatting span.
type TextEntityTypeBlockQuote ¶
type TextEntityTypeBlockQuote struct{}
type TextEntityTypeBold ¶
type TextEntityTypeBold struct{}
type TextEntityTypeBotCommand ¶
type TextEntityTypeBotCommand struct{}
type TextEntityTypeCode ¶
type TextEntityTypeCode struct{}
type TextEntityTypeEmailAddress ¶
type TextEntityTypeEmailAddress struct{}
type TextEntityTypeHashtag ¶
type TextEntityTypeHashtag struct{}
type TextEntityTypeItalic ¶
type TextEntityTypeItalic struct{}
type TextEntityTypeMention ¶
type TextEntityTypeMention struct{}
type TextEntityTypeMentionName ¶
type TextEntityTypeMentionName struct {
UserID int64
}
type TextEntityTypePre ¶
type TextEntityTypePre struct{}
type TextEntityTypePreCode ¶
type TextEntityTypePreCode struct {
Language string
}
type TextEntityTypeSpoiler ¶
type TextEntityTypeSpoiler struct{}
type TextEntityTypeStrikethrough ¶
type TextEntityTypeStrikethrough struct{}
type TextEntityTypeTextURL ¶
type TextEntityTypeTextURL struct {
URL string
}
type TextEntityTypeURL ¶
type TextEntityTypeURL struct{}
type TextEntityTypeUnderline ¶
type TextEntityTypeUnderline struct{}
type User ¶
type User struct {
ID int64
FirstName string
LastName string
Username string
PhoneNumber string
IsBot bool
Status UserStatus
}
User is the domain representation of a Telegram user.
func LoginWithQR ¶
LoginWithQR authorizes cfg.Storage.SessionFile by scanning a QR code in an already authorized Telegram app. Expired QR tokens are refreshed by gotd.
type UserStatus ¶
type UserStatus interface {
// contains filtered or unexported methods
}
UserStatus describes last-seen state.
type UserStatusEmpty ¶
type UserStatusEmpty struct{}
type UserStatusLastMonth ¶
type UserStatusLastMonth struct{}
type UserStatusLastWeek ¶
type UserStatusLastWeek struct{}
type UserStatusOffline ¶
type UserStatusOffline struct {
WasOnline int32
}
type UserStatusOnline ¶
type UserStatusOnline struct {
Expires int32
}
type UserStatusRecently ¶
type UserStatusRecently struct{}
type Video ¶
type Video struct {
FileName string
Duration int32
Width int
Height int
File *File
Thumbnail *File
}
Video is a video file.