package telegram

Import Path
	github.com/gotd/td/telegram (on go.dev)

Dependency Relation
	imports 48 packages, and imported by 0 packages


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. 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 : github.com/gotd/td/tg.Invoker func ClientFromEnvironment(opts Options) (*Client, error) func NewClient(appID int, appHash string, opt Options) *Client func RunUntilCanceled(ctx context.Context, client *Client) error
CloseInvoker is a closeable tg.Invoker. ( CloseInvoker) Close() error ( CloseInvoker) Invoke(ctx context.Context, input bin.Encoder, output bin.Decoder) error *github.com/gotd/td/pool.DC CloseInvoker : github.com/gotd/td/tg.Invoker CloseInvoker : io.Closer func (*Client).CDN(ctx context.Context, dc int, max int64) (CloseInvoker, error) func (*Client).DC(ctx context.Context, dc int, max int64) (CloseInvoker, error) func (*Client).MediaOnly(ctx context.Context, dc int, max int64) (CloseInvoker, error) func (*Client).Pool(max int64) (CloseInvoker, error)
ConnectionState represents the state of the primary connection. See Options.OnConnectionState. String implements fmt.Stringer. ConnectionState : fmt.Stringer const ConnectionStateConnecting const ConnectionStateDisconnected const ConnectionStateReady
DeviceConfig is config which send when Telegram connection session created.
Error represents RPC error returned to request.
FileSessionStorage is alias of mtproto.FileSessionStorage.
InvokeFunc implements tg.Invoker as function. Invoke implements tg.Invoker. InvokeFunc : github.com/gotd/td/tg.Invoker func Middleware.Handle(next tg.Invoker) InvokeFunc func MiddlewareFunc.Handle(next tg.Invoker) InvokeFunc
Middleware returns new InvokeFunc for next invoker. ( Middleware) Handle(next tg.Invoker) InvokeFunc MiddlewareFunc
MiddlewareFunc implements Middleware as function. Handle implements Middleware. MiddlewareFunc : Middleware
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. Clock clock.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. MessageID mtproto.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. 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.
UpdateHandler will be called on received updates from Telegram. ( UpdateHandler) Handle(ctx context.Context, u tg.UpdatesClass) error UpdateHandlerFunc github.com/gotd/td/tg.UpdateDispatcher
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
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.
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