Deployment
Deployment
How a vaegram client takes updates in production, stops cleanly, and avoids fighting a second copy of itself.
A deployed bot is a process that stays connected for weeks. What keeps it that way is how it gets updates, how it shuts down, and how many copies run.
Example
use vaegram::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
.bot_token("123456:ABC-DEF")
.start()
.await?;
bot.on_message(filters::command("start"), |msg| async move {
msg.answer("Hello!").await?;
Ok(())
});
bot.run().await
}
run returns Ok(()) after stop, and Error::Disconnected when the connection ends first.
How updates arrive
| Mode | How updates reach the handlers | When to use it |
|---|---|---|
| MTProto (default) | Telegram pushes updates on the connection; run dispatches them |
user accounts, MTProto bots |
| Bot API polling | run long-polls getUpdates |
a Bot API bot that can reach api.telegram.org |
| Bot API webhook | Telegram POSTs to your HTTPS URL; a Webhook dispatches them |
a Bot API bot behind a public HTTPS proxy |
The first two are the same call, run. In Bot API mode a webhook replaces the poll: while one is set, Client::run gets Telegram’s 409 error instead of updates.
Webhooks
Webhook mode needs the bot-api feature, and the built-in server needs webhook-server. The flow is always: make a receiver with a secret, register the public URL, then feed it requests.
use vaegram::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
.bot_api(std::env::var("BOT_TOKEN").expect("BOT_TOKEN"))
.start()
.await?;
let secret = std::env::var("WEBHOOK_SECRET").expect("WEBHOOK_SECRET");
let webhook = bot.webhook(secret)?;
webhook.register("https://bot.example.com/telegram").await?;
webhook.serve("127.0.0.1:8080").await
}
The API id and hash are not used in Bot API mode, but Client::builder still takes them.
- The secret is 1 to 256 characters of
A-Z,a-z,0-9,_and-. Keep it in the environment or a secret store. The receiver compares it in constant time;serverejects a request before reading its body. - The URL must be HTTPS, on port 443, 80, 88 or 8443.
servespeaks plain HTTP, so it belongs behind a reverse proxy that terminates TLS: bind it where only the proxy reaches it and register the proxy’s public URL. - A self-signed certificate is uploaded with the webhook:
.certificate(pem_bytes)on the requestregisterreturns..ip_address("203.0.113.10")pins where Telegram sends requests, and.max_connections(40)sets how many it sends at once (1 to 100). get_webhook_inforeports the URL,pending_update_countandlast_error_message, which is the first thing to read when deliveries stop.
Your own HTTP server
Webhook::handle takes one request’s body and headers and returns a WebhookResponse; answer the request with its status(). Drive the handlers with webhook.run().await (it is Client::run, fed by the webhook) and mount handle in whatever server you already run.
let headers = token.into_iter().map(|value| ("X-Telegram-Bot-Api-Secret-Token", value));
let answer = webhook.handle(&body, headers).await;
match answer.status() {
200 => {} // queued for the handlers, or already taken
401 => {} // wrong or missing secret; nothing was queued
_ => {} // 503: no run is taking updates, or the queue stayed full
}
serve is a small HTTP/1.1 server around the same path: it accepts POST only (405 otherwise), checks the secret before reading the body (401), caps a body at 4 MiB (413), serves 256 connections at once, and answers 200 as soon as an update is queued, so a slow handler never causes a redelivery.
To go back to polling, bot.delete_webhook().await?; and then run.
Graceful shutdown
run_until_signal stops on Ctrl-C or, on Unix, SIGTERM, which is what containers and service managers send. It calls stop, so run finishes the handlers already running and returns Ok(()).
bot.run_until_signal().await?; // Ctrl-C or SIGTERM calls stop()
bot.close().await; // waits for the final save before the process exits
stop_with_timeout(d)bounds that wait: handlers still running at the deadline are cancelled and reported asError::Timeout.runsaves the update state as it returns;close().awaitis what flushes and closes the storage. Await it beforestd::process::exitorRuntime::shutdown_background, which do not wait for a save a plain drop starts in the background.- Returning from
main,#[tokio::main]included, waits for that save.
One instance per session
The default FileStorage keeps <name>.session and holds <name>.session.lock while the client is open. A second client on the same file, in this process or another, fails with ResourceBusy instead of writing interleaved records.
That lock does not protect you from running the same login on two machines: copying the session file and starting both gets the auth key revoked by Telegram (Error::is_auth_key_duplicated), and both clients must log in again. One process per login, or log in separately on each.
In Bot API mode Telegram allows one consumer of a bot’s updates: a second poller, or a poll while a webhook is set, gets 409.
Behind a proxy
ClientBuilder::proxy takes a parsed Proxy. Any address or link Proxy understands works, including tg://proxy, tg://socks and t.me/proxy links.
use vaegram::connection::Proxy;
let proxy: Proxy = "tg://socks?server=127.0.0.1&port=1080".parse()?;
let _bot = vaegram::Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef")
.bot_token("123456:ABC-DEF")
.proxy(proxy);
- SOCKS5, SOCKS4 and HTTP CONNECT are built in; HTTP CONNECT sends Basic credentials in the clear.
- An MTProxy goes through
.proxy(Proxy::MtProxy { .. }); the secret picks padding or fake TLS. - On a network that only lets HTTPS out, the
web-proxyfeature addsProxy::Web, an MTProxy stream carried in HTTPS requests to a relay (tg://webproxylinks). Thewebsocketfeature is the other way out:.websocket()connects over TLS toweb.telegram.org.
Common mistakes
- Registering
http://or a non-standard port. Telegram only posts to HTTPS on 443, 80, 88 and 8443. - Calling
webhook.servebeforeregister, or without a runningrun: every request is answered 503. - Using
run_until_ctrl_cin a container. SIGTERM ends the process without a clean stop; userun_until_signal. - Skipping
close().awaitbeforestd::process::exit, and losing the last update state.
See also
- API docs for
WebhookandWebhookResponse. - Receiving updates for handlers and the update loop.
- Bot API mode vs MTProto for what each transport supports.
- Sessions and storage for the session file and its lock.