Your first client
A gotd program almost always follows the same shape:
- Create a client with
telegram.NewClient. - Call
client.Run, passing a callback. - Do all your work inside that callback.
- Return from the callback to disconnect cleanly.
package main
import (
"context"
"fmt"
"github.com/gotd/td/telegram"
)
func main() {
client := telegram.NewClient(appID, appHash, telegram.Options{})
if err := client.Run(context.Background(), func(ctx context.Context) error {
// The client is connected only while this function runs.
// ctx is cancelled when the connection drops or Run returns.
api := client.API()
// help.getNearestDC works without authentication — a good connectivity check.
dc, err := api.HelpGetNearestDC(ctx)
if err != nil {
return err
}
fmt.Printf("connected, nearest DC: %d\n", dc.NearestDC)
return nil
}); err != nil {
panic(err)
}
}
The Run lifecycle
Run connects, performs the MTProto handshake, runs your callback, and then tears the
connection down. A few rules follow from this:
- The client is only usable inside the callback.
client.API(),client.Auth(),client.Self()and friends must be called whileRunhas not returned. ctxgoverns the connection. If the context is cancelled, the callback'sctxis cancelled too. Use it for every API call so requests are cancelled gracefully.- Returning ends the session. Return
nilfor a clean shutdown, or an error to propagate it out ofRun.
If you authenticate inside the callback, the session lives only for that run unless you persist it — see Sessions and storage. Without a stored session you must re-authenticate every time.
What about long-running bots?
A bot or userbot needs to stay connected and process updates indefinitely. For that you
block inside the callback until the context is cancelled. gotd ships a helper,
telegram.RunUntilCanceled, and the
BotFromEnvironment wrapper that wires this up for you. See
Handling updates and the
Echo bot tutorial.
Configuring the client
telegram.Options
controls almost everything. The fields you will reach for most often:
| Field | Purpose |
|---|---|
SessionStorage | Persist auth between runs — see Sessions |
UpdateHandler | Receive incoming updates — see Handling updates |
Logger | A github.com/gotd/log-compatible logger (e.g. via logzap) |
Middlewares | Intercept every RPC — see Middleware |
NoUpdates | Disable update subscription for one-shot scripts |
Device | Device/app info reported to Telegram |
Resolver | Customize how datacenters are reached — see Transports |
All fields have sensible defaults; an empty telegram.Options{} is valid.