Skip to content

MTGo Config ​

The Config struct is the primary configuration object used to initialize and control an MTGo client. It holds credentials, connection parameters, feature toggles, logging options, and device simulation details.

Config Struct ​

go
type Config struct {
    // Authentication
    APIID                  int32
    APIHash                string
    BotToken               string
    SessionString          string
    PhoneNumber            string
    PhoneCode              string
    Password               string
    CodeFunc               CodeFunc
    PasswordFunc           PasswordFunc

    // Connection
    DC                     int
    SessionName            string
    WorkDir                string
    InMemory               bool
    Proxy                  *Proxy
    MTProxy                *MTProxyConfig
    TestMode               bool
    IPv6                   bool
    WebSocket              bool
    WebSocketTLS           bool
    ServerAddr             string
    LocalAddr              string
    TransportMode          string
    Storage                storage.Storage

    // Update Handling
    NoUpdates              bool
    AutoConnect            bool
    SkipUpdates            bool
    SleepThreshold         time.Duration
    HandlerTimeout         time.Duration
    Timeout                time.Duration
    ReqTimeout             time.Duration
    Retries                int

    // Concurrency & Caching
    MaxConcurrentTrans     int
    DispatchWorkers        int
    DispatchQueueSize      int
    MaxMessageCacheSize    int
    MaxTopicCacheSize      int
    PeerCacheSize          int

    // Parsing & Display
    ParseMode              params.ParseMode
    HidePassword           bool
    LinkPreviewOptions     *types.LinkPreviewOptions
    Takeout                bool

    // Fetching
    FetchReplies           bool
    FetchTopics            bool
    FetchStories           bool
    FetchStickers          bool

    // Device Simulation
    ClientPlatform         types.ClientPlatform
    Device                 DeviceConfig

    // Deprecated: use Device fields instead
    AppVersion             string
    DeviceModel            string
    SystemVersion          string
    LangCode               string
    LangPack               string
    SystemLangCode         string
    TZOffset               int

    // Peer Storage
    SavePeers              bool

    // Reconnection
    ReconnectEnabled       bool
    ReconnectBaseDelay     time.Duration
    ReconnectMaxDelay      time.Duration
    ReconnectMaxAttempts   int

    // Health Check
    HealthEnabled          bool
    HealthPingInterval     time.Duration
    HealthPongTimeout      time.Duration

    // Update Pipeline
    UpdateQueueSize        int
    DurableUpdateQueue     bool
    MaxUpdateHandlerRetry  int
    UpdateRecoveryEnabled  bool

    // Logging
    Log                    LogConfig
}

Authentication Fields ​

FieldTypeDefaultDescription
APIIDint320Telegram API application ID obtained from my.telegram.org. Required for all clients.
APIHashstring""Telegram API application hash obtained from my.telegram.org. Required for all clients.
BotTokenstring""Bot authentication token from @BotFather. Used instead of phone-based login when running as a bot.
SessionStringstring""Pre-existing session string for resuming an authenticated session without re-login. Supports Telethon, Pyrogram, GramJS, mtcute, or auto-detected format.
PhoneNumberstring""Phone number for user authentication in international format (e.g. +1234567890). Used during interactive login flow.
PhoneCodestring""Verification code received via Telegram/SMS during authentication. Typically set programmatically in response to a code callback.
Passwordstring""Two-factor authentication password. Required when the account has 2FA enabled.
CodeFuncCodeFuncnilFunction that returns the verification code for phone login. When nil, TerminalCodeFunc (stdin prompt) is used.
PasswordFuncPasswordFuncnilFunction that returns the 2FA password during phone login. When nil, TerminalPasswordFunc (stdin prompt) is used.

Connection Fields ​

