Package-Level Type Names (total 50, in which 23 are exported)
/* sort exporteds by: | */
AuthLostError is returned by Client.Run when the authorization of a client
is lost (e.g. the session was terminated from another device) and
Options.OnAuthLost returned an error.
Use errors.As to match it. Err is the RPC error that revealed the lost authorization, e.g.
AUTH_KEY_UNREGISTERED or SESSION_REVOKED. Reason is the error returned by Options.OnAuthLost. Error implements error. Kind returns why authorization is lost. Unwrap returns both underlying errors.
*AuthLostError : error
*AuthLostError : go.uber.org/multierr.multipleErrors
AuthTransferHandler is a function that is called during authorization transfer.
The fn callback should be serialized by user id via external locking.
You can call [Client.Self] to acquire current user id.
The fn callback must return fn error if any.
Client represents a MTProto client to Telegram. allowCDN is the explicit downloader policy copied from Options.AllowCDN. // immutable // immutable Client config. // immutable auth tracks authorization for OnAuthLost. authLost receives error to stop Run on lost authorization.cancelcontext.CancelFunc CDN public keys loaded from help.getCdnConfig and cached per CDN DC.cdnKeysByDCmap[int][]PublicKey cdnKeysGen increments on cache invalidation to avoid storing stale
singleflight result after fingerprint miss.cdnKeysLoadsingleflight.GroupcdnKeysMuxsync.MutexcdnKeysSetbool Shared CDN pools and handle references. cdnSessions stores session state for CDN pools separately from regular DCs.cfg*manager.AtomicConfig // immutableconnclientConnconnBackoffatomic.Pointer[backoff.BackOff] connChanged is closed and re-created on every primary connection
replacement, letting invokeConn wait for reconnect and retry. connDC is the DC of conn, set by createPrimaryConn. Guarded by connMux.connMuxsync.Mutex Connection factory fields. // immutable Client context. Will be canceled by Run on exit. dcAuthPending holds DCs whose authorization was transferred before the
session (key) of the new connection was reported; the mark is set when
it is. Guarded by sessionsMux. dcAuthorized holds, per non-home DC, the id of the auth key the
authorization was transferred to, so that pools using it skip the
transfer and the key is persisted. Guarded by sessionsMux. // immutable Telegram device information. // immutable DCList state.
Domain list (for websocket) // immutable downloadSchedulers are per-DC download schedulers, nil if
Options.DownloadScheduler is not set. // immutable downloader is the instrumented base of Client.Downloader, nil if the
client is not created by NewClient. // immutable droppedKeys holds the ids of auth keys dropped per DC after
ErrPFSDropKeysRequired, so that a connection still running on a dropped
key can't store it back (see storeDCSess). Guarded by sessionsMux. fileInvokers are FileDC invokers wrapped with middlewares.fileInvokersMuxsync.Mutex // immutable filePools are pools returned by FileDC. freezeChecked is when the freeze state was last checked after a
frozen error, guarded by freezeMux.freezeMuxsync.Mutex invoker implements tg.Invoker on top of Client and mw. // immutable Schema layer requested via invokeWithLayer. // immutable life is the state of Start, Close, Done and Wait. // immutable metrics are OpenTelemetry instruments, see meters. // immutablemigrationchan struct{} Migration state. // immutable mw is list of middlewares used in invoker, can be blank. // immutable // immutable Denotes that no update mode is enabled. // immutable // immutable onConnDead is onDead with the DC ID and connection kind. // immutable onConnectionState is called on primary connection state change. // immutable onConnectionStateEvent is onConnectionState with the DC ID. // immutable // immutable onFrozen is called when a frozen error is confirmed by app config. // immutable onSelfError is called on error calling Self(). onSelfSuccess is called on success calling Self(). onTransfer is called in transfer. MTProto options. // immutable primarySessions counts new server sessions of the primary connection. Wrappers for external world, like logs or PRNG. // immutable Ready signal channel, sends signal when client connection is ready.
Resets on reconnect. // immutable requestTimeout returns response deadline of request, may be nil. // immutable // immutable Restart signal channel. // immutable restartSem serializes restarts on request timeout, a 1-slot semaphore
that waiters can leave when their context is done. saveMux serializes load-modify-save of the stored session.selfBotatomic.Bool selfID and selfBot are the authorized user, if known (selfID != 0). serverTime is the server time offset shared by all connections. // immutable serverTimeSet reports whether Options.ServerTimeOffset was set, so the
persisted offset doesn't override it. // immutable Connection state. Guarded by connMux. sessionStates are server session slots per DC, reused across
reconnects. Guarded by sessionsMux. sessions stores regular non-primary DC sessions.sessionsMuxsync.Mutex Session storage. // immutable, nillable Connections to non-primary DC.
subConns are pools for *_MIGRATE redirects (invokeSub). Denotes to use Test DCs. // immutable tg provides RPC calls via Client. Uses invoker below. // immutable Tracing. Telegram updates handler. // immutable API returns *tg.Client for calling raw MTProto methods. Auth returns auth client. CDN creates new multi-connection invoker to given CDN DC ID.
It connects to CDN DCs. CDNProvider returns downloader.CDNProvider that serves CDN redirects using
cached CDN pools of the client.
Wrap any downloader.Client with it via downloader.WithCDNProvider to enable
CDN downloads through it. Close is Shutdown without a deadline: it stops the client started by Start
and waits until all of its background work is finished.
It returns the error that stopped the client before Close was called, e.g.
*AuthLostError (the same as Wait), or nil if Close stopped it or if Start
failed.
Close is idempotent and safe to call concurrently, also before Start (then
the client can not be started anymore). Never call Close from update
handlers, OnAuthLost or other callbacks running inside the client, it would
deadlock: use Stop there. Close returns ErrAlreadyStarted for a client
driven by Run. Config returns current config. DC creates new multi-connection invoker to given DC. Done returns a channel that is closed when the client stops for any reason:
Stop or Close, a fatal error, the end of the lifetime context, a failed Start
or the return of Run. Use Wait to get the reason. Download creates Builder for plain file downloads. DownloadScheduler returns the download Scheduler of given DC, created on
first use with Options.DownloadScheduler, or nil if it is not set.
Each DC has its own window: a flood wait of one DC doesn't shrink the
window of another one. DownloadVia creates Builder for plain file downloads, sending requests to
master DC through given invoker, e.g. a pool from Client.Pool, Client.DC or
Client.MediaOnly.
Unlike passing tg.NewClient(invoker) to downloader directly, CDN redirects
are served through CDN pools of the client (if CDN is allowed). No
Scheduler is set, as the DC of invoker is unknown: use
Builder.WithScheduler(c.DownloadScheduler(dc)). DownloadWeb creates Builder for web file downloads. DownloadWebVia creates Builder for web file downloads through given invoker. Downloader returns file downloader configured for current client: CDN
policy from Options.AllowCDN, metrics from Options.MeterProvider and logs
from Options.Logger (named "downloader").
Each call returns a new copy, so its With* methods don't affect other
downloads; instruments are shared and created once.
It has no Scheduler: use Downloader.WithScheduler with
Client.DownloadScheduler of the DC the downloads go to. FileDC returns invoker for file requests (e.g. upload.getFile) to given DC.
Unlike Client.DC, the pool is created once per DC (concurrent callers share
creation), cached and closed when Run returns, so callers can call FileDC
for every request. Its size is Options.FilePoolSize.
The invoker:
- is wrapped with Options.Middlewares (flood wait, rate limit, metrics);
- uses the primary session for the home DC, without authorization
transfer;
- follows FILE_MIGRATE_X errors to FileDC(X).
Must be called while client is running, otherwise an error is returned.
If a request fails as unauthorized, the cached pool of that DC is dropped
and the request is retried once on a new pool with authorization transfer. FreezeState fetches app config and returns the freeze state of the account. Invoke invokes raw MTProto RPC method. It sends input and decodes result
into output. InvokeRawJSON invokes MTProto method using pure TDLib JSON format.
It accepts JSON with @type field in TDLib format (e.g., "sendMessage")
and returns JSON response in TDLib format.
The JSON structure, keys and values exactly match TDLib standard JSON.
For example, use "sendMessage" not "messages.sendMessage" in @type field. LogOut logs the client out the way Telegram Desktop and TDLib do:
1. auth.logOut on the home DC. A 401 error counts as success: the
authorization is gone either way.
2. auth.logOut on every other DC the client imported the authorization
to (pools of *_MIGRATE redirects and of FileDC), best effort; then
those pools are closed and their sessions forgotten.
3. The stored session is wiped, so the next client started with the same
storage creates a new auth key and starts unauthorized.
Like TDLib, LogOut is irrevocable: the local steps run even if auth.logOut
fails, and its error is returned after them. Lost authorization is not
reported to OnAuthLost while and after logging out, and the client stops
saving its session until it is authorized again.
The client keeps running, unauthorized, on its current auth key; sign in
again or stop it. The auth keys are not destroyed on the server
(destroy_auth_key).
The result carries auth.loggedOut.future_auth_token, if the server sent
one: pass it to a later sign-in (auth.sendCode logout_tokens) to skip the
code. MediaOnly creates new multi-connection invoker to given DC ID.
It connects to MediaOnly DCs. MigrateTo forces client to migrate to another DC. Ping sends low level ping request to Telegram server. Pool creates new multi-connection invoker to current DC. QR returns QR login helper. RandInt64 returns new random int64 from random source.
Useful helper for places in API where random int is required. Run starts client session and blocks until connection close.
The f callback is called on successful session initialization and Run
will return on f() result.
Context of callback will be canceled if fatal error is detected.
The ctx is used for background operations like updates handling or pools.
Run is single-use: create a new Client to run again. See Start, Close and
Wait for the classic approach without explicit callback; Run and Start are
mutually exclusive on one Client (ErrAlreadyStarted). Done and Wait report
the result of Run once it returned. Self returns current user.
You can use tg.User.Bot to check whether current user is bot. SelfID returns the ID of the authorized user or bot and whether it is a
bot, without a request: ok is false if it is not known yet. It is known
after a successful Self call (including the one Run makes on connect) and
is restored from the stored session. SendMessage sends message to peer.
Deprecated: use helpers like message.NewSender. ServerTimeOffset returns the server time minus local time observed by the
client, to be passed as Options.ServerTimeOffset on the next start. It is
zero until the first connection to the server. Shutdown stops the client started by Start, like Stop, and waits until all
of its background work (connections, pools, update handlers and OnAuthLost
callbacks) is finished or ctx is done, like http.Server.Shutdown.
It returns the error that stopped the client before Shutdown was called,
e.g. *AuthLostError (the same as Wait), or nil if Shutdown stopped it or if
Start failed, as Start already returned the error. If ctx is done first, it
returns the wrapped ctx.Err(), and the client keeps stopping in background.
Do not call Shutdown or Close from update handlers, OnAuthLost or other
callbacks running inside the client: the client waits for them to return,
so the call blocks until ctx is done. Use Stop there.
Shutdown returns ErrAlreadyStarted for a client driven by Run. Start connects the client in the background and blocks until it is ready
for requests, which is the moment Run would call its callback, or until it
fails.
The ctx bounds the startup only, like in net.Dialer.DialContext: once Start
returned, the client runs until Stop or Close, a fatal error (e.g.
*AuthLostError or a permanent connection error) or the end of the context
passed via WithLifetime. Note that the client reconnects indefinitely on
transient errors, so use ctx with a deadline to bound the startup.
Start returns the wrapped ctx.Err() if ctx is done before the client is
ready, or the error that stopped the client before it got ready, e.g.
*ConfigError. On error the client is fully stopped: no goroutines are left
behind, and Close returns nil at once.
The client is valid for requests, e.g. via API, between a successful Start
and Close, as inside the Run callback. Use Done or Wait to learn that it
stopped, and Close to release resources:
if err := client.Start(ctx); err != nil {
return err
}
defer func() { _ = client.Close() }()
Start and Run are mutually exclusive, and a Client can be started once:
create a new Client to start again. Start supersedes the
github.com/gotd/contrib/bg package. Stop stops the client started by Start without waiting for it: use Done,
Wait or Close to wait. Unlike Close and Shutdown, Stop is safe to call from
update handlers, OnAuthLost and other callbacks running inside the client.
Stop is idempotent and safe to call concurrently, also before Start (then
the client can not be started anymore). Stop does nothing for a client
driven by Run: cancel the Run context or return from its callback instead. Wait blocks until the client stops or ctx is done.
It returns the error that stopped the client, e.g. *AuthLostError, a
permanent connection error, the error returned by a failed Start or by
Run, nil if it was stopped by Stop or Close or by the end of the lifetime
context, or the wrapped ctx.Err() if ctx is done first.
Unlike Close, Wait does not stop the client, so it is the blocking "run
until disconnected" call of the Start style:
return client.Wait(ctx) acquireSessionState returns a free server session slot of dc for a new
connection, see mtproto.SessionState.(*Client) asCDNHandler() manager.Handler(*Client) asHandler() manager.Handler authLostDetected reports lost authorization revealed by err, if the client
is authorized.(*Client) cachedCDNKeys() ([]exchange.PublicKey, bool, uint64)(*Client) cachedCDNKeysForDC(dcID int) ([]exchange.PublicKey, bool) cachedDC returns cached data pool to given DC or creates new one.
Creation (dial, key exchange and authorization transfer) is done once per DC
without holding cache lock, so other DCs and calls to already created pools
are not blocked. Creation is bounded by migration timeout and is not
canceled when the caller that started it gives up. Failed creation is not
cached.(*Client) cdnConfigFetchContext(caller context.Context) context.Context checkFreeze fetches the freeze state, logs it and calls OnFrozen.(*Client) createCachedDC(ctx context.Context, cache *dcPoolCache, dc int, call *subConnCall) createConnWith creates connection that uses primary session and returns
it with the DC of the session it was created for.
If dialer is nil, primary DC dialer is used.(*Client) createPool(dc int, max int64, creator func() pool.Conn) (*pool.DC, error) createPrimaryConn creates primary connection and records its DC in
c.connDC, so callers must hold connMux (or own c exclusively).(*Client) ctxOrBackground() context.Context(*Client) dc(ctx context.Context, dcID int, max int64, dialer mtproto.Dialer, mode manager.ConnMode) (*pool.DC, error) dcAuthPendingFor reports whether the authorization of the DC of data was
transferred before its key was stored, see setDCAuthorized. dcKeyAuthorized reports whether the stored key of dc already has the
authorization transferred.(*Client) dcList() dcs.List(*Client) dcTransferSetup(dcID int) manager.SetupCallback dropKeyLocked wipes the key and salt of the stored session of dc and
remembers the dropped key, so that connections still running on it don't
store it back. Must be called with sessionsMux held. ensureRestart restarts the primary connection and waits until it is ready.
Reason is restartTimeout or restartMigration, for metrics and logs.(*Client) exportAuth(ctx context.Context, dcID int) (*tg.AuthExportedAuthorization, error)(*Client) fetchCDNKeys(ctx context.Context) ([]exchange.PublicKey, error)(*Client) fetchCDNKeysForDC(ctx context.Context, dcID int) ([]exchange.PublicKey, error)(*Client) fetchConfig(ctx context.Context) fillDCKeys sets data.DCs to the authorized keys of the other DCs. finishStart records the error that stopped the client and closes done.(*Client) handleCDNConnDead(dcID int, err error)(*Client) handleDCConnDead(dcID int, err error)(*Client) handlePrimaryConnDead(err error) handleServiceNotification logs service notifications and reports
AUTH_KEY_DROP_* ones as lost authorization.(*Client) handleUpdates(b *bin.Buffer) error homeDownloader returns Downloader with Scheduler of the home DC, if
Options.DownloadScheduler is set. init sets fields which needs explicit initialization, like maps or channels. invokeCachedDC invokes request on cached data pool of dc.
If the request fails as unauthorized, the pool may be cached with a failed
authorization transfer, e.g. created before sign in completed: it is
dropped and the request is retried once on a new pool, which transfers
authorization again. invokeConn directly invokes RPC call on primary connection without any
additional handling.
If the connection dies before the request is processed by the server,
invokeConn waits until the reconnection loop replaces the connection and
retries the request on it, see https://github.com/gotd/td/issues/1030. invokeDirect directly invokes RPC method, automatically handling datacenter redirects.(*Client) invokeMigrate(ctx context.Context, dcID int, input bin.Encoder, output bin.Decoder) error(*Client) invokeSub(ctx context.Context, dc int, input bin.Encoder, output bin.Decoder) error isDroppedKey reports whether data carries an auth key dropped for its DC
after ErrPFSDropKeysRequired.(*Client) isPermanentError(err error) bool(*Client) loadCDNKeys(ctx context.Context) (fetchedCDNKeys, error) logOutGuests logs out on every cached non-primary DC pool and closes them.(*Client) markAuthorized() meters returns instruments of the client, or noop ones for a client
created without NewClient (tests).(*Client) migrateToDc(ctx context.Context, dcID int) error notifyConnDead calls OnDead and OnConnDead callbacks, if set. notifyConnectionState calls OnConnectionState and OnConnectionStateEvent
callbacks, if set, for the primary connection to the given DC. now returns current time of the client clock. observeAuth tracks authorization by request results and reports lost
authorization of the primary session. observeRestriction logs and counts errors that tell about restrictions
of the account, and checks the freeze state on frozen errors.(*Client) onCDNSession(cfg tg.Config, s mtproto.Session) error onPrimaryNewSession recovers updates after the server started a new
session on the primary connection: updates sent to the previous session
may be lost, so the update handler gets updatesTooLong (getDifference in
telegram/updates), like TDLib and Telegram Desktop. The first session of
the client is skipped: there is no previous one.(*Client) onReady()(*Client) onSession(cfg tg.Config, s mtproto.Session) error primaryConn creates data connection on primary session.
If dialer is nil, primary DC dialer is used.(*Client) primaryDC(dc int) mtproto.Dialer primaryPool creates data pool that shares primary session (auth key) of
the client, so no authorization transfer is needed.
If dialer is nil, primary DC dialer is used.(*Client) processUpdates(updates tg.UpdatesClass) error(*Client) reconnectUntilClosed(ctx context.Context) error(*Client) refreshCDNKeys(ctx context.Context) ([]exchange.PublicKey, error) registerPoolsGauge starts reporting open pools until the returned function
is called. replaceConn replaces primary connection and notifies invokers waiting for
reconnection (see invokeConn).
Caller must hold connMux. reportAuthLost calls OnAuthLost and stops Run if it returns an error.(*Client) resetReady() restartSuspect restarts primary connection, unless it was already replaced
(connChanged is closed), and waits until new connection is ready.(*Client) restoreConnection(ctx context.Context) error restoreDCKeys loads authorized keys of the other DCs, so that their pools
skip key exchange and authorization transfer. run implements Run, see Run and Start. runUntilRestart runs the primary connection until restart. It stores the
DC of the connection in dc, so that its state is reported for the right DC
even after migration changed the session.(*Client) saveSession(cfg tg.Config, s mtproto.Session) error setDCAuthorized marks the current key of dc as authorized (or not) and
persists the authorized keys. setSelf records the authorized user and persists it.(*Client) storeDCSess(target map[int]*pool.SyncSession, data pool.Session) transfer exports current authorization and imports it to another DC.
See https://core.telegram.org/api/datacenter#authorization-transfer.(*Client) updateInterceptor(updates ...tg.UpdateClass) updateStoredSession loads the stored session, applies f and saves it. It
does nothing if there is no storage, no stored session yet, or after
LogOut. waitAuthLost waits for the running OnAuthLost call, if any. wipeSession clears the stored session: the session loader treats empty
data as no session. withResponseDeadline returns context that is canceled with errNoResponse
once timeout passes after conn became ready to send requests.
Time spent waiting for the connection (dial, key exchange, initConnection)
does not count: a slow handshake must not be taken for a dead connection,
or each request would restart it before it gets ready.
*Client : CloseInvoker
*Client : github.com/gotd/td/tg.Invoker
*Client : io.Closer
*Client : github.com/gotd/td/telegram/internal/manager.protoConn
func ClientFromEnvironment(opts Options) (*Client, error)
func Connect(ctx context.Context, appID int, appHash string, opt Options, so ...StartOption) (*Client, error)
func NewClient(appID int, appHash string, opt Options) *Client
func RunUntilCanceled(ctx context.Context, client *Client) error
func noopOnTransfer(ctx context.Context, _ *Client, fn func(context.Context) error) error
ConfigError is returned by Client.Run when the server rejects the
connection setup (initConnection) with an error that reconnecting cannot
fix, e.g. API_ID_INVALID, API_ID_PUBLISHED_FLOOD or
CONNECTION_API_ID_INVALID: the client is misconfigured.
Use errors.As to match it. Err is the RPC error returned to initConnection. Error implements error. Unwrap returns the RPC error.
*ConfigError : github.com/go-faster/errors.Wrapper
*ConfigError : error
func asConfigError(err error) (*ConfigError, bool)
ConnDeadEvent describes a dead connection.
See Options.OnConnDead. DC is the ID of the DC of the connection. Err is the reason. Kind is the kind of the connection.
func (*Client).notifyConnDead(e ConnDeadEvent)
ConnectionStateEvent describes a state change of the primary connection.
See Options.OnConnectionStateEvent. DC is the ID of the DC of the primary connection. State is the new state.
DeviceConfig is config which send when Telegram connection session created.
Error represents RPC error returned to request.
FileSessionStorage is alias of mtproto.FileSessionStorage.
FreezeState is the freeze state of the account, from app config.
A frozen account is signed in and can read, but most methods fail with
FROZEN_METHOD_INVALID until Until or a successful appeal.
See https://core.telegram.org/api/config#freeze-since-date. AppealURL is a t.me link to the bot to appeal with. Since is when the account was frozen, zero if it is not. Until is when the account will be deleted unless the appeal succeeds. Frozen reports whether the account is frozen.
func FreezeStateFrom(cfg tg.JSONValueClass) FreezeState
func (*Client).FreezeState(ctx context.Context) (FreezeState, error)
Options of Client. AckBatchSize is limit of MTProto ACK buffer size. AckInterval is maximum time to buffer MTProto ACK. AllowCDN enables downloader CDN redirect flow for clients that support
downloader integration.
If false, downloader will stay on the master DC path (legacy behavior).
If true and server does not return redirect, requests still go through the
same master path (no extra CDN round-trips).
Default is false.Clockclock.Clock CompressThreshold is a threshold in bytes to determine that message
is large enough to be compressed using GZIP.
If < 0, compression will be disabled.
If == 0, default value will be used. DC ID to connect.
If not provided, 2 will be used by default. DCList is initial list of addresses to connect. Device is device config.
Will be sent with session creation request. DialTimeout is timeout of creating connection. DownloadScheduler enables adaptive limits of in-flight part requests
shared by downloads of the client: one downloader.Scheduler per DC,
created with these options, see Client.DownloadScheduler.
Client.Download and DownloadWeb use the Scheduler of the home DC.
DownloadVia and DownloadWebVia use none, as the DC of the invoker is
unknown: pass Builder.WithScheduler(client.DownloadScheduler(dc)).
Builder.WithScheduler overrides it for one download. Default is nil (no
shared limit). EnablePFS enables Perfect Forward Secrecy with temporary auth keys. ExchangeTimeout is timeout of every key exchange request. FilePoolSize is the max number of connections of each pool returned by
Client.FileDC. Defaults to 4. Layer is the schema layer to request via invokeWithLayer.
If not provided, tg.Layer will be used, i.e. the layer of the schema
this package is generated from. Override it only if the server must be
asked for an older layer; requests are still encoded using tg.Layer
schema, so a mismatch may cause decoding errors. Logger is the structured logger. No logs by default.
Use github.com/gotd/log/logzap to bridge a *zap.Logger:
import (
"go.uber.org/zap"
"github.com/gotd/log/logzap"
)
zapLog, _ := zap.NewProduction()
opts := telegram.Options{
Logger: logzap.New(zapLog),
} MaxRetries is limit of send retries.MessageIDmtproto.MessageIDSource MeterProvider is used for client metrics (gotd.client.*): connection
states, dead connections, reconnects, migrations, lost authorization,
request timeouts, cached DC pools and Invoke durations. No metrics by
default; the global provider is not used.
It is also used by Client.Downloader and Client.Download* (gotd.downloader.*)
and by schedulers of Options.DownloadScheduler, with attribute dc. The
updates manager (telegram/updates) is configured separately: set
updates.Config.MeterProvider too. Middlewares list allows wrapping tg.Invoker. Can be useful for metrics,
tracing, etc. Note that order is important, see ExampleMiddleware.
Middlewares are called in order from first to last. MigrationTimeout configures migration timeout. NoUpdates enables no updates mode.
Enabled by default if no UpdateHandler is provided. OnAuthLost is called when a request of an authorized client fails
with an error meaning that the authorization is lost (see IsAuthLost),
e.g. the session was terminated from another device. Called once until
the client is authorized again.
The client counts as authorized after any successful request that
requires authorization (anything but auth.*, help.*, langpack.* and the
2FA/login email account.* methods), including Self() on connect, or
after a sign in that returned a complete authorization. So a session
restored from storage is covered after its first such request, also
with NoUpdates.
ctx is the context of Run, not of the failed request, so the callback
can make requests, e.g. to sign in again. The callback runs on its own
goroutine, so the failed request returns at once, and Run waits for it
before returning.
Return non-nil error to stop Run with *AuthLostError, so that one
account of many can be stopped and reported. Return nil to keep
running, e.g. to sign in again.
If the connect-time Self() of an authorized client reveals the lost
authorization (e.g. on reconnect), OnAuthLost is called first. If it
returns nil, OnSelfError is called too, as for any Self() error; if
it stops Run, OnSelfError is not called. Before the client is
authorized, such errors are reported via OnSelfError only. OnConnDead is called on connection dead with the DC ID and the kind of
the connection, e.g. for metrics. Preferred over OnDead, which is kept
for compatibility; if both are set, OnDead is called first.
Called from the connection lifecycle, so the callback must not block. OnConnectionState is called when the primary connection state changes:
on every (re)connect start, on successful initialization and on
connection loss. Connection death details are reported via OnDead.
Called synchronously from connection lifecycle, so the callback must
not block. OnConnectionStateEvent is OnConnectionState with the DC ID of the
primary connection the state is about, which changes on migration.
Preferred over OnConnectionState, which is kept for compatibility; if
both are set, OnConnectionState is called first. Same constraints. OnDead will be called on connection dead.
It is called for all connections: primary, pools and CDN, without
telling them apart. Prefer OnConnDead in new code. OnFrozen is called when a request fails because the account is frozen
(see IsFrozen) and app config confirms it. The account stays signed in
and can read, but most methods fail until state.Until or a successful
appeal via state.AppealURL.
The freeze state is checked at most once an hour, on its own
goroutine; ctx is the context of Run. Use Client.FreezeState to check
it at any time, e.g. at start. OnSelfError is called when client receives error calling Self() on connect.
Return error to stop reconnection.
NB: this method is called immediately after connection, so it's not expected to be
non-nil error on first connection before auth, so it's safe to return nil until
first successful auth. OnSelfSuccess is called when client get self calling Self() on connect. OnTransfer is called during authorization transfer.
See [AuthTransferHandler] for details. PingInterval is duration between pings (ping_delay_disconnect) of a
connection. Zero (default) pings like Telegram Desktop, every 30–45
seconds with disconnect_delay 60; see mtproto.Options. PingTimeout is the timeout of ping response, after which the connection
is considered dead. Defaults to 15 seconds, see mtproto.Options. PublicKeys of telegram.
If not provided, embedded public keys will be used. Random is random source. Defaults to crypto. ReconnectionBackoff configures and returns reconnection backoff object. RequestTimeout returns response deadline for a request on the primary
connection, zero to wait as long as the request context allows
(optional).
If the deadline passes while the request context is still alive (e.g.
the request was acknowledged but never answered by a half-dead
connection), the client reconnects and sends the request once more on
the new connection, like Telegram Desktop does. Return zero for
requests that must not be sent twice. Resolver to use. RetryInterval is duration between send retries. ServerTimeOffset is the initial server time minus local time, e.g.
Client.ServerTimeOffset of a previous run. It is corrected from the
first message of the server; message ids and the msg_id time check use
server time, so a skewed local clock doesn't break the connection. SessionStorage will be used to load and save session data.
NB: Very sensitive data, save with care. TempKeyTTL controls temporary key lifetime in seconds.
Default: 86400 (24h).
The value is clamped in mtproto layer to keep protocol-safe bounds. OpenTelemetry. UpdateHandler will be called on received update. WireTracer observes plaintext MTProto messages and lifecycle events of
every connection of the client: primary, other DCs, media and CDN
connections. Nil (default) disables wire tracing.
See mtproto.WireTracer.(*Options) setDefaults()
func OptionsFromEnvironment(opts Options) (Options, error)
func BotFromEnvironment(ctx context.Context, opts Options, setup func(ctx context.Context, client *Client) error, cb func(ctx context.Context, client *Client) error) error
func ClientFromEnvironment(opts Options) (*Client, error)
func Connect(ctx context.Context, appID int, appHash string, opt Options, so ...StartOption) (*Client, error)
func NewClient(appID int, appHash string, opt Options) *Client
func OptionsFromEnvironment(opts Options) (Options, error)
func TestClient(ctx context.Context, opts Options, cb func(ctx context.Context, client *Client) error) error
PublicKey is a Telegram server public key.
SessionStorage is alias of mtproto.SessionStorage.
UpdateHandlerFunc type is an adapter to allow the use of
ordinary function as update handler.
UpdateHandlerFunc(f) is an UpdateHandler that calls f. Handle calls f(ctx, u)
UpdateHandlerFunc : UpdateHandler
authState tracks whether the client is authorized in current Run.authorizedatomic.Bool done is closed when the last OnAuthLost call returns, nil if there
was none. Calls are chained, so it is closed after all of them. loggedOut is set by LogOut until the client is authorized again: lost
authorization is not reported and the session is not saved.reportedatomic.Bool stopped is set when OnAuthLost stopped Run.
lifecycle is the state of Start, Close, Done and Wait. cancel stops the Run started by Start, nil until it is created. closing is set by Stop, so that Start cancels Run at once if Stop
was called before cancel was set. done is closed after the client stops, lazily created by doneChan. err is the error that stopped the client, written before done is
closed. // lifecycleModemuxsync.Mutex startFailed is set when Start returned an error, written before done
is closed. doneChan returns the done channel, creating it if needed.
rawJSONResponseDecoder is a decoder that can decode any response type
and store it as bin.Object for later JSON encoding.resultbin.Object(*rawJSONResponseDecoder) Decode(b *bin.Buffer) error
*rawJSONResponseDecoder : github.com/gotd/td/bin.Decoder
Package-Level Functions (total 50, in which 17 are exported)
AuthKeyDropError returns the error that is reported via OnAuthLost when
the server sends an AUTH_KEY_DROP_* service notification: a *tgerr.Error
with code 401, the notification type as Type and its text as Message.
AuthLostKindOf classifies an error of IsAuthLost.
BotFromEnvironment creates bot client using ClientFromEnvironment
connects to server and authenticates it.
Variables:
BOT_TOKEN — token from BotFather.
ClientFromEnvironment creates client using OptionsFromEnvironment
but does not connect to server.
Variables:
APP_ID: app_id of Telegram app.
APP_HASH: app_hash of Telegram app.
Connect creates a new client with NewClient and starts it with Start.
The ctx bounds the startup only, see Start. Call Close on the returned
client to stop it. On error the client is fully stopped and nil is
returned.
DeviceTDesktopWindows returns a DeviceConfig that emulates a Telegram Desktop
(Windows build) installation on initConnection, making the connection
parameters indistinguishable from Telegram Desktop from the server's
perspective.
Combine it with TDesktopResolver to also match Telegram Desktop on the
transport layer.
FreezeStateFrom returns the freeze state from help.getAppConfig result.
IsAccountBanned reports whether err means that the account is banned by
Telegram: USER_DEACTIVATED_BAN for a signed in account, PHONE_NUMBER_BANNED
when signing in.
IsAuthLost reports whether err means that the authorization of the session
is lost: the auth key is unregistered, the session is revoked or expired,
the user is deactivated, or the key is used by another connection
(AUTH_KEY_DUPLICATED).
SESSION_PASSWORD_NEEDED and other "not authorized yet" errors are not
included.
Errors made from AUTH_KEY_DROP_* service notifications (see
AuthKeyDropError) are included.
IsFrozen reports whether err means that the request was refused because
the account is frozen: FROZEN_METHOD_INVALID (code 420, not a flood
wait) or FROZEN_PARTICIPANT_MISSING.
NewClient creates new unstarted client.
OptionsFromEnvironment fills unfilled field in opts parameter
using environment variables.
Variables:
SESSION_FILE: path to session file
SESSION_DIR: path to session directory, if SESSION_FILE is not set
ALL_PROXY, NO_PROXY: see https://pkg.go.dev/golang.org/x/net/proxy#FromEnvironment
RunUntilCanceled is client callback which
locks until client context is canceled.
TDesktopResolver returns a DC resolver that connects the same way as Telegram
Desktop: every direct connection is wrapped in Obfuscated2 and uses the
abridged transport codec.
Use it together with DeviceTDesktopWindows to be indistinguishable from
Telegram Desktop both on the transport layer and in initConnection:
client := telegram.NewClient(appID, appHash, telegram.Options{
Device: telegram.DeviceTDesktopWindows(),
Resolver: telegram.TDesktopResolver(),
})
TestClient creates and authenticates user telegram.Client
using Telegram test server.
TimezoneParams builds the initConnection params value with the tz_offset
field, matching what the official clients (e.g. Telegram Desktop) send.
The offset is the timezone offset of loc in seconds, rounded to the nearest
15 minutes (900 seconds) and clamped to the [-12h, +14h] range, exactly like
Telegram Desktop's prepareInitParams.
WithLifetime sets the parent context of the client started by Start: when
ctx is done, the client stops as if Stop was called, and Wait and Close
return nil.
By default the lifetime is context.WithoutCancel of the ctx passed to Start,
so values like loggers and trace spans are kept, but the cancellation and
deadline of the startup ctx do not stop the started client.
asConfigError returns ConfigError if err is a permanent error of
initConnection.
These are 400 and 406 errors: the same request with the same parameters
fails again. Official clients send initConnection as a prefix of the
first real request, so such an error fails that request instead of
reconnecting.
CONNECTION_NOT_INITED and CONNECTION_LAYER_INVALID are excluded: TDLib and
Telegram Desktop handle them by sending initConnection again. Errors of
IsAuthLost (e.g. AUTH_KEY_DUPLICATED) keep their own handling.
authEffectOf reports how the successful result of input changes
authorization.
buildTDLibToTelegramMap builds reverse mapping from TDLib method names
(e.g., "sendMessage") to Telegram API names (e.g., "messages.sendMessage").
chainMiddlewares composes new invoker in such order that first element in
chain is called first, and latest "next" argument will be "invoker".
E.g. we have invoker and two middlewares, so order will be following:
0, 1, (invoker), 1 (after "next"), 0 (after "next").
See TestMiddlewareOrder or ExampleMiddleware.
encodeTDLibError encodes tgerr.Error to TDLib JSON error format.
errRetryableOnNewConn reports whether request failed because connection
died before the request was processed by the server (request was not sent,
or sent but not acknowledged), so it is safe to retry the request on a new
connection.
unwrapQuery returns the innermost request of invokeWith* and
initConnection wrappers.
waitReady blocks until ready is closed or ctx is done and reports whether
ready was closed.
Readiness wins when both happen: a request may complete on the fresh
connection and cancel ctx before this goroutine is scheduled, and a plain
select would then drop the ready event at random.
Package-Level Variables (total 17, in which 3 are exported)
AsFloodWait returns wait duration and true boolean if err is
the "FLOOD_WAIT" error.
Client should wait for that duration before issuing new requests with
same method.
ErrAlreadyStarted is returned by Start and Run if the client was
already started by Start or Run: a Client is single-use, and Start and
Run are mutually exclusive. It is also returned by Close and Shutdown
of a client driven by Run.
ErrClientClosed is returned by Start and Run after Close, Shutdown or
Stop of a client that was never started, and by Start canceled by them.
durationBuckets are histogram buckets in seconds, from a fast RPC to a slow
pool creation.
Package-Level Constants (total 42, in which 19 are exported)
Available MTProto default server addresses.
See https://my.telegram.org/apps.
Available MTProto default server addresses.
See https://my.telegram.org/apps.
AuthLostBanned means that the account is banned by Telegram
(USER_DEACTIVATED_BAN).
AuthLostDeleted means that the account is deleted (USER_DEACTIVATED).
AuthLostExpired means that the session expired (SESSION_EXPIRED).
AuthLostKeyInvalid means that the auth key is invalid or used by
another connection (AUTH_KEY_INVALID, AUTH_KEY_DUPLICATED).
AuthLostRevoked means that the session was terminated, e.g. from
another device (SESSION_REVOKED), or the server asked to drop the key
(AUTH_KEY_DROP_* service notification).
AuthLostUnknown is an error that is not one of IsAuthLost errors.
AuthLostUnregistered means that the server doesn't know the auth key
as an authorized one (AUTH_KEY_UNREGISTERED). It is what a terminated
session usually returns, but also what the keys of a deleted or banned
account return once they are dropped.
ConnectionStateConnecting means that client is establishing the primary
connection (initial connect or reconnect after failure).
ConnectionStateDisconnected means that the primary connection is dead.
Client will reconnect automatically, transitioning to
ConnectionStateConnecting.
ConnectionStateReady means that the primary connection is initialized
and ready to send requests.
ConnKindCDN is a connection to a CDN DC.
ConnKindData is a connection of a pool: Client.Pool, Client.DC,
Client.MediaOnly, Client.FileDC, or a FILE_MIGRATE connection.
ConnKindPrimary is the primary connection of Client.Run.
ErrFloodWait is error type of "FLOOD_WAIT" error.
Port is default port used by telegram.
Test-only credentials. Can be used with AddrTest and TestAuth to
test authentication.
Reference:
- https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
Test-only credentials. Can be used with AddrTest and TestAuth to
test authentication.
Reference:
- https://github.com/telegramdesktop/tdesktop/blob/5f665b8ecb48802cd13cfb48ec834b946459274a/docs/api_credentials.md
authAuthorized means that the client is authorized.
authKeyDropPrefix is the type prefix of service notifications asking to
drop the auth key, e.g. after a key leak. Telegram Desktop logs out on
them, mobile apps offer to.
authLoggedOut means that the client logged out.
authNone means that the request tells nothing about authorization.
downloaderMeterName is the meter of downloader metrics, the same as of
downloader.Downloader.WithMeterProvider.
freezeCheckInterval limits app config fetches on frozen errors, as in
Telegram Desktop.
guestLogOutTimeout bounds auth.logOut on each non-primary DC.
Single key because help.getCdnConfig has no request params.
Historical sizing hint for close backlog in tests and heuristics.
Queue growth is controlled by stale-pool production rate and de-dup via
closing map, while close fan-out remains bounded by workers.
maxFileMigrations bounds FILE_MIGRATE hops of one request.
meterName is the name of the meter of Client.
modeClosed means that Close was called before Start.
modeIdle means that neither Run nor Start was called.
modeRun means that the client is driven by Run.
modeStart means that the client is driven by Start and Close.
Values of metric attributes.
Values of metric attributes.
Values of metric attributes.
Values of metric attributes.
Values of metric attributes.
Telegram Desktop application version sent in initConnection.
Keep in sync with the bundled tdesktop reference (Telegram/SourceFiles/core/version.h).
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.