telegram

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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.

View Source
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

This section is empty.

Types

type Animation

type Animation struct {
	FileName string
	Duration int32
	File     *File
}

Animation is a GIF file.

type Audio

type Audio struct {
	Title     string
	Performer string
	FileName  string
	Duration  int32
	File      *File
}

Audio is an audio file.

type AuthState

type AuthState int

AuthState is the authorization state reported to the TUI.

const (
	AuthStateWaitPhone AuthState = iota
	AuthStateWaitCode
	AuthStateWaitPassword
	AuthStateReady
	AuthStateClosed
)

type AuthStateCallback

type AuthStateCallback func(AuthState, string)

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
}

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 ChatLastMessageMsg

type ChatLastMessageMsg struct {
	ChatId      int64
	LastMessage *Message
}

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 ChatReadInboxMsg

type ChatReadInboxMsg struct {
	ChatId                 int64
	LastReadInboxMessageId int64
	UnreadCount            int32
}

ChatReadInboxMsg is sent when the read inbox state changes.

type ChatReadOutboxMsg

type ChatReadOutboxMsg struct {
	ChatId                  int64
	LastReadOutboxMessageId int64
}

ChatReadOutboxMsg is sent when the read outbox state changes.

type ChatType

type ChatType int

ChatType classifies a chat.

const (
	ChatTypePrivate ChatType = iota
	ChatTypeBasicGroup
	ChatTypeSupergroup
	ChatTypeChannel
)

type ChatUpdateMsg

type ChatUpdateMsg struct {
	Chat *Chat
}

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 NewClientAsync

func NewClientAsync(cfg *config.Config, authorizer *TUIAuthorizer) *Client

NewClientAsync starts the gotd client in the background. The client blocks on authorization — call this before starting the TUI so the auth UI can feed credentials via the authorizer channels.

func NewRPCClientAsync

func NewRPCClientAsync(cfg *config.Config, authorizer *TUIAuthorizer) *Client

NewRPCClientAsync is like NewClientAsync but runs the client in 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 (*Client) Close

func (c *Client) Close()

Close shuts the client down.

func (*Client) CreatePrivateChat

func (c *Client) CreatePrivateChat(userID int64) (*Chat, error)

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) DataDir

func (c *Client) DataDir() string

DataDir returns the root data directory.

func (*Client) DownloadFileSync

func (c *Client) DownloadFileSync(key string) (*File, error)

DownloadFileSync downloads a registered file to the files dir and returns its local state.

func (*Client) EditTextMessage

func (c *Client) EditTextMessage(chatID int64, messageID int64, text string) (*Message, error)

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

func (c *Client) GetChat(chatID int64) (*Chat, error)

GetChat returns a single chat by canonical chat ID.

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

func (c *Client) GetContacts() ([]*User, error)

GetContacts returns the contact list.

func (*Client) GetMe

func (c *Client) GetMe() (*User, error)

GetMe returns the authorized user.

func (*Client) GetMessage

func (c *Client) GetMessage(chatID, messageID int64) (*Message, error)

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) GetUser

func (c *Client) GetUser(userID int64) (*User, error)

GetUser returns a user by ID.

func (*Client) IsReady

func (c *Client) IsReady() bool

IsReady returns true if the client is authorized.

func (*Client) ListChats

func (c *Client) ListChats(limit int) ([]*Chat, error)

ListChats fetches the dialog list without emitting any UI events.

func (*Client) LoadChats

func (c *Client) LoadChats(limit int) error

LoadChats fetches the dialog list and pushes every chat to the UI as a ChatUpdateMsg (this replaces tdlib's updateNewChat flow).

func (*Client) OpenChat

func (c *Client) OpenChat(chatID int64) error

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) SearchChats

func (c *Client) SearchChats(query string, limit int32) ([]*Chat, error)

SearchChats searches chat titles by query (server-side).

func (*Client) SearchMessages

func (c *Client) SearchMessages(query string, limit int32) ([]*Message, error)

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) 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) ViewMessages

func (c *Client) ViewMessages(chatID int64, messageIDs []int64) error

ViewMessages marks messages as read.

func (*Client) WaitReady

func (c *Client) WaitReady()

WaitReady blocks until the client is authorized and ready.

type ConnectionState

type ConnectionState int

ConnectionState is the simplified network state.

const (
	ConnectionStateConnecting ConnectionState = iota
	ConnectionStateReady
)

type ConnectionStateMsg

type ConnectionStateMsg struct {
	State ConnectionState
}

ConnectionStateMsg is sent when the network connection state changes.

type Contact

type Contact struct {
	FirstName   string
	LastName    string
	PhoneNumber string
}

Contact is a shared contact.

type Document

type Document struct {
	FileName  string
	MimeType  string
	File      *File
	Thumbnail *File
}

Document is a generic file.

type File

type File struct {
	ID         string
	Path       string
	Size       int64
	Downloaded bool
}

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.

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

func NewListener(client *Client, program *tea.Program) *Listener

NewListener registers update handlers on the client's dispatcher. main.go should now pass the wrapper client: telegram.NewListener(tgClient, p).

func (*Listener) Start

func (l *Listener) Start()

Start is a no-op kept for API compatibility: handlers are registered eagerly in NewListener and dispatch is driven by client.Run.

type Location

type Location struct {
	Latitude  float64
	Longitude float64
}

Location is a geo point.

type Message

type Message struct {
	ID     int64
	ChatID int64

	SenderID MessageSender

	Date          int32
	EditDate      int32
	IsOutgoing    bool
	IsChannelPost bool
	IsForwarded   bool

	ReplyToMessageID int64

	Content MessageContent
}

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 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

type MessageDeletedMsg struct {
	ChatId     int64
	MessageIds []int64
}

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

type MessageEditedMsg struct {
	ChatId    int64
	MessageId int64
}

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 MessagePoll

type MessagePoll struct {
	Poll *Poll
}

MessagePoll is a poll 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

type MessageSendSucceededMsg struct {
	Message      *Message
	OldMessageId int64
}

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
}

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 Photo

type Photo struct {
	ID    int64
	Sizes []*PhotoSize
}

Photo is a photo with several sizes.

type PhotoSize

type PhotoSize struct {
	Type   string
	Width  int
	Height int
	File   *File
}

PhotoSize is one size variant of a photo.

type Poll

type Poll struct {
	Question string
}

Poll is a poll (question only; answers are not rendered).

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

type QRLoginToken struct {
	URL       string
	ExpiresAt time.Time
}

QRLoginToken is a short-lived Telegram login token to render as a QR code.

type Sticker

type Sticker struct {
	Emoji string
	File  *File
}

Sticker is a sticker.

type SupergroupFullInfo

type SupergroupFullInfo struct {
	Description string
	MemberCount int32
}

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) SignUp

func (a *TUIAuthorizer) SignUp(ctx context.Context) (auth.UserInfo, error)

SignUp implements auth.UserAuthenticator.

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/length in UTF-16 code units, as returned by Telegram; render converts as before).

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 UnreadCountMsg

type UnreadCountMsg struct {
	UnreadCount        int32
	UnreadUnmutedCount int32
}

UnreadCountMsg is sent when global unread counts change.

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

func LoginWithQR(ctx context.Context, cfg *config.Config, opts QRLoginOptions) (*User, error)

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.

type VideoNote

type VideoNote struct {
	Duration int32
	File     *File
}

VideoNote is a round video file.

type VoiceNote

type VoiceNote struct {
	Duration int32
	File     *File
}

VoiceNote is a voice message file.

Jump to

Keyboard shortcuts

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