FieldTypeDefaultDescription
DCint0Data center ID to connect to. When 0, the client resolves the correct DC automatically during authentication.
SessionNamestring""Label identifying this session. Stored via Storage.SetSessionID and used by backends to scope queries.
WorkDirstring""Working directory for session files and other persistent data. Defaults to the current working directory when empty.
InMemoryboolfalseWhen true, stores the session entirely in memory instead of writing to disk. Session is lost when the process exits.
Proxy*ProxynilSOCKS5/HTTP proxy configuration for routing connections through a proxy server.
MTProxy*MTProxyConfignilMTProxy configuration for connecting through an obfuscated proxy tunnel.
TestModeboolfalseWhen true, connects to Telegram's test DC environment. Used for development and testing only.
IPv6boolfalseWhen true, forces the client to resolve server addresses to IPv6.
WebSocketboolfalseWhen true, routes MTProto traffic over a WebSocket connection. Useful behind restrictive firewalls.
WebSocketTLSbooltrueWhen true, secures the WebSocket connection with TLS (wss://). Should be true in production.
ServerAddrstring""Optional override for the DC address. When set, dials this address directly instead of resolving from the built-in datacenter map. Format: "host:port".
LocalAddrstring""Local network address to bind when dialing the server. Useful on multi-homed hosts. Format: "host:port".
TransportModestring"Abridged"MTProto TCP framing mode. Valid values: "Abridged", "Intermediate", "PaddedIntermediate", "Full".
Storagestorage.StoragenilCustom storage backend. When set, takes precedence over InMemory and file-based storage. Use helper constructors from sub-packages: sqlite.New(), postgres.New(), mongodb.New(), storage.NewMemory().

Update Handling Fields ​

FieldTypeDefaultDescription
NoUpdatesboolfalseWhen true, disables the long-poll loop that receives real-time updates. Useful for send-only clients.
AutoConnectboolfalseWhen true, automatically connects on first RPC call or handler registration without requiring an explicit Connect() call.
SkipUpdatesbooltrueWhen true, discards all pending updates that accumulated while the client was offline. Prevents processing stale messages on reconnect.
SleepThresholdtime.Duration10sDuration the client waits in flood-wait situations before resuming requests.
HandlerTimeouttime.Duration0Maximum time an update handler may run before its context is cancelled. When 0, no timeout is enforced.
Timeouttime.Duration60sTCP connection timeout used when dialing Telegram servers.
ReqTimeouttime.Duration60sDefault timeout applied to RPC requests when no deadline is set on the context. Enforced minimum of 1 second.
Retriesint0Number of retries for RPC calls on transient errors (timeouts, connection resets, 500s). Non-retryable errors (401, 400, 403) fail immediately.

Concurrency & Caching Fields ​

FieldTypeDefaultDescription
MaxConcurrentTransint1Maximum number of concurrent file transfers. Keep low on bandwidth-constrained networks.
DispatchWorkersint0Number of session workers for TL-decoding incoming messages. Values <= 0 use runtime.GOMAXPROCS(0).
DispatchQueueSizeint256Bounded queue capacity for incoming messages waiting for TL decode. Larger values absorb bursts at the cost of memory.
MaxMessageCacheSizeint1000Maximum number of messages retained in the internal cache. Older entries are evicted when exceeded.
MaxTopicCacheSizeint1000Maximum number of forum topics retained in the internal cache. Older entries are evicted when exceeded.
PeerCacheSizeint5000Maximum number of peer and username entries cached in memory. Setting to 0 disables eviction (unbounded growth).

Parsing & Display Fields ​

FieldTypeDefaultDescription
ParseModeparams.ParseMode0Default formatting mode for message text. Use params.ParseModeMarkdown, params.ParseModeHTML, etc. Zero value means no parsing.
HidePasswordboolfalseWhen true, masks the 2FA password in logs and error output. Recommended for production.
LinkPreviewOptions*types.LinkPreviewOptionsnilGlobal defaults for link previews on outgoing messages. Individual methods can override per-call.
TakeoutboolfalseWhen true, enables a takeout session for exporting Telegram data. Less prone to FLOOD_WAIT. Only for user accounts; bots ignore this. Implies NoUpdates=true.

Fetching Fields ​

FieldTypeDefaultDescription
FetchRepliesbooltrueWhen true, resolves reply-to references so that quoted messages are included in the incoming Message object.
FetchTopicsbooltrueWhen true, loads forum topic metadata alongside messages from supergroups with topics enabled.
FetchStoriesbooltrueWhen true, retrieves Telegram Stories posted by contacts and channels.
FetchStickersbooltrueWhen true, downloads sticker metadata so that sticker messages include the full Sticker object.

Device Simulation Fields ​

FieldTypeDefaultDescription
ClientPlatformtypes.ClientPlatformClientPlatformAndroidSimulated client platform reported to Telegram. Affects which features Telegram exposes.
DeviceDeviceConfigsee defaultsDevice identity reported to Telegram. When set, its fields override the deprecated top-level fields.

The following top-level fields are deprecated — use Device instead:

FieldMaps toDescription
AppVersionDevice.AppVersionApplication version string (e.g. "1.0.0").
DeviceModelDevice.DeviceModelHardware model (e.g. "Samsung Galaxy S24").
SystemVersionDevice.SystemVersionOS version (e.g. "Android 14").
LangCodeDevice.LangCodeISO 639-1 UI language code (e.g. "en").
LangPackDevice.LangPackLanguage pack identifier (e.g. "tdesktop").
SystemLangCodeDevice.SystemLangCodeDevice-level language code.
TZOffsetDevice.TZOffsetTimezone offset from UTC in seconds.

Peer Storage ​

FieldTypeDefaultDescription
SavePeersbooltrueWhen true, persistently caches peer information to storage. Avoids repeated lookups on restart.

Reconnection Fields ​

FieldTypeDefaultDescription
ReconnectEnabledbooltrueEnables automatic reconnection with exponential backoff when the transport is interrupted.
ReconnectBaseDelaytime.Duration1sInitial delay before the first reconnection attempt. Subsequent attempts double the delay.
ReconnectMaxDelaytime.Duration60sCaps the exponential backoff delay between reconnection attempts.
ReconnectMaxAttemptsint0Maximum number of reconnection tries. A value of 0 means unlimited retries.

Health Check Fields ​

FieldTypeDefaultDescription
HealthEnabledbooltrueActivates periodic health-check pings to detect stale connections early. When false, disconnections are only discovered on the next RPC call.
HealthPingIntervaltime.Duration60sTime between successive health-check pings. Shorter intervals detect failures faster but consume more bandwidth.
HealthPongTimeouttime.Duration30sMaximum time to wait for a pong response before treating the connection as dead and triggering a reconnect.

Update Pipeline Fields ​

FieldTypeDefaultDescription
UpdateQueueSizeint1024Buffered channel capacity for incoming updates. Larger values absorb bursts but increase memory usage.
DurableUpdateQueuebooltruePersists undelivered updates across reconnects so that no update is lost during brief network outages.
MaxUpdateHandlerRetryint3Number of times the client retries calling an update handler that returned an error. After exhausting retries, the update is dropped.
UpdateRecoveryEnabledbooltrueRestores updates that may have been lost during reconnection by fetching missed events from the server.

Logging ​

FieldTypeDefaultDescription
LogLogConfigzero valueConfigures the client's logging subsystem including log level, file output, and size limits.

Proxy Struct ​

The Proxy struct configures an upstream proxy for the client's connections.

go
type Proxy struct {
    Addr     string
    Username string
    Password string
    Protocol string
}
FieldTypeDefaultDescription
Addrstring""Proxy address in host:port format (e.g. "127.0.0.1:1080").
Usernamestring""Username for proxy authentication. Leave empty if the proxy does not require credentials.
Passwordstring""Password for proxy authentication. Leave empty if the proxy does not require credentials.
Protocolstring"socks5"Proxy protocol: "socks5", "socks4", "http", or "https".

MTProxyConfig Struct ​

The MTProxyConfig struct configures a connection through an MTProxy server.

go
type MTProxyConfig struct {
    Addr   string
    Secret string
}
FieldTypeDefaultDescription
Addrstring""MTProxy server address in host:port format.
Secretstring""Hex-encoded MTProxy secret. Supports dd-prefixed (obfuscated2 + PaddedIntermediate), ee-prefixed (fake TLS + obfuscated2), or simple 16-byte secrets.

DeviceConfig Struct ​

The DeviceConfig struct holds device identity reported to Telegram during init.

go
type DeviceConfig struct {
    DeviceModel    string
    SystemVersion  string
    AppVersion     string
    LangCode       string
    SystemLangCode string
    LangPack       string
    TZOffset       int
    ClientPlatform types.ClientPlatform
}
FieldTypeDefaultDescription
DeviceModelstring"MTGo"Hardware model (e.g. "Samsung Galaxy S24").
SystemVersionstring"1.0.0"OS version (e.g. "Android 14").
AppVersionstring"1.0.0"Client app version.
LangCodestring"en"ISO 639-1 UI language code.
SystemLangCodestring"en"Device-level language code.
LangPackstring"tdesktop"Translation pack identifier.
TZOffsetint0Timezone offset from UTC in seconds.
ClientPlatformtypes.ClientPlatformClientPlatformAndroidSimulated platform.

LogConfig Struct ​

The LogConfig struct controls logging output, verbosity, and rotation.

go
type LogConfig struct {
    Level   LogLevel
    File    string
    MaxSize int64
    Logger  *Logger
}
FieldTypeDefaultDescription
LevelLogLevelNoLevelMinimum log level. Messages below this level are discarded.
Filestring""File path for log output. When empty, logs are discarded unless a custom Logger is provided.
MaxSizeint640Maximum log file size in bytes before rotation. When 0, no rotation is performed.
Logger*LoggernilCustom logger instance. When non-nil, takes precedence over File and Level.

DefaultConfig ​

The DefaultConfig variable provides a pre-populated configuration with sensible defaults. It is the recommended starting point for constructing a Config.

go
var DefaultConfig = Config{
    SleepThreshold:      10 * time.Second,
    Timeout:             60 * time.Second,
    ReqTimeout:          60 * time.Second,
    MaxConcurrentTrans:  1,
    DispatchQueueSize:   256,
    MaxMessageCacheSize: 1000,
    MaxTopicCacheSize:   1000,
    PeerCacheSize:       5000,
    Device: DeviceConfig{
        DeviceModel:    "MTGo",
        SystemVersion:  "1.0.0",
        AppVersion:     "1.0.0",
        LangPack:       "tdesktop",
        LangCode:       "en",
        SystemLangCode: "en",
        ClientPlatform: types.ClientPlatformAndroid,
    },
    SkipUpdates:           true,
    TransportMode:         "Abridged",
    SavePeers:             true,
    WebSocketTLS:          true,
    FetchReplies:          true,
    FetchTopics:           true,
    FetchStories:          true,
    FetchStickers:         true,
    ReconnectEnabled:      true,
    ReconnectBaseDelay:    1 * time.Second,
    ReconnectMaxDelay:     60 * time.Second,
    HealthEnabled:         true,
    HealthPingInterval:    60 * time.Second,
    HealthPongTimeout:     30 * time.Second,
    UpdateQueueSize:       1024,
    DurableUpdateQueue:    true,
    MaxUpdateHandlerRetry: 3,
    UpdateRecoveryEnabled: true,
}

Start from DefaultConfig and override only the fields you need:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your_api_hash_here"
cfg.SessionName = "my_session"

Transport Mode Constants ​

Constants for selecting the MTProto TCP framing mode:

go
const (
    TransportModeAbridged         = "Abridged"
    TransportModeIntermediate     = "Intermediate"
    TransportModePaddedIntermediate = "PaddedIntermediate"
    TransportModeFull             = "Full"
)
ConstantDescription
TransportModeAbridgedCompact framing, 1-4 bytes overhead. Default.
TransportModeIntermediateFixed 4-byte length-prefix framing.
TransportModePaddedIntermediateIntermediate with 0-15 bytes of random padding.
TransportModeFullFull framing with sequence numbers and CRC32.

LogLevel Constants ​

The LogLevel type controls logging verbosity. Lower values produce more output.

go
const (
    TraceLevel LogLevel = iota // 0 - Most verbose
    DebugLevel                 // 1
    InfoLevel                  // 2
    WarnLevel                  // 3
    ErrorLevel                 // 4
    NoLevel                    // 5 - Logging disabled
)
ConstantValueDescription
TraceLevel0Extremely verbose output including full MTProto frame contents. Useful for debugging protocol-level issues. Warning: produces very large log volumes.
DebugLevel1Detailed debugging output including request/response summaries. Suitable for development and troubleshooting.
InfoLevel2General operational messages such as connection events, authentication progress, and session state changes. Recommended for most production deployments.
WarnLevel3Warning conditions that are not errors but may indicate suboptimal behavior (e.g., slow handlers, retryable failures).
ErrorLevel4Error conditions only. Logs unexpected failures, connection drops, and handler panics.
NoLevel5Disables all log output. Suitable when you want zero console/file noise.

Examples ​

Minimal User Client ​

Connect as a user with phone-based authentication and sensible defaults:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "user_session"
cfg.PhoneNumber = "+1234567890"
cfg.Log.Level = mtgo.InfoLevel

Bot Client ​

Connect as a bot using a BotFather token. No phone authentication is needed:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.BotToken = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
cfg.HandlerTimeout = 30 * time.Second

Ephemeral In-Memory Client ​

Useful for one-shot operations where persistence is not needed:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionString = "existing_session_string"
cfg.InMemory = true
cfg.NoUpdates = true
cfg.SkipUpdates = true

Client with Proxy ​

Route traffic through a SOCKS5 proxy:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "proxied_session"
cfg.Proxy = &mtgo.Proxy{
    Addr:     "127.0.0.1:1080",
    Username: "proxy_user",
    Password: "proxy_pass",
}

Client with MTProxy ​

Route traffic through an MTProxy server:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "mtproxy_session"
cfg.MTProxy = &mtgo.MTProxyConfig{
    Addr:   "proxy.example.com:443",
    Secret: "dd05fb7acb549be047a7c585116581418",
}

Client with WebSocket Transport ​

Use WebSocket transport, useful behind restrictive firewalls:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.BotToken = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
cfg.WebSocket = true
cfg.WebSocketTLS = true

Custom Device Identity ​

Spoof a specific device and locale:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "full_device"
cfg.Device = mtgo.DeviceConfig{
    DeviceModel:    "Samsung Galaxy S24 Ultra",
    SystemVersion:  "Android 14",
    AppVersion:     "10.14.2",
    LangCode:       "en",
    LangPack:       "android",
    SystemLangCode: "en",
    TZOffset:       3600,
    ClientPlatform: types.ClientPlatformAndroid,
}

Custom Storage Backend ​

Use SQLite or another storage backend:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "custom_storage"
cfg.Storage = sqlite.New("bot.db")

Logging to File with Rotation ​

Write logs to a rotating file with a 50 MB size limit:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.SessionName = "logged_session"
cfg.Log = mtgo.LogConfig{
    Level:   mtgo.DebugLevel,
    File:    "/var/log/mtgo/client.log",
    MaxSize: 50 * 1024 * 1024, // 50 MB
}
cfg.HidePassword = true

High-Throughput Bot ​

Optimized configuration for a bot handling heavy traffic:

go
cfg := mtgo.DefaultConfig
cfg.APIID = 12345678
cfg.APIHash = "your-api-hash"
cfg.BotToken = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
cfg.MaxConcurrentTrans = 100
cfg.MaxMessageCacheSize = 10000
cfg.DispatchWorkers = 8
cfg.FetchReplies = true
cfg.FetchTopics = true
cfg.SavePeers = true
cfg.HandlerTimeout = 10 * time.Second
cfg.SleepThreshold = 500 * time.Millisecond
cfg.Log.Level = mtgo.WarnLevel

Released under the Apache-2.0 License.