Files
MichilisandClaude Opus 5.5 44d0905fa3 Phase 6: inline mode and docs
- Inline mode (INLINE_MODE_ENABLED): "@bot <link>" sends the cached file
  by file_id when the user's limits admit it without payment, and
  otherwise one result that opens the bot with /start il_<token> for the
  link. An inline send counts as a download when Telegram reports it
  chosen (inline feedback). The bot asks Telegram for inline_query and
  chosen_inline_result updates.
- README, OPERATIONS and ARCHITECTURE describe the new flows, Stars,
  inline mode and every new setting; docs/SCREENS.md regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:47:26 +00:00

324 lines
13 KiB
Markdown

# Operations
How to deploy, scale and look after the bot. For a first production
setup, follow [DEPLOY.md](DEPLOY.md) from top to bottom. For workers see
[WORKERS.md](WORKERS.md), for metrics and alerts [MONITORING.md](MONITORING.md).
## Deploy with docker compose
You need Docker with the compose plugin, and a bot token from @BotFather.
```sh
git clone <this repository> dlbot && cd dlbot
cp .env.example .env
```
Edit `.env`. The minimum is:
```sh
BOT_TOKEN=123456:ABC...
OWNER_IDS=<your Telegram user id>
WORKER_A_TOKEN=<openssl rand -hex 24>
WORKER_B_TOKEN=<openssl rand -hex 24>
```
Then:
```sh
docker compose up -d --build
docker compose ps # core, worker-a, worker-b should be healthy
curl localhost:8080/healthz # {"status":"ok"}
```
Open the bot in Telegram, press Start, send a link. As an owner, `/workers`
shows both workers.
The compose file runs the core without an embedded worker and two separate
workers. For a single small machine you can instead run only the core with
`WORKER_EMBEDDED=true` and no remote workers.
## Deploy without Docker
Build `bin/core` and `bin/worker` with `make build`, install `yt-dlp` and
`ffmpeg`, and use the units in `deploy/systemd/`. Each unit file starts
with the commands to install it.
## Choosing the database
**SQLite** is the default and needs nothing. It is a file
(`DB_DSN=data/dlbot.db`) and handles a busy bot on one machine. Back it up
with `sqlite3 dlbot.db ".backup backup.db"`, not with `cp`.
**Postgres** is for when the core should be restartable on another machine,
or when you want the database on managed infrastructure.
```sh
DB_DRIVER=postgres
DB_DSN=postgres://dlbot:<password>@postgres:5432/dlbot?sslmode=disable
POSTGRES_PASSWORD=<password>
docker compose --profile postgres up -d
```
The schema is the same on both and migrations run at startup. There is no
tool to move data from one to the other; choose before you have users, or
accept starting fresh.
Run only **one core** per database. Workers scale out; the core does not.
## Choosing storage
**Local disk** (default): files live under `STORAGE_LOCAL_DIR`. Workers
send finished files through the core.
**S3 compatible** (AWS S3, Garage, MinIO): set
```sh
STORAGE_BACKEND=s3
S3_ENDPOINT=https://s3.example.com
S3_BUCKET=dlbot
S3_ACCESS_KEY=...
S3_SECRET_KEY=...
S3_REGION=garage # whatever your server expects
S3_PATH_STYLE=true # Garage and MinIO: true. AWS: false.
```
The bucket must exist. With `S3_PRESIGN=true` (default) workers upload
straight to the bucket with presigned URLs. If workers reach the bucket
under another address than the core, set `S3_PRESIGN_ENDPOINT`.
Storage holds the cache's stored copies. `CACHE_BUDGET_MB` caps it; the
sweeper evicts the least used files when it is exceeded.
## Files up to 2 GB: the local Bot API server
The cloud Bot API accepts uploads up to 50 MB. A local Bot API server
lifts that to 2000 MB.
1. Get `api_id` and `api_hash` at https://my.telegram.org.
2. If the bot ever ran against the cloud API, log it out there once:
`curl https://api.telegram.org/bot<TOKEN>/logOut`. A bot can be logged
in to one server at a time.
3. In `.env`:
```sh
TELEGRAM_API_ID=...
TELEGRAM_API_HASH=...
TELEGRAM_API_URL=http://telegram-bot-api:8081
TELEGRAM_MAX_UPLOAD_MB=2000
```
4. `docker compose --profile local-api up -d`
`TELEGRAM_MAX_UPLOAD_MB` is the ceiling for everyone. Passes allow up to
`PAID_MAX_SIZE_MB` (2000) but never more than this.
## Public address, webhooks and TLS
The core listens on `HTTP_LISTEN` (`:8080`). Compose binds it to localhost.
Put a TLS reverse proxy (Caddy, nginx, Traefik) in front and set
`PUBLIC_URL=https://bot.example.com` when you want any of:
- instant payment settlement (LNbits webhook) and the "Open in wallet" button
- the Mini App
- remote workers across the internet
- Telegram webhooks instead of long polling (`TELEGRAM_MODE=webhook`,
`WEBHOOK_URL`, `WEBHOOK_SECRET`)
Routes the proxy must pass through:
| Path | Who calls it |
| --- | --- |
| `/telegram/webhook` | Telegram (webhook mode only) |
| `/lnbits/webhook/<secret>` | LNbits |
| `/pay/<id>` | Users pressing "Open in wallet" |
| `/app/...` | The Mini App and its API, opened by Telegram clients |
| `/worker/v1/...` | Remote workers. Allow long requests (30 s) and large uploads. |
| `/healthz` | Your monitoring |
| `/metrics` | Prometheus, over the private network only. `deploy/caddy/Caddyfile` blocks it |
Without `PUBLIC_URL` the bot still works: long polling for Telegram,
polling for payments, workers on the same network.
## The Mini App
The Mini App is a small web page that Telegram opens inside the chat. The
core serves it; there is nothing extra to host.
1. Give the core a public HTTPS address and set it (see the section above).
Telegram refuses Mini Apps over plain http.
```sh
PUBLIC_URL=https://bot.example.com
MINIAPP_ENABLED=true
```
2. Restart the core, then open `https://bot.example.com/app/` in a browser.
You should see one sentence asking you to open the page from Telegram.
That means the app is served and refuses strangers, as it should.
3. Tell Telegram where the app lives. In @BotFather: `/mybots`, pick the
bot, **Bot Settings**, **Configure Mini App**, **Enable Mini App**, and
enter `https://bot.example.com/app/`. This is the bot's "main Mini App".
It adds a **Launch app** button to the bot's profile and makes the link
`https://t.me/<your bot>?startapp` work, which the bot uses in groups.
4. Send `/app` to the bot and press the button.
With the app on, `/app` shows an "Open app" button, group admins get a
link from `/settings` straight into their group's page, and a download
that is over the limit offers the shop inside the app.
The app has no login of its own. Telegram signs who the user is, and the
core checks that signature with the bot token on every call. A signature
older than 24 hours is refused, so an app left open for a day asks to be
opened again.
If step 3 is skipped, the button in private chats still works. Only the
`?startapp` links from groups and the profile button need it.
With the app on, the bot also sets the **menu button** next to the message
field to open the app. The default label is in the source language; each
private chat gets the label in its user's language the first time they
write, and again when they switch language. The command list stays one
tap away under "/".
## Telegram Stars
Stars are a second way to pay for passes and credit packs, next to
Lightning. They need nothing in @BotFather.
```sh
STARS_ENABLED=true
STARS_PRICES=pass_day=50,pass_week=200,pass_month=600,credits_1000=70,credits_5000=330,credits_20000=1300
```
Prices in Stars are set on their own and are never converted from sats.
A product without a price is not sold for Stars. Lightning stays the first
option on every screen; "Pay with Stars" switches to the Stars prices.
Stars purchases are confirmed by Telegram's `successful_payment` update,
never by polling, and each Telegram charge settles once.
To refund a Stars payment, send `/refund <purchase ID>` (or the Telegram
charge ID from the log). Telegram returns the Stars, and the credits or the
pass are taken back. `/stats` shows revenue per payment method.
Stars and Telegram's affiliate program: see [AFFILIATE.md](AFFILIATE.md).
## Inline mode
`@bot <link>` in any chat. When the file is in the cache and the user's
limits allow it without paying, it is sent as is; otherwise the result
opens the bot, which downloads it the usual way.
1. In @BotFather: `/setinline`, pick the bot, enter a placeholder such as
"Paste a link".
2. In @BotFather: `/setinlinefeedback`, pick the bot, **100%**. Telegram
then reports which result was sent, and an inline send counts as a
download of the day. Without it, inline sends are still only offered
within the limits, but they do not count against the daily quota.
3. Set `INLINE_MODE_ENABLED=true` and restart.
## Referrals and flow settings
| Setting | Default | What it does |
| --- | --- | --- |
| `QUEUE_NOTICE_THRESHOLD_SECONDS` | 10 | Show the queue position only above this wait, or with somebody ahead |
| `MULTI_LINK_MAX` | 5 | Links of one message that are handled |
| `CAPTION_ATTRIBUTION` | true | A "via @bot" line under file captions |
| `REFERRAL_REWARD_SATS` | 200 | Sats an inviter earns when an invited user's first Lightning purchase settles (old name `REFERRAL_REWARD` still works) |
| `REFERRAL_DAILY_CAP` | 2000 | Most an inviter earns per day; more waits for the next day. 0 means no cap. |
| `AFFILIATE_ENABLED` | false | Explain Telegram's affiliate program in the Mini App |
## Languages, menus and the bot's profile
At every start the core publishes its command menus in every language it
has a catalog for, and sets the bot's name, description and short
description per language from the catalogs. The profile texts are only
sent again when they change, because Telegram rate limits those calls.
- To keep a name or description you set in @BotFather, set
`TELEGRAM_SET_PROFILE=false`. Or edit `profile.*` in the catalogs.
- To change any text, edit `locales/*.toml` and rebuild, or run with
`LOCALES_DIR` pointing at a copy of `locales/` and send `/reload i18n`.
- `I18N_PSEUDO=true` adds a test language for owners, see
[TRANSLATING.md](TRANSLATING.md).
## Live widgets
In private chats the download status and invoices are HTML widgets (Bot
API 10.4): a progress bar with its own Cancel button, and an invoice with
its QR code, a countdown and the paid state. Nothing needs setting up.
- Telegram shows widgets in private chats only, so groups keep ordinary
messages.
- If `sendWidget` fails, that message is sent the ordinary way. If it
fails three times in a row, or the Bot API server does not know the
method (an older local Bot API server), the bot stops trying for ten
minutes or an hour, then tries again. `dlbot_widgets_total` counts both.
- Apps too old for widgets show the caption: the title of the download,
or the invoice text with the copyable invoice and its buttons.
- `TELEGRAM_WIDGETS=false` turns them off.
## Health and logs
- `GET /healthz` on the core answers 200 while the database is reachable.
- `GET /healthz` on a worker (`WORKER_HEALTH_LISTEN`, `:8081`) answers 200
while the core accepts its token and answers its calls.
- Logs are JSON on stderr, one object per line (`LOG_FORMAT=text` for
reading by eye). Every job line carries `job_id`. The bot token, payment
keys and worker tokens are removed from all log output, and URLs are
logged without credentials or signed parameters.
- Raw yt-dlp errors are in the log under `detail`. Users only ever see the
friendly message.
## Owner commands
Only in a private chat, only for the user IDs in `OWNER_IDS`.
| Command | What it does |
| --- | --- |
| `/workers` | Workers, their state, load, tags and yt-dlp version |
| `/drain <worker>` | Finish current jobs, take no new ones. `/drain <worker> off` undoes it. |
| `/ytdlp update` | Update yt-dlp on every worker now |
| `/cache` | Cache size, hit rate, volume saved |
| `/purge <link>` | Take a video down: delete its files and block it for good |
| `/blocklist add site <host>` | Refuse a whole site. Also `add key <extractor:id>`, `remove`, and no argument to list. |
| `/stats` | Users, jobs, queue, cache, payments, revenue per payment method, and whether the ledger and balances agree |
| `/queue all` | Every queued and running job with its worker and tags |
| `/user <id>`, `/group <chat id>` | Look one up |
| `/ban <id>`, `/unban <id>` | A banned user gets no answers |
| `/grant <id> day\|week\|month` | Give a pass to a user, or to a group (negative ID) |
| `/grant code credits <sats> [uses]` | Create a gift code. Also `code day\|week\|month`. |
| `/credit <id> <sats>` | Add credits |
| `/refund <id> <sats>`, `/refund <id> pass <duration>` | Give sats back, or extend a pass |
| `/refund <purchase or charge ID>` | Return a Stars payment and take back what it granted |
| `/broadcast <text>` | Preview, then send to everyone on confirmation |
| `/maint on\|off` | Refuse new downloads for everyone but owners |
| `/reload i18n` | Reload translations from `LOCALES_DIR` |
## Backups
Back up the database. It holds wallets and the ledger, which are money.
Storage only holds cached files and can be lost without harm: the bot
downloads again.
## Updating
```sh
git pull
docker compose up -d --build
```
The core stops cleanly on SIGTERM: workers hand their running jobs back to
the queue, and the next start resumes deliveries, refunds and unsettled
invoices from the database.
## Checking a deployment
```sh
make acceptance # or MODE=compose make acceptance
```
runs the core with two workers against a fake Telegram, kills a worker in
the middle of a download and checks that the other one delivers the file.