mtp

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 42 Imported by: 0

Documentation

Overview

Package mtp talks to Telegram as a user account over MTProto.

Index

Constants

View Source
const (
	AccessRead  = "read"
	AccessWrite = "write"
)
View Source
const (
	ClassRead    = "read"
	ClassWrite   = "write"
	ClassBlocked = "blocked"
)
View Source
const (
	TransportAuto      = "auto"
	TransportTCP       = "tcp"
	TransportWebsocket = "websocket"
)

Variables

This section is empty.

Functions

func Classify

func Classify(method string) string

Classify decides whether a method only reads, changes the account, or is never allowed.

func CodeHint

func CodeHint(via, next string, timeout int) string

CodeHint tells a person where to look for the code.

func Describe

func Describe(name string) (map[string]any, error)

Describe returns a compact description of a method or a TL type. Field types end in "!" when required and "?" when optional.

func FilterNames

func FilterNames() []string

FilterNames lists the values accepted by --filter.

func Home

func Home(getenv func(string) string) (string, error)

Home returns the tgbot config directory: $TGBOT_HOME or the OS config dir.

func Layer

func Layer() string

Layer is the MTProto API layer of the embedded schema.

func MethodNames

func MethodNames(prefix string) []string

MethodNames lists MTProto methods, optionally filtered by prefix.

func ParseParams

func ParseParams(raw []byte) (map[string]any, error)

ParseParams reads a JSON object, keeping numbers exact.

func ParseSessionBundle

func ParseSessionBundle(s string) (apiID int, data []byte, err error)

ParseSessionBundle unpacks the output of ExportSession.

func PlaceholderResolver

func PlaceholderResolver(kind, ref string) (map[string]any, error)

PlaceholderResolver stands in for real lookups when only validating (--dry-run).

func PublicID

func PublicID(typ string, id int64) int64

Types

type Config

type Config struct {
	APIID     int       `json:"api_id"`
	APIHash   string    `json:"api_hash"`
	Access    string    `json:"access"`
	Transport string    `json:"transport,omitempty"` // set to websocket once the direct protocol proved blocked
	UserID    int64     `json:"user_id,omitempty"`
	Username  string    `json:"username,omitempty"`
	Name      string    `json:"name,omitempty"`
	CreatedAt time.Time `json:"created_at"`
}

Config is stored next to the session. It holds no Telegram login secrets, but api_hash should still be kept private.

type Conn

type Conn struct {
	API     *tg.Client
	Self    *tg.User
	Profile *Profile
	Peers   *Peers
	Client  *telegram.Client
}

Conn is a connected, authorized account.

func (*Conn) Delete

func (c *Conn) Delete(ctx context.Context, p PeerEntry, ids []int, revoke bool) error

func (*Conn) Dialogs

func (c *Conn) Dialogs(ctx context.Context, o DialogsOpts) ([]Dialog, error)

func (*Conn) Download

func (c *Conn) Download(ctx context.Context, p PeerEntry, id int, out string) (string, error)

Download saves the media of a message and returns the file path. out may be a directory or a file path; empty means the current directory.

func (*Conn) Edit

func (c *Conn) Edit(ctx context.Context, p PeerEntry, id int, text, parse string) (*Sent, error)

func (*Conn) Forward

func (c *Conn) Forward(ctx context.Context, from, to PeerEntry, ids []int) error

func (*Conn) History

func (c *Conn) History(ctx context.Context, p PeerEntry, o HistoryOpts) (*History, error)

func (*Conn) Inbox

func (c *Conn) Inbox(ctx context.Context, o InboxOpts) (*Inbox, error)

Inbox returns unread messages using Telegram's own read markers, so it needs no local state: whatever the user has not read in any client shows up here.

func (*Conn) Info

func (c *Conn) Info(ctx context.Context, p PeerEntry) (map[string]any, error)

Info describes one peer.

func (*Conn) Join

func (c *Conn) Join(ctx context.Context, ref string) (*Who, error)

func (*Conn) Leave

func (c *Conn) Leave(ctx context.Context, p PeerEntry) error

func (*Conn) MarkRead

func (c *Conn) MarkRead(ctx context.Context, p PeerEntry, maxID int) error

func (*Conn) Poll

