Package-Level Type Names (total 27, in which 15 are exported)
/* sort exporteds by: | */
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. // immutablecancelcontext.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.connMuxsync.Mutex Connection factory fields. // immutable Client context. Will be canceled by Run on exit. // immutable Telegram device information. // immutable DCList state.
Domain list (for websocket) // immutable invoker implements tg.Invoker on top of Client and mw. // immutable // 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 onConnectionState is called on primary connection state change. // immutable // immutable onSelfError is called on error calling Self(). onSelfSuccess is called on success calling Self(). onTransfer is called in transfer. MTProto options. // immutable Wrappers for external world, like logs or PRNG. // immutable Ready signal channel, sends signal when client connection is ready.
Resets on reconnect. // immutable // immutable Restart signal channel. // immutable Connection state. Guarded by connMux. sessions stores regular non-primary DC sessions.sessionsMuxsync.Mutex Session storage. // immutable, nillable Connections to non-primary DC.subConnsMuxsync.Mutex 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. Config returns current config. DC creates new multi-connection invoker to given DC. Download creates Builder for plain file downloads. DownloadWeb creates Builder for web file downloads. Downloader returns file downloader configured for current client. 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. 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.
See `examples/bg-run` and `contrib/gb` package for classic approach without
explicit callback, with Connect and defer close(). Self returns current user.
You can use tg.User.Bot to check whether current user is bot. SendMessage sends message to peer.
Deprecated: use helpers like message.NewSender.(*Client) asCDNHandler() manager.Handler(*Client) asHandler() manager.Handler(*Client) cachedCDNKeys() ([]exchange.PublicKey, bool, uint64)(*Client) cachedCDNKeysForDC(dcID int) ([]exchange.PublicKey, bool)(*Client) cdnConfigFetchContext(caller context.Context) context.Context(*Client) createConn(id int64, mode manager.ConnMode, setup manager.SetupCallback, onDead func(error)) pool.Conn(*Client) createPool(dc int, max int64, creator func() pool.Conn) (*pool.DC, error)(*Client) createPrimaryConn(setup manager.SetupCallback) pool.Conn(*Client) dc(ctx context.Context, dcID int, max int64, dialer mtproto.Dialer, mode manager.ConnMode) (*pool.DC, error)(*Client) dcList() dcs.List(*Client) dcTransferSetup(dcID int) manager.SetupCallback(*Client) ensureRestart(ctx context.Context) error(*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)(*Client) handleCDNConnDead(dcID int, err error)(*Client) handleDCConnDead(dcID int, err error)(*Client) handlePrimaryConnDead(err error)(*Client) handleUpdates(b *bin.Buffer) error init sets fields which needs explicit initialization, like maps or channels. 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(*Client) isPermanentError(err error) bool(*Client) loadCDNKeys(ctx context.Context) (fetchedCDNKeys, error)(*Client) migrateToDc(ctx context.Context, dcID int) error notifyConnectionState calls OnConnectionState callback, if set.(*Client) onCDNSession(cfg tg.Config, s mtproto.Session) error(*Client) onReady()(*Client) onSession(cfg tg.Config, s mtproto.Session) error(*Client) primaryDC(dc int) mtproto.Dialer(*Client) processUpdates(updates tg.UpdatesClass) error(*Client) reconnectUntilClosed(ctx context.Context) error(*Client) refreshCDNKeys(ctx context.Context) ([]exchange.PublicKey, error) replaceConn replaces primary connection and notifies invokers waiting for
reconnection (see invokeConn).
Caller must hold connMux.(*Client) resetReady()(*Client) restoreConnection(ctx context.Context) error(*Client) runUntilRestart(ctx context.Context) error(*Client) saveSession(cfg tg.Config, s mtproto.Session) error(*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)
*Client : github.com/gotd/td/tg.Invoker
*Client : github.com/gotd/td/telegram/internal/manager.protoConn
func ClientFromEnvironment(opts Options) (*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
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. EnablePFS enables Perfect Forward Secrecy with temporary auth keys. ExchangeTimeout is timeout of every key exchange request. 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 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. 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. OnDead will be called on connection dead. 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. 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. Resolver to use. RetryInterval is duration between send retries. 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.(*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 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
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 29, in which 9 are exported)
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.
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.
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.
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.
Package-Level Variables (total 7, in which 1 is 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.
Package-Level Constants (total 13, in which 9 are exported)
Available MTProto default server addresses.
See https://my.telegram.org/apps.
Available MTProto default server addresses.
See https://my.telegram.org/apps.
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.
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
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.
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.4. (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.