func (c *Conn) Poll(ctx context.Context, o PollOpts) (*PollResult, error)

Poll returns messages that arrived since the previous poll. Cursors (the last seen message id per chat) live in the profile directory, so no daemon is needed: call it from a cron job or an agent loop.

func (*Conn) Raw

func (c *Conn) Raw(ctx context.Context, method string, params map[string]any) (any, error)

Raw runs any MTProto method. Reads are always allowed; writes need an access-write profile; a small set of dangerous methods is never allowed.

func (*Conn) Resolve

func (c *Conn) Resolve(ctx context.Context, ref string) (PeerEntry, error)

Resolve turns a user-supplied reference into an entry.

Accepted: me, @username, username, t.me/username, t.me/c/<channel>/<msg>, a numeric id as printed by this tool, +phone, or a chat title.

func (*Conn) Search

func (c *Conn) Search(ctx context.Context, o SearchOpts) (*SearchResult, error)

func (*Conn) Send

func (c *Conn) Send(ctx context.Context, p PeerEntry, o SendOpts) (*Sent, error)

func (*Conn) Status

func (c *Conn) Status(ctx context.Context) (map[string]any, error)

StatusInfo describes the profile and the health of its session.

type Dialog

type Dialog struct {
	ID             int64    `json:"id"`
	Type           string   `json:"type"`
	Title          string   `json:"title"`
	Username       string   `json:"username,omitempty"`
	Unread         int      `json:"unread,omitempty"`
	UnreadMentions int      `json:"unread_mentions,omitempty"`
	Muted          bool     `json:"muted,omitempty"`
	Pinned         bool     `json:"pinned,omitempty"`
	Archived       bool     `json:"archived,omitempty"`
	LastMessage    *Message `json:"last_message,omitempty"`
	// contains filtered or unexported fields
}

Dialog is one chat in the chat list.

type DialogsOpts

type DialogsOpts struct {
	Limit    int
	Unread   bool
	Archived bool
	Query    string
}

type Error

type Error struct {
	Kind    Kind
	Code    int
	Message string
	Params  map[string]any
	Err     error
}

Error is a failure with enough structure for the CLI to pick an exit code.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type History

type History struct {
	Chat      Who       `json:"chat"`
	Messages  []Message `json:"messages"`
	OlderThan int       `json:"older_than,omitempty"` // pass as --before to continue backwards
	Untrusted bool      `json:"untrusted"`
}

type HistoryOpts

type HistoryOpts struct {
	Limit    int
	OffsetID int // only messages older than this id
	MinID    int // only messages newer than this id
	Since    time.Time
	Until    time.Time
}

type Inbox

type Inbox struct {
	Chats     []InboxChat `json:"chats"`
	Untrusted bool        `json:"untrusted"`
}

type InboxChat

type InboxChat struct {
	Chat       Who       `json:"chat"`
	Unread     int       `json:"unread"`
	Messages   []Message `json:"messages"`
	MoreUnread int       `json:"more_unread,omitempty"`
	MarkedRead bool      `json:"marked_read,omitempty"`
}

type InboxOpts

type InboxOpts struct {
	MaxChats     int
	PerChat      int
	Scan         int
	IncludeMuted bool
	MarkRead     bool
}

type Kind

type Kind string
const (
	KindUsage   Kind = "usage"   // bad arguments
	KindAuth    Kind = "auth"    // no session, or the session is dead
	KindBlocked Kind = "blocked" // refused by the access policy
	KindAPI     Kind = "api"     // Telegram returned an error
	KindRuntime Kind = "runtime" // network, disk, anything else
)

type LoginOptions

type LoginOptions struct {
	Options
	APIID           int
	APIHash         string
	Phone           string
	QR              bool
	TelethonSession string
	TgbotSession    string // bundle made by `tgbot user session export`
	Code            string // non-interactive step 2
	Resend          bool   // ask Telegram to deliver the pending code another way (SMS or call)
	Password        string // 2FA password, only for this call
	Prompt          func(label string, secret bool) (string, error)
	ShowQR          func(url string, expires time.Time)
}

LoginOptions drive an interactive login. The CLI supplies the prompts, so this package never touches the terminal.

type LoginResult

type LoginResult struct {
	AlreadyLoggedIn bool
	CodeSent        bool
	CodeVia         string
	CodeNext        string // how a resend would be delivered, if Telegram allows one
	CodeTimeout     int    // seconds before a resend is allowed
	Self            *tg.User
}

type Media

type Media struct {
	Type     string `json:"type"`
	Name     string `json:"name,omitempty"`
	Mime     string `json:"mime,omitempty"`
	Size     int64  `json:"size,omitempty"`
	Duration int    `json:"duration,omitempty"`
	Title    string `json:"title,omitempty"`
	URL      string `json:"url,omitempty"`
}

type Message

type Message struct {
	ID      int      `json:"id"`
	Date    string   `json:"date"`
	Chat    *Who     `json:"chat,omitempty"`
	From    *Who     `json:"from,omitempty"`
	Text    string   `json:"text,omitempty"`
	Out     bool     `json:"out,omitempty"`
	ReplyTo int      `json:"reply_to,omitempty"`
	FwdFrom string   `json:"forwarded_from,omitempty"`
	Media   *Media   `json:"media,omitempty"`
	Links   []string `json:"links,omitempty"`
	Edited  string   `json:"edited,omitempty"`
	Views   int      `json:"views,omitempty"`
	Pinned  bool     `json:"pinned,omitempty"`
	Service string   `json:"service,omitempty"`
	AlbumID int64    `json:"album_id,omitempty"`
}

Message is the compact view of a message that agents see.

type Options

type Options struct {
	Version      string
	Stderr       io.Writer
	MaxFloodWait time.Duration // longest FLOOD_WAIT that is waited out instead of reported
	LockTimeout  time.Duration // how long to queue behind another tgbot process

	Transport      string        // auto (default), tcp or websocket
	Proxy          string        // socks5://host:port, or http://host:port with websocket
	ConnectTimeout time.Duration // how long one transport may take to connect
}

Options tune one connected run.

type PeerEntry

type PeerEntry struct {
	Type       string `json:"type"` // user, chat, channel
	ID         int64  `json:"id"`
	AccessHash int64  `json:"access_hash,omitempty"`
	Title      string `json:"title,omitempty"`
	Username   string `json:"username,omitempty"`
	Phone      string `json:"phone,omitempty"`
}

PeerEntry is what the cache remembers about a user, group or channel.

func (PeerEntry) Chat

func (e PeerEntry) Chat() Who

Chat identifies a chat in results.

func (PeerEntry) Input

func (e PeerEntry) Input() tg.InputPeerClass

func (PeerEntry) InputChannel

func (e PeerEntry) InputChannel() tg.InputChannelClass

func (PeerEntry) InputUser

func (e PeerEntry) InputUser() tg.InputUserClass

type Peers

type Peers struct {
	// contains filtered or unexported fields
}

Peers caches access hashes. Telegram only accepts a numeric user or channel id together with the access hash it handed out earlier, so ids from a previous run are resolvable only if we kept them.

func LoadPeers

func LoadPeers(path string) *Peers

func (*Peers) Apply

func (p *Peers) Apply(users []tg.UserClass, chats []tg.ChatClass)

Apply remembers every user and chat from an API response.

func (*Peers) Save

func (p *Peers) Save()

type PollOpts

type PollOpts struct {
	Peers      []string // limit to these chats
	PerChat    int
	Scan       int
	Peek       bool // do not advance the cursors
	IncludeOwn bool
}

type PollResult

type PollResult struct {
	Baseline  bool        `json:"baseline,omitempty"` // first run: cursors were just set, nothing is returned
	Chats     []InboxChat `json:"chats"`
	Untrusted bool        `json:"untrusted"`
}

type Profile

type Profile struct {
	Name string
	Dir  string
	Cfg  Config
}

Profile is one logged-in account: a directory with the session, config and peer cache.

func NewProfile

func NewProfile(home, name string) (*Profile, error)

NewProfile points at a profile directory without requiring it to exist.

func (*Profile) CanWrite

func (p *Profile) CanWrite() bool

CanWrite reports whether the profile may change anything on the account.

func (*Profile) ConfigPath

func (p *Profile) ConfigPath() string

func (*Profile) Exists

func (p *Profile) Exists() bool

func (*Profile) ExportSession

func (p *Profile) ExportSession() (string, error)

ExportSession packs the stored session so it can be moved to another machine. Whoever holds the string has full access to the account.

func (*Profile) Load

func (p *Profile) Load(getenv func(string) string) error

Load reads the config. It fails with KindAuth when the profile has never logged in.

func (*Profile) LockPath

func (p *Profile) LockPath() string

func (*Profile) Login

func (p *Profile) Login(ctx context.Context, o LoginOptions) (*LoginResult, error)

Login signs in and stores the session. If the profile already has a working session it does nothing: a new login is never needed while the key is valid.

func (*Profile) LoginState

func (p *Profile) LoginState() string

LoginState is "awaiting_2fa" while a QR scan was accepted but the password is missing, else "".

func (*Profile) Logout

func (p *Profile) Logout(ctx context.Context, o Options, local bool) (revoked bool, err error)

Logout terminates the session on Telegram's side (unless local is set) and deletes the local files.

func (*Profile) Open

func (p *Profile) Open(ctx context.Context, o Options, fn func(ctx context.Context, c *Conn) error) error

Open connects with the stored session and runs fn. It fails with KindAuth when the session is missing or no longer valid.

func (*Profile) PeersPath

func (p *Profile) PeersPath() string

func (*Profile) RequireWrite

func (p *Profile) RequireWrite(what string) error

RequireWrite is the single gate every state-changing command passes through.

func (*Profile) ResetLogin

func (p *Profile) ResetLogin(ctx context.Context, lockTimeout time.Duration) error

ResetLogin throws away an unfinished login (a pending code, or a QR scan that still waits for the 2FA password) so the next login starts clean. A finished session is never touched.

func (*Profile) Save

func (p *Profile) Save() error

func (*Profile) SessionPath

func (p *Profile) SessionPath() string

func (*Profile) Watch

func (p *Profile) Watch(ctx context.Context, o Options, w WatchOpts, emit func(Message) error) error

Watch streams new messages live over one connection until the window ends.

type RawPlan

type RawPlan struct {
	Method  string
	Class   string
	Request *tlRequest
	Result  string
	Params  map[string]any
}

RawPlan is a validated request that has not been sent.

func PlanRaw

func PlanRaw(method string, params map[string]any, resolve func(kind, ref string) (map[string]any, error)) (*RawPlan, error)

PlanRaw validates params against the schema. resolve turns the @peer, @user and @channel shorthands into Input* objects.

type SearchOpts

type SearchOpts struct {
	Query  string
	Peer   *PeerEntry
	From   *PeerEntry
	Filter string
	Limit  int
	Since  time.Time
	Until  time.Time
	Before int
}

type SearchResult

type SearchResult struct {
	Messages  []Message `json:"messages"`
	Total     int       `json:"total,omitempty"`
	Untrusted bool      `json:"untrusted"`
}

type SendOpts

type SendOpts struct {
	Text      string
	ReplyTo   int
	Silent    bool
	NoPreview bool
	Parse     string // "", "html", "md"
	File      string
	AsFile    bool
	Schedule  time.Time
}

type Sent

type Sent struct {
	ID   int    `json:"id,omitempty"`
	Date string `json:"date,omitempty"`
	Chat Who    `json:"chat"`
}

type TLDecl

type TLDecl struct {
	Name   string
	Fields []TLField
	Result string
}

TLDecl is a TL constructor (an object) or a method.

type TLField

type TLField struct {
	Name     string
	Type     string // type without the flags.N? prefix, e.g. "InputPeer", "Vector<int>"
	Optional bool   // only sent when the flag bit is set
	Flags    bool   // this field is a flags word (flags:# or flags2:#)
	FlagName string // for optional fields: which flags word holds the bit
	Bit      int
}

TLField is one parameter of a TL constructor or method.

type WatchOpts

type WatchOpts struct {
	Peers      []string
	For        time.Duration // 0 = until interrupted
	Max        int           // stop after this many messages; 0 = no limit
	IncludeOwn bool
}

type Who

type Who struct {
	ID       int64  `json:"id"`
	Type     string `json:"type,omitempty"`
	Name     string `json:"name,omitempty"`
	Username string `json:"username,omitempty"`
}

Who identifies a person or chat in output.

Jump to

Keyboard shortcuts

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