- Stars as a second payment method for passes and credit packs, next to Lightning (STARS_ENABLED, prices in [stars_prices] / STARS_PRICES, set on their own). Invoices in XTR with no provider token and one price; pre-checkout checks payer, state, currency and amount; successful_payment settles through the same transaction as Lightning, so entitlement is identical. Idempotent by telegram_payment_charge_id (unique index). - Migration 00009: payment_method on purchases and ledger entries, plus stars_amount, tg_charge_id and refunded_at on purchases. Stars purchases never reach LNbits. - Chat: buy screen, /credits, /account and the over-limit offer show Lightning first and a Pay with Stars button. - Mini App: Lightning and Stars switch on Buy; Stars use createInvoiceLink and WebApp.openInvoice, confirmed by the server-side payment event. - Owner /refund <purchase or charge ID> calls refundStarPayment and takes back the credits or pass; refunded_payment messages do the same once. /stats shows revenue by payment method. - The sats referral reward counts Lightning purchases only. - The bot now asks Telegram for pre_checkout_query updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1138 lines
59 KiB
Markdown
1138 lines
59 KiB
Markdown
# Assumptions
|
|
|
|
Decisions taken where the brief was open. Each one was the simplest
|
|
reasonable option at the time. They are grouped by phase and can be revisited.
|
|
|
|
## Verified third-party facts
|
|
|
|
Checked against source or live behavior before use, not from memory.
|
|
|
|
| What | Version | How it was checked |
|
|
| --- | --- | --- |
|
|
| telego | v1.13.0, Bot API 10.4 | Module source. `SendWidget` and `WidgetQuery` exist natively. |
|
|
| yt-dlp | 2026.10.26 | `--help` of the release binary plus real downloads. |
|
|
| go-i18n | v2.7.0 | Module source (`parse.go` for nested TOML keys). |
|
|
| goose | v3.30.1 | Module source (`NewProvider`, dialect constants). |
|
|
| modernc.org/sqlite | v1.62.0 | Module source (`_pragma` and `_txlock` DSN keys). |
|
|
|
|
**Go version.** telego v1.13.0, the release that supports Bot API 10.4,
|
|
declares `go 1.26.11`, so that is the minimum for this module. The brief asks
|
|
for Go 1.23 or newer, which this satisfies. With the default
|
|
`GOTOOLCHAIN=auto` an older Go downloads the right toolchain by itself.
|
|
|
|
yt-dlp behaviors that shaped the wrapper:
|
|
|
|
- A download that is rejected by `--match-filters` or `--max-filesize` exits
|
|
with status 0 and no file. The wrapper detects the missing file and maps
|
|
it to `too_long`, `live_stream` or `too_large`.
|
|
- `--print pre_process:...` still fires when a filter rejects the item, so
|
|
the worker always learns duration and live status.
|
|
- `filesize_approx` can be a float and many numbers can be null. The JSON
|
|
types tolerate all of that.
|
|
- YouTube refuses requests from many datacenter addresses ("Sign in to
|
|
confirm you are not a bot"). This maps to `site_blocked` and is the reason
|
|
worker tags such as `residential` exist (Phase 4).
|
|
|
|
## Phase 1
|
|
|
|
### Project
|
|
|
|
- **Module path** is `github.com/noderunners/dlbot`. No remote was given.
|
|
Renaming is a search and replace.
|
|
- **One binary for now.** Phase 1 asks for "one local worker", so the worker
|
|
runs inside `cmd/core` (`WORKER_EMBEDDED=true`). The worker code already
|
|
talks to the core through the `worker.Coordinator` interface and the
|
|
`workerproto` messages, so `cmd/worker` in Phase 4 only adds an HTTPS
|
|
transport.
|
|
- **Configuration** is environment first. An optional TOML file holds the
|
|
same settings for people who prefer a file; the environment overrides it.
|
|
A `.env` file in the working directory is loaded for convenience.
|
|
- **IDs** are 26 character, time sortable, lowercase strings generated by
|
|
the application. This avoids autoincrement differences between SQLite and
|
|
Postgres and keeps callback data short.
|
|
- **Timestamps** are unix milliseconds in `BIGINT` columns, for the same
|
|
portability reason.
|
|
|
|
### Bot behavior
|
|
|
|
- **Private chat:** any message with a link starts the flow. Up to 3 links
|
|
per message get a card each. Text without a link gets a short hint.
|
|
- **Groups:** only commands are handled. `/dl <url>`, or `/dl` as a reply to
|
|
a message with a link. The card and the file reply to the message that
|
|
holds the link. Auto-detect of pasted links arrives with group settings in
|
|
Phase 5.
|
|
- **The card is the status message.** After a format is picked the same
|
|
message is edited through queued, downloading, processing, uploading and
|
|
done. One request is one download; to get a second format the user sends
|
|
the link again.
|
|
- **Card buttons:** Best, 720p, 480p, MP3, Thumbnail, Cancel. Resolution
|
|
buttons at or above the source height are hidden because they would
|
|
duplicate Best. MP3 is hidden when the source has no audio, Thumbnail when
|
|
there is none. The 1080 and m4a profiles exist but are not on the card.
|
|
- **"Skip the queue"** is not shown yet. It is a paid action and appears with
|
|
payments in Phase 2, rather than as a button that does nothing.
|
|
- **Thumbnail:** the card is a photo sent by URL. When Telegram cannot fetch
|
|
the thumbnail the bot falls back to a text card with the same buttons.
|
|
- **/audio and /thumb** skip the card and start the profile directly.
|
|
- **Playlists** are detected and politely refused for now. Per-item jobs
|
|
with an item cap come with the cache in Phase 3, because each item is its
|
|
own cache entry.
|
|
- **Language:** the user's Telegram `language_code` is stored and resolved
|
|
on every update. Only English ships in Phase 1, but no handler contains
|
|
literal text.
|
|
- **Forum topics:** replies keep messages in the right topic. If the
|
|
original message is deleted the fallback message goes to the general
|
|
topic.
|
|
|
|
### Formats
|
|
|
|
- Video prefers **h264 with AAC in mp4** (`-S vcodec:h264,res[:N],acodec:m4a`,
|
|
merge to `mp4/mkv`). This is what Telegram clients stream inline. "Best"
|
|
therefore means the best h264 rendition, which on YouTube is up to 1080p.
|
|
- Files that are not mp4, m4v or mov are sent as documents instead of being
|
|
transcoded. Transcoding belongs to the derive step of Phase 3.
|
|
- A video or photo Telegram rejects is sent once more as a document.
|
|
- MP3 is 192 kbit/s.
|
|
|
|
### Limits
|
|
|
|
- Until payments exist everyone is on the free tier from the config:
|
|
50 MB, 10 minutes, 1 active job, at most 20 queued free jobs. The daily
|
|
quota arrives with the entitlement resolver in Phase 2.
|
|
- The Telegram upload ceiling (`TELEGRAM_MAX_UPLOAD_MB`, 50 on the cloud Bot
|
|
API) always caps the size, whatever the tier allows.
|
|
- Limits are checked twice: on the metadata before queueing, and by the
|
|
worker on the real file. Metadata is often incomplete.
|
|
- Live streams are refused.
|
|
|
|
### Queue
|
|
|
|
- **Retry:** a retryable failure is retried once (`QUEUE_MAX_ATTEMPTS=2`).
|
|
A retried job keeps its original place in the queue.
|
|
- **Lease expiry** (worker died) counts as an attempt, which bounds the
|
|
damage of a job that crashes workers. A **clean worker shutdown** hands the
|
|
job back without spending an attempt.
|
|
- **Cancel:** a queued job is cancelled at once. A running job is flagged
|
|
and stops at the worker's next heartbeat (10 seconds by default).
|
|
- **Wait estimate** is jobs ahead (plus half of the running ones) divided by
|
|
worker slots, times the average duration of the last 20 jobs, or 45
|
|
seconds when there is no history. It is deliberately rough.
|
|
|
|
### Delivery
|
|
|
|
- The stored file is deleted as soon as every requester has it. Keeping
|
|
files is the job of the cache in Phase 3.
|
|
- A failed send to Telegram is retried up to 3 times, then reported.
|
|
- If the core stops during an upload, the delivery is retried on the next
|
|
start. A crash at exactly the wrong moment can therefore send a file
|
|
twice; losing it was judged worse.
|
|
|
|
### Safety
|
|
|
|
- Links to localhost, private, link-local and similar addresses are
|
|
rejected before yt-dlp sees them. This is a first line of defense, not a
|
|
full SSRF guard: a public hostname can still resolve to a private address.
|
|
Workers should run in a network that cannot reach internal services.
|
|
- Raw yt-dlp output never reaches users. It is redacted (URLs lose
|
|
credentials and signed query values) and kept for owner logs.
|
|
- The bot token and the webhook secret are removed from all log output by
|
|
the logger itself, because HTTP client errors quote request URLs and Bot
|
|
API URLs contain the token.
|
|
- No age verification or KYC flow exists or is planned. Content a site
|
|
gates behind a login is reported as "needs a login".
|
|
|
|
## Phase 2
|
|
|
|
### Verified LNbits facts
|
|
|
|
Read from the LNbits source at `v0.12.12` (the target) and `v1.7.1` (current).
|
|
|
|
- `POST /api/v1/payments` with the invoice key creates an invoice. Fields
|
|
used: `out=false`, `amount`, `unit="sat"`, `memo`, `expiry`, `webhook`.
|
|
v0.12 answers with `payment_request`, v1.x with the payment object and
|
|
`bolt11`. The client reads either.
|
|
- `GET /api/v1/payments/{payment_hash}` answers `{"paid": bool, ...}` in
|
|
both versions, and 404 for an unknown hash.
|
|
- The webhook is a single `POST` of the payment as JSON. **It is not signed
|
|
and it is not retried.** This shaped the design: a webhook is treated as a
|
|
hint, the payment is confirmed with LNbits before anything is credited,
|
|
and polling is a required fallback, not an optimization.
|
|
- Only the invoice key is needed. The bot never holds a key that can spend.
|
|
|
|
### Entitlement
|
|
|
|
- **Order** is exactly as specified: own pass, group pass, group credits,
|
|
own credits, free. A one-off payment for the file sits in front of all of
|
|
them, since it was bought for exactly that download.
|
|
- **Credits are used before the free tier.** A user with enough credits pays
|
|
per download even for a small file that the free tier would have allowed.
|
|
This follows the specified order literally. What they get for it is the
|
|
paid limits and the priority lane.
|
|
- **Credits cost a flat price per download** (`PRICE_CREDIT_DOWNLOAD`, 50
|
|
sats), whatever the size. "Per extra" spending is "Skip the queue".
|
|
- **All paid sources share one tier** (`limits.paid`) and one lane. Pass
|
|
holders, credit payers and one-off payers queue first come first served
|
|
among themselves.
|
|
- **Group wallets** are in the resolver and its tests now. They get their
|
|
data in Phase 5; until then every request resolves as in a private chat.
|
|
|
|
### Limits
|
|
|
|
- **A day** is a UTC calendar day, for both the download quota and the
|
|
volume cap.
|
|
- The **daily download quota** counts when a job is queued and is given back
|
|
when the download fails or is cancelled. The **daily volume** counts bytes
|
|
actually delivered. A user can therefore overshoot the volume cap by one
|
|
file, since the size is only known afterwards.
|
|
- Quota and volume are tracked per requester, also when a group pays.
|
|
- **Rate limit:** 10 links per minute per user and 30 per group, in memory.
|
|
A restart forgets it.
|
|
|
|
### Payments
|
|
|
|
- **Invoices are personal** and only ever appear in the private chat. In a
|
|
group, a refused download shows a "Buy for me" deep link instead.
|
|
- **"Open in wallet"** needs `PUBLIC_URL`. Telegram accepts only http and
|
|
https in URL buttons, so the button opens a small page of the core that
|
|
forwards to the `lightning:` link. Without `PUBLIC_URL` the button is
|
|
left out and the invoice is still scannable and copyable.
|
|
- **Copyable BOLT11:** the invoice is in a code block in the caption, where
|
|
one tap copies it. Telegram's dedicated copy button is limited to 256
|
|
characters, which is shorter than most invoices.
|
|
- **No job exists before payment.** An over-limit download is queued only
|
|
when its invoice settles, so "unpaid jobs are cancelled" holds by
|
|
construction: there is nothing to cancel.
|
|
- **A payment that arrives late is still honored.** If an invoice is paid
|
|
after it expired or was cancelled, it is credited when detected (invoices
|
|
closed within the last hour are polled; all of the last 7 days are checked
|
|
at startup).
|
|
- **An invoice does not expire while LNbits is unreachable.** It could have
|
|
been paid, and telling a payer that a paid invoice expired is worse than
|
|
leaving one open a little longer.
|
|
- **A payment whose purpose is gone becomes credits.** If a one-off or
|
|
skip-the-queue payment settles after the download finished or the card
|
|
expired, the same amount is credited to the payer's balance and they are
|
|
told. Lightning payments cannot be sent back.
|
|
- **One-off price** is `base + step * started 100 MB`, with an unknown size
|
|
priced as 200 MB.
|
|
|
|
### Refunds
|
|
|
|
- A download is retried once automatically. When it then fails, is
|
|
cancelled, or cannot be sent to Telegram, what it cost is given back:
|
|
credits return to the wallet they came from (also group wallets), a
|
|
one-off payment becomes credits on the payer's wallet, and the slot in the
|
|
daily quota is freed.
|
|
- **A pass is not extended automatically** after a failed download. Under a
|
|
pass a download costs nothing, so there is nothing to refund except the
|
|
quota slot, which is freed. Extending a pass exists as an operation
|
|
(`ExtendPass`) for the owner's `/refund` command.
|
|
- "Skip the queue" is not refunded when the promoted download later fails.
|
|
The priority was delivered.
|
|
|
|
### Skip the queue
|
|
|
|
- The button appears on the **queued status** of a job in the free lane,
|
|
not on the link card. On the card there is no job yet to move. It costs
|
|
`PRICE_SKIP_QUEUE`, paid from credits when the balance covers it and by
|
|
invoice otherwise.
|
|
|
|
### Reserved free slot
|
|
|
|
- The reservation applies when the fleet has at least two slots. With a
|
|
single slot, reserving it would lock paying users out, so paid simply goes
|
|
first.
|
|
- Fleet capacity is the sum of the capacities of workers that claimed in
|
|
the last 90 seconds. It is kept in memory and rebuilt within seconds of a
|
|
restart.
|
|
|
|
### Gift codes, Cashu, referrals
|
|
|
|
- Gift codes are fully implemented: credits or a pass, a maximum number of
|
|
uses, an optional expiry, one use per user.
|
|
- **Cashu is behind the `billing.Cashu` interface and not implemented.**
|
|
`/redeem` recognizes a Cashu token and answers that tokens are not
|
|
accepted. Redeeming means melting the token at its mint into a Lightning
|
|
payment to our own invoice, with fee reserve and input fee handling and
|
|
V4 tokens in CBOR. That is not "straightforward" enough to ship without a
|
|
real mint to test against.
|
|
- **Referral:** the link is `t.me/<bot>?start=ref_<user id>`. Only a user
|
|
who is new to the bot can be referred, once, and not by themselves. The
|
|
reward (200 sats) is credited on their first paid purchase. Donations do
|
|
not count as a purchase.
|
|
- **Telegram Stars** as a second payment method is not built ("optional
|
|
later" in the brief).
|
|
|
|
## Phase 3
|
|
|
|
### Cache key
|
|
|
|
- The key is yt-dlp's `extractor` (lower case, without a `:suffix`) plus its
|
|
video `id`, plus the profile. Two URLs of the same video share an entry.
|
|
- **Fallback is a hash of the URL, not of the content.** The generic
|
|
extractor names a file after the end of its URL, so different sites
|
|
collide; for it, and whenever an ID is missing, the key is derived from
|
|
the normalized URL. A hash of the file would only be known after the
|
|
download, too late to find a hit.
|
|
- Entries are per bot (`bot_id`), because a Telegram `file_id` only works
|
|
for the bot that received it.
|
|
|
|
### What a cache hit is, and is not
|
|
|
|
- A hit goes through `service.Start` like any request: same entitlement,
|
|
same size and duration checks, same daily quota and volume, same active
|
|
job limit and queue cap, same price. It then becomes a job that is created
|
|
already finished, so only the worker is skipped.
|
|
- **A hit is judged by the real file**, not by metadata estimates. A file a
|
|
pass holder put in the cache is refused to a free user it is too large
|
|
for, even when the metadata gave no size. This can also go the other way:
|
|
if an estimate was too high, the cached file is allowed.
|
|
- A resend from `/history` is a download like any other and counts.
|
|
|
|
### Sharing a download (singleflight)
|
|
|
|
- A second requester for a result that is queued or running joins that job.
|
|
Each requester keeps their own caps: when the file is finished, it is
|
|
checked against each one's limits before it is sent to them.
|
|
- **A queued job is lifted** to the looser caps and to the paid lane when a
|
|
paying requester joins. A free user who asked first benefits from that.
|
|
- **A running job is only joined when it covers the newcomer's caps.**
|
|
Otherwise the newcomer gets a job of their own, because the running one
|
|
was started with a size cap that could cut their file short.
|
|
- Content that is not cacheable is never shared between users.
|
|
|
|
### Stored copies
|
|
|
|
- A job's stored file becomes the cache's stored copy in place. Nothing is
|
|
moved or copied.
|
|
- The result enters the cache right after the first successful send, before
|
|
the requester sees "Done".
|
|
- A download that worked but could not be sent to anyone is still cached.
|
|
|
|
### Derive
|
|
|
|
- A lower video profile or audio is transcoded from a stored higher profile
|
|
when one exists (`CACHE_DERIVE`). The nearest profile above is used.
|
|
- **Alias instead of transcode:** when the stored higher profile is already
|
|
no taller than the requested cap (a 360p video asked for as "720"), it is
|
|
the same file yt-dlp would fetch and is served as a plain hit.
|
|
- A derive job that fails becomes a normal download of that profile, at no
|
|
cost in attempts.
|
|
- Transcoding is h264 `veryfast` CRF 23 with AAC 128k, MP3 at 192k.
|
|
|
|
### Self-healing
|
|
|
|
- When Telegram refuses a cached `file_id`: the id is cleared, the stored
|
|
copy is uploaded again and the new id is saved. Without a usable stored
|
|
copy the entry is dropped and the job goes to the queue as a fresh
|
|
download. The requester was admitted and charged once and stays so.
|
|
|
|
### Eviction and TTL
|
|
|
|
- TTL by extractor: stable sites 30 days, ephemeral ones 6 hours, the rest
|
|
7 days. The lists are configurable prefixes of extractor names.
|
|
- Over budget, stored copies are evicted in order of
|
|
`last_hit + min(hits, 48) hours`: each hit protects an entry like one more
|
|
hour of recency, up to two days.
|
|
- **Eviction removes the stored copy and keeps the file_id.** The entry
|
|
still serves instant resends; it just cannot heal or be transcoded.
|
|
- Never cached: live streams, and anything whose yt-dlp `availability` is
|
|
not public or unlisted (private, members-only, needs a login). The bot has
|
|
no cookie support yet, so "downloads that needed cookies" cannot occur;
|
|
the availability check is what will cover them.
|
|
|
|
### Takedown
|
|
|
|
- `/purge <link>` or `/purge extractor:id` deletes the stored files of
|
|
every profile of the video, clears their file_ids, marks the entries
|
|
blocked and adds the key to the blocklist. A blocked key is refused before
|
|
any download and can never be cached again. Takedown markers have no TTL.
|
|
- The site blocklist also covers subdomains.
|
|
|
|
### Playlists
|
|
|
|
- A playlist link shows a card with the item count and the formats. Each
|
|
item becomes its own request, job and cache entry.
|
|
- **Items start one after another** as the requester's active job slots
|
|
free up, instead of all at once. The per-user active job limit therefore
|
|
holds for playlists too, and one long playlist cannot fill the queue.
|
|
- The per-request cap is by tier: 3 items free, 25 paid. Each item counts
|
|
against the daily quota.
|
|
- `/cancel` also cancels items that have not started.
|
|
- An item that is itself a list is skipped.
|
|
|
|
### Subtitles and history
|
|
|
|
- `/subs` lists written subtitles before automatic captions, with the
|
|
requester's language first and marked. At most 24 languages are shown.
|
|
- `/history` shows the last 10 delivered files.
|
|
|
|
## Phase 4
|
|
|
|
### What could and could not be run here
|
|
|
|
- **Docker was not available on the build machine.** The user that built
|
|
this has no access to the Docker socket, and rootless Docker is missing
|
|
its helpers. So `deploy/Dockerfile` and `docker-compose.yml` were written
|
|
and checked with `docker compose config` (which parses, merges and
|
|
interpolates them without a daemon), but **no image was built and no
|
|
container was run**. Treat the first `docker compose up --build` as the
|
|
real test of those files.
|
|
- **The acceptance scenario itself was run for real**, with the same
|
|
binaries as separate OS processes: one core, two workers over the HTTP
|
|
worker protocol, the real yt-dlp downloading a rate-limited public file,
|
|
and `kill -9` on the worker that held the job. The core logged the
|
|
expired lease, requeued the job, and the second worker delivered the
|
|
file. `deploy/acceptance/kill-worker.sh` does this in both modes;
|
|
`MODE=compose` is the untested one.
|
|
- **Postgres was tested against a real Postgres 15**, started as a private
|
|
instance. The whole test suite, end-to-end flows included, passes on
|
|
SQLite and on Postgres.
|
|
- **S3 was tested against an in-memory S3 server** (`gofakes3`), not
|
|
against Garage, MinIO or AWS. The client is `minio-go`, which those
|
|
servers are routinely used with.
|
|
- **The local Bot API server was not run.** Support for it is
|
|
configuration: `TELEGRAM_API_URL` and `TELEGRAM_MAX_UPLOAD_MB`. Uploads
|
|
are streamed, never buffered, so a 2 GB file does not need 2 GB of RAM.
|
|
|
|
### Database
|
|
|
|
- One schema and one set of queries for both engines. Queries use `?`
|
|
placeholders that are rewritten to `$n` for Postgres.
|
|
- **Postgres needed two explicit locks that SQLite gives for free.**
|
|
SQLite runs write transactions one at a time; Postgres runs them side by
|
|
side. A per-user advisory lock guards "count active jobs, then insert
|
|
one", and a row lock on the job guards every "read the status, then act
|
|
on it". Without the second, cancelling a job could cross with a worker
|
|
claiming it and leave a job running for nobody. The test suite found
|
|
that on its first Postgres run.
|
|
- One core per database. Nothing coordinates two cores.
|
|
- No data migration between SQLite and Postgres.
|
|
|
|
### Workers
|
|
|
|
- **Tokens** are random, per worker, stored as SHA-256 hashes, and
|
|
revocable. They are created with `core worker add <name>` (a CLI
|
|
subcommand rather than a bot command, so a token never passes through
|
|
Telegram) or listed in `WORKER_TOKENS` for fixed setups.
|
|
- A worker's identity comes from its token. The `worker_id` field in a
|
|
request body is ignored.
|
|
- **Scope:** a token can claim, heartbeat, complete, fail and upload, and
|
|
only for jobs leased to that worker. The storage key of a result is
|
|
chosen by the core.
|
|
- **Tags** are matched exactly: a job goes to a worker that has all of the
|
|
site's tags. A claim looks at the first 25 queued jobs to find one the
|
|
worker qualifies for, so a job waiting for a rare tag does not block the
|
|
queue behind it.
|
|
- **Draining** is a flag on the core, checked on every claim. A draining
|
|
worker gets neither jobs nor lookups.
|
|
- **Lease expiry counts as an attempt; a clean shutdown does not.**
|
|
- **Fleet capacity** for the reserved free slot is still counted in memory
|
|
from recent claims.
|
|
|
|
### Link lookups
|
|
|
|
- With remote workers only, the core has no yt-dlp, so lookups for cards
|
|
are handed to workers through their claim calls (`PROBE_MODE`). They are
|
|
held in memory: a core restart drops a pending lookup and the user sends
|
|
the link again. Workers keep two extra claim requests open for lookups,
|
|
so cards stay quick when all download slots are busy.
|
|
- Lookups follow the same tag rules as downloads.
|
|
|
|
### Storage
|
|
|
|
- With S3, workers upload through presigned URLs and the core is not in
|
|
the data path. With local disk, they stream the file to the core.
|
|
- An upload of unknown size is spooled to a temp file first, to avoid
|
|
chunked streaming uploads that not every S3 compatible server accepts.
|
|
- The core's upload endpoint enforces the job's size cap while receiving.
|
|
|
|
### yt-dlp updates
|
|
|
|
- Each worker updates its own yt-dlp on a schedule (`yt-dlp -U`).
|
|
`/ytdlp update` is delivered to workers with their next claim, so it
|
|
reaches every connected worker within seconds.
|
|
|
|
## Phase 5
|
|
|
|
### Groups
|
|
|
|
- **Groups are recorded** from `my_chat_member` updates, and also the first
|
|
time a command is used in one, in case that update was missed.
|
|
- **Admin rights come from Telegram only** (`getChatMember`), cached for
|
|
five minutes per group and user. A change of admins can therefore take up
|
|
to five minutes to reach the bot. The cache for a group is dropped when
|
|
the bot's own status in it changes.
|
|
- **Anonymous admins are not supported for commands.** A message sent "as
|
|
the group" carries no user to verify. Buttons work, because a button
|
|
press always carries the real user.
|
|
- **The settings panel is visible to every member**, so each button press
|
|
is checked again. A member who presses gets a notice and nothing changes.
|
|
- **A switched-off bot is silent in that group**, except for `/settings`
|
|
from an admin, which is how it is switched on again.
|
|
- **"Pass holders"** means: the requester has a pass of their own, or the
|
|
group has one, or they are an admin.
|
|
- **Spending rule "capped"** counts group credits a member spent today
|
|
(UTC). The first time it is chosen in the quick settings the cap defaults
|
|
to four downloads' worth.
|
|
- **Site lists** match a host and its subdomains. With an empty allow list
|
|
every site is allowed. At most 50 entries per list.
|
|
- **Group size and duration caps** can only lower what the group's pass or
|
|
credits allow, and only apply when the group pays. They are set from the
|
|
Mini App (Phase 6), not from a command.
|
|
- **Group language** overrides each member's language for everything the
|
|
bot says in that group.
|
|
- **Default quality** (group or personal) skips the card and starts that
|
|
format at once.
|
|
- **"Delete command messages"** needs the bot to be an admin with the right
|
|
to delete. Without it the delete fails quietly.
|
|
- **Auto-detect** takes the first link of a message. It needs the bot to
|
|
see ordinary messages (admin, or group privacy off), which the bot says
|
|
when the setting is turned on.
|
|
|
|
### Paying for a group
|
|
|
|
- **Anyone can pay into a group wallet.** What is bought belongs to the
|
|
group. Invoices only ever appear in the payer's private chat; the group
|
|
shows deep links (`?start=gw_<chat id>`) with the group pre-selected.
|
|
- A purchase for a group does not auto-start the download that was refused.
|
|
The requester presses the format button again.
|
|
- Refunds for downloads paid with group credits go back to the group.
|
|
|
|
### Owner tools
|
|
|
|
- Owner commands exist only in a private chat with a configured owner. For
|
|
everyone else, and for owners in groups, they are unknown commands.
|
|
- `/grant <id> <day|week|month>` and `/credit`, `/refund` take a user ID,
|
|
or a negative chat ID for a group. `/refund <id> pass <duration>` extends
|
|
a running pass.
|
|
- `/grant code ...` creates gift codes.
|
|
- `/broadcast` shows a preview and sends only after the owner presses the
|
|
confirm button. It goes to every user who is not banned, about 20
|
|
messages per second.
|
|
- `/maint on` refuses new downloads for everyone but owners. Running jobs
|
|
finish.
|
|
- `/reload i18n` needs `LOCALES_DIR`; catalogs built into the binary cannot
|
|
change at runtime.
|
|
- `/privacy`, `/terms` and `/support` are short texts in the catalog.
|
|
Replace them with your own before running a public bot.
|
|
|
|
## Phase 6
|
|
|
|
### Verified Telegram Mini App facts
|
|
|
|
Checked against https://core.telegram.org/bots/webapps on 2026-11-18.
|
|
|
|
- The page must load `https://telegram.org/js/telegram-web-app.js` in its
|
|
head. It provides `window.Telegram.WebApp`.
|
|
- `initData` is a query string. It is valid when
|
|
`hex(HMAC_SHA256(key=HMAC_SHA256(key="WebAppData", msg=bot_token), msg=data_check_string))`
|
|
equals its `hash` field, where the check string is every other field as
|
|
`key=value`, sorted by key, joined with line feeds.
|
|
- `start_param` in initData carries the `startapp` value of a
|
|
`https://t.me/<bot>?startapp=<value>` link. Such links open the bot's
|
|
main Mini App, which is set in @BotFather. No Bot API method sets it.
|
|
- A launch from an inline keyboard `web_app` button has no start
|
|
parameter. Those buttons work in private chats only.
|
|
- Theme colors arrive as CSS variables (`--tg-theme-...`), safe areas as
|
|
`--tg-safe-area-inset-...` and `--tg-content-safe-area-inset-...`.
|
|
- `openLink` opens a URL in the system browser. The page does not say that
|
|
it accepts schemes other than http and https.
|
|
|
|
### Authentication
|
|
|
|
- Every API call carries `Authorization: tma <initData>`. The core
|
|
validates it on each request. There is no session, cookie or token of
|
|
our own, so a call can never be more trusted than Telegram's signature.
|
|
- initData older than 24 hours is refused, and so is one dated more than
|
|
five minutes ahead. Telegram does not refresh initData while an app
|
|
stays open, so an app left open for a day has to be opened again. A
|
|
shorter window would log people out mid-use; no window would make a
|
|
leaked string valid forever.
|
|
- The check string is tried as documented (all fields but `hash`), and
|
|
also without `signature`. Either way only the bot token can produce the
|
|
hash.
|
|
- A call without valid initData gets `401` and one sentence in the
|
|
language of the browser. A banned user gets `403`.
|
|
- The API exists only when `MINIAPP_ENABLED=true`. That setting requires
|
|
an https `PUBLIC_URL` and the core refuses to start otherwise (plain
|
|
http is accepted for localhost, for development).
|
|
|
|
### What the app can do, and where the result goes
|
|
|
|
- A web page cannot receive files. Downloads started in the app, and
|
|
resends from its history, post their status message and file in the
|
|
user's private chat with the bot. The app says so and shows progress on
|
|
the Queue tab.
|
|
- Downloads from the app are personal: they resolve entitlement like a
|
|
private chat (own pass, own credits, free), never a group's wallet.
|
|
- The front end is never trusted. It shows every format and every
|
|
product; the core applies limits and prices when the call arrives. A
|
|
price sent by the client is ignored for passes, and credits must be an
|
|
amount the billing service accepts.
|
|
- The shop sells passes and credits. "Pay for this file only" needs a
|
|
refused download behind it and stays in the chat; "skip the queue" is
|
|
the Prioritize button on the Queue tab. Donations stay in the chat.
|
|
- Buy, step 1: the targets offered are the user and the groups they
|
|
administer. The API accepts any group the bot is in, the same rule as in
|
|
chat, where anybody may pay for a group.
|
|
- Payment detection: the app asks `GET /app/api/purchase/<id>` every 2.5
|
|
seconds, and each call asks LNbits. This works without a webhook. A
|
|
paid purchase also produces the usual "Paid" message in the chat.
|
|
- The QR code is made by the core and sent as a PNG data URL, so the app
|
|
ships no QR library.
|
|
- "Open in wallet" goes through the existing `/pay/<id>` page with
|
|
`openLink`, because `openLink` is only documented for web addresses.
|
|
- Queue and history are polled (queue every 2 seconds while visible).
|
|
There is no push channel; polling is simple and the numbers are small.
|
|
- "Audio only" on the Me tab is the default format MP3. Turning it off
|
|
returns to "ask every time".
|
|
- Rate limits: link lookups share the chat's budget (`RATE_USER_PER_MINUTE`),
|
|
starts and resends get twice that, invoices 10 per minute per user.
|
|
|
|
### Groups in the app
|
|
|
|
- Telegram has no "list my groups" call. The Groups tab shows groups where
|
|
the bot is present, has seen the user at least once, and Telegram
|
|
confirms the user as an admin right now (cached for five minutes, like
|
|
in chat).
|
|
- Every group endpoint checks admin status again. A demoted admin loses
|
|
access; a group the bot left is "not found" for everybody.
|
|
- Settings are saved as a whole and validated field by field. Site lists
|
|
accept a host name or a pasted link and store the host.
|
|
- Size and duration caps for a group can only be set here. They can lower
|
|
the tier's limit, never raise it; a higher value is stored as the tier's.
|
|
- Usage by member covers the last 7 days.
|
|
|
|
### Front end
|
|
|
|
- Vite, React and TypeScript, no router and no UI library. About 77 KB of
|
|
JavaScript after gzip.
|
|
- The build output `web/miniapp/dist` is committed, so `go build` and
|
|
`go install` work without Node.js. `make miniapp` rebuilds it. A Go test
|
|
fails when it is older than its sources. The Docker build rebuilds it.
|
|
- File names are stable (`assets/app.js`) to keep diffs small. The core
|
|
sends `Cache-Control: no-cache` with an ETag of the content, so clients
|
|
revalidate and pick up a new build at once.
|
|
- A Content-Security-Policy allows scripts from the app itself and
|
|
telegram.org only, and framing by Telegram's web clients only.
|
|
- The lookup card in the app has no thumbnail. An image loaded by the
|
|
browser would reveal the user's IP address to the video site; in chat the
|
|
thumbnail is fetched by Telegram's servers instead.
|
|
- All text comes from the catalog over the API. A test fails when the app
|
|
asks for a key the catalog lacks, or when markup contains a literal
|
|
sentence.
|
|
- Right to left: the direction comes from the language (`ar`, `he`, `fa`,
|
|
`ur` and a few more are known as RTL), and the style sheet uses logical
|
|
properties. No RTL catalog ships yet, so this is tested by forcing the
|
|
direction in the browser test.
|
|
- The bot's menu button is left alone. Replacing it with the app would
|
|
hide the command list, which is translated per language.
|
|
- The built-in catalogs decide the language list on the Me tab. The app
|
|
follows the user's language setting, or the Telegram language when none
|
|
is set, and reloads its texts when it changes.
|
|
|
|
### What could and could not be run here
|
|
|
|
- The API tests run on SQLite and Postgres like the rest of the suite.
|
|
- The browser test (`make miniapp-e2e`) ran here in headless Chromium:
|
|
lookup and download, cancel, resend, buying a pass, group settings,
|
|
group top-up, preferences, a deep link, forced RTL, and the notice
|
|
outside Telegram. It is not part of `make check`, because it needs a
|
|
browser.
|
|
- The app was not opened inside a real Telegram client. The bridge script
|
|
is replaced by a stand-in in the browser test. Theme colors, the back
|
|
button and haptics follow the documentation but were not seen on a
|
|
phone.
|
|
- `npm audit` reports an advisory for `picomatch`, a dependency of Vite.
|
|
It is a build tool and is not part of what the core serves.
|
|
|
|
### Fixed on the way
|
|
|
|
- A worker used one scratch directory per job. When a download failed and
|
|
the retry started on another slot of the same worker before the first
|
|
slot had finished reporting, the first slot's cleanup deleted the
|
|
retry's file, and the job failed with an internal error. It showed up as
|
|
a rare test failure on a busy machine. Every attempt now has its own
|
|
directory, and a test holds the two slots in exactly that order.
|
|
|
|
## Phase 7
|
|
|
|
### Verified Bot API facts
|
|
|
|
Checked against https://core.telegram.org/bots/api (Bot API 10.4) on
|
|
2026-11-18, and against telego v1.13.0.
|
|
|
|
- `setMyCommands` takes at most 100 commands, a scope, and a two-letter
|
|
ISO 639-1 `language_code`. Without a code the list applies to users
|
|
whose language has no list of its own. A command is 1 to 32 lowercase
|
|
letters, digits or underscores; a description 1 to 256 characters.
|
|
- Telegram picks the menu in this order: chat scope with the user's
|
|
language, chat scope, then all private chats (or, in groups, chat
|
|
administrators, chat, all chat administrators, all group chats), then
|
|
default, each with and then without the language.
|
|
- `setMyName` (0 to 64 characters), `setMyDescription` (0 to 512, shown
|
|
in an empty chat) and `setMyShortDescription` (0 to 120, shown on the
|
|
profile and when the bot is shared) take the same `language_code`.
|
|
- `deleteMyCommands` removes the list of a scope and language.
|
|
|
|
### Languages
|
|
|
|
- English is the source and the fallback. Spanish and Dutch ship
|
|
complete. A user gets their Telegram language when a catalog matches
|
|
it, regional variants included (es-PY uses Spanish), and English
|
|
otherwise. `/language` (or the Mini App) overrides that per user;
|
|
`/grouplang` per group.
|
|
- Spanish: neutral Latin American with "tú". Paraguay speaks "vos", but
|
|
"tú" is what written Spanish across the region expects and is read
|
|
without friction in Paraguay; the vocabulary avoids words that sound
|
|
odd there. No opening `¿` or `¡`, as asked; a test enforces it.
|
|
- Dutch: informal "je".
|
|
- Owner texts are translated too. Owners pick their language like anyone.
|
|
- Command names, their arguments (`/spending admins`) and product IDs
|
|
stay English in every language. The bot parses them.
|
|
- The invoice memo, which wallets show, is the brand name plus the
|
|
product in the payer's language.
|
|
|
|
### Menus and profile
|
|
|
|
- At startup the core publishes three menus in every language: private
|
|
chats (download, account and preference commands), group members
|
|
(download commands, the group wallet and pass) and group admins (the
|
|
same plus the settings commands). Owner commands are never listed.
|
|
`/app` is listed only when the Mini App is on.
|
|
- The source language is published without a language code, so it is
|
|
also the menu for languages without a catalog.
|
|
- Telegram chooses menus by the language of the user's app, not by the
|
|
bot's setting. So when a user picks a language in the bot, the core
|
|
sets a menu for that private chat alone; "follow my Telegram language"
|
|
deletes it. `/grouplang` does the same for the group's member and
|
|
admin menus. These calls are limited to six per minute per chat.
|
|
- Chat menus are not rewritten when a catalog changes. They refresh the
|
|
next time that user or group changes language. The general menus are
|
|
rewritten at every start and on `/reload i18n`.
|
|
- The bot's name, description and short description are set per
|
|
language from `profile.*`, but only when the text changed since the
|
|
last time it went through, because Telegram limits these calls
|
|
hard. `TELEGRAM_SET_PROFILE=false` leaves what was set in @BotFather.
|
|
A change made in @BotFather is overwritten only when the catalog text
|
|
changes.
|
|
|
|
### Formatting
|
|
|
|
- Numbers use the language's grouping and decimal marks (Go's
|
|
`golang.org/x/text`, and `Intl` in the Mini App): "1.000 sats",
|
|
"10,0 MB" in Spanish and Dutch.
|
|
- Dates are written from the catalog (`format.date`, `format.datetime`,
|
|
`format.months`): "18 nov 2026, 12:05 UTC". Always UTC, and labeled:
|
|
the bot does not know the reader's time zone. Limits reset at midnight
|
|
UTC, which the texts say.
|
|
- Durations in words use the plural rules of the language ("5 minutos").
|
|
Media lengths are written as 4:05 everywhere.
|
|
|
|
### Completeness check
|
|
|
|
- `locales/catalog_test.go` is the check CI runs (`make i18n-check`).
|
|
For every catalog it fails on: a message missing or extra compared with
|
|
the source, a plural that is plain elsewhere or lacks `one`, a changed
|
|
set of placeholders, HTML tags or commands, broken braces, empty
|
|
texts, stray spaces, em dashes, inverted marks in Spanish, menu and
|
|
profile texts over Telegram's limits, button labels over 40
|
|
characters, a month list that is not twelve long, and a duplicate
|
|
language name. It also flags longer texts identical to English, except
|
|
where they are meant to be (the brand name in the invoice memo).
|
|
- It also reads the code. Every message of the source must be used,
|
|
either by its full ID or by a prefix or suffix the code builds IDs from
|
|
(`"error." + code`, `name + ".list"`), and every ID-shaped string in the
|
|
code whose table exists must be in the catalog. Tests are not counted.
|
|
`web/miniapp/embed_test.go` does the same for the Mini App.
|
|
- `.github/workflows/ci.yml` runs this, the whole suite with the race
|
|
detector, the suite on Postgres, and the Mini App build and browser
|
|
test. It was written for GitHub Actions and has not run there yet;
|
|
every step in it was run here by hand.
|
|
|
|
### Pseudo-locale
|
|
|
|
- `I18N_PSEUDO=true` makes `en-XA` from the English catalog at load time:
|
|
accented letters, brackets, a third longer, with placeholders, tags,
|
|
entities, commands, links and mentions kept. Plurals and dates keep
|
|
working.
|
|
- It is hidden from users and offered to owners only, in `/language`,
|
|
`/grouplang` and the Mini App. It is never published to Telegram
|
|
(not a two-letter code).
|
|
|
|
### Fixed on the way
|
|
|
|
- The test helper that sets up a waiting download picked the first "In
|
|
the queue" status edit after the second user's press, from any chat.
|
|
Under load a late edit of the first user's status could match, and the
|
|
test then pressed the wrong button. It now matches the second user's
|
|
chat only. This is the likely cause of the one Postgres failure of
|
|
`TestSkipTheQueueWithInvoice` reported in Phase 4, which uses the same
|
|
helper. The bot itself was right in both cases.
|
|
|
|
## Phase 8
|
|
|
|
### Verified widget facts
|
|
|
|
Checked on 2026-11-18 against https://core.telegram.org/bots/api (Bot API
|
|
10.4, released 2026-11-09), https://core.telegram.org/bots/widgets, and
|
|
telego v1.13.0, which has `SendWidget`, `EditMessageWidgetData`,
|
|
`AnswerWidgetQuery` and `Update.WidgetQuery`.
|
|
|
|
- `sendWidget` sends one HTML document: at most 32768 bytes, and at most
|
|
4096 bytes after zlib at level 9. It takes `chat_data` and
|
|
`public_data` (1024 bytes each), a caption, `allow_queries` and the
|
|
usual `reply_markup`.
|
|
- In production, widgets work only in the private chat with the bot, and
|
|
cannot be forwarded. Groups, inline mode and forwards are test server
|
|
only.
|
|
- The widget runs in a sandbox (QuickJS), not a browser: no network at
|
|
all, no logical CSS properties, no `color-mix()`, no form controls but
|
|
`<button>`, `copyText` up to 256 characters, `openLink` URLs up to 256.
|
|
The theme arrives as `--tg-theme-*` variables.
|
|
- Only the bot changes a widget's state, with `editMessageWidgetData`,
|
|
which counts against the bot's sending limits like a message. The
|
|
widget learns of it through `chatDataChanged` and `publicDataChanged`.
|
|
- A widget asks the bot with `TelegramWidget.request(data)` (1 to 64
|
|
bytes, on a tap). The bot gets a `widget_query` update (it must be in
|
|
`allowed_updates`) and must answer with `answerWidgetQuery` within 15
|
|
seconds. `from` cannot be forged.
|
|
- Apps without widget support show the message as unsupported media with
|
|
its caption.
|
|
|
|
### Design
|
|
|
|
- Both widgets are an extra layer. The ordinary messages are still built
|
|
the same way; a widget replaces one only after `sendWidget` succeeded.
|
|
Every failure leads back to the ordinary message: a refused
|
|
`sendWidget`, a state that does not fit, a widget message that is gone.
|
|
- Job card: status, a progress bar (moving when the size is unknown), and
|
|
a Cancel button inside the widget. "Skip the queue" stays a normal
|
|
button under it, because it leads to a payment. The caption is the
|
|
title. Once the widget is up, the card with the format buttons is
|
|
deleted, so the chat shows one message per download, as before.
|
|
- Invoice: product, amount, QR code, a countdown from the invoice's expiry
|
|
(the device's clock), and the paid or expired state. The caption is the
|
|
ordinary invoice text, including the BOLT11 string in `<code>`, where a
|
|
tap copies it: `copyText` is limited to 256 characters, shorter than an
|
|
invoice. The ordinary buttons (open in wallet, check payment, cancel)
|
|
stay under it.
|
|
- The QR code is drawn by the widget from a bitmap the bot packs into the
|
|
public data (one bit per module, low error correction). A 290-character
|
|
invoice is 53 modules, 598 bytes of state. If an invoice is ever too
|
|
long for that, the QR is left out and the caption still carries the
|
|
invoice. A browser test draws a real code with the widget's own script
|
|
and decodes it back.
|
|
- The widgets' HTML does not depend on the language. Every text comes in
|
|
the state, translated by the bot, with the text direction.
|
|
- After a failure the next message tries again. Three failures in a row
|
|
pause widgets for ten minutes; a 404 or "method not found" (a Bot API
|
|
server without widgets) pauses them for an hour.
|
|
- Widget messages are recorded in `widget_messages`, so a restart can
|
|
still update them. Rows older than a week are deleted.
|
|
- Widgets are on by default (`TELEGRAM_WIDGETS=true`). The automatic
|
|
fallback makes that safe.
|
|
|
|
### Metrics and load test
|
|
|
|
- Prometheus metrics with `prometheus/client_golang` v1.25.0. The core
|
|
serves `/metrics` on its HTTP port (`METRICS_ENABLED`, on by default);
|
|
each worker on its health port. Values that live in the database or in
|
|
the services (queue, heartbeats, cache, invoices, Lightning) are read
|
|
at scrape time; events are counted as they happen.
|
|
- Errors per site use the host name as a label. The number of series
|
|
grows with the number of distinct sites people use, which is bounded in
|
|
practice; there is no limit in the code.
|
|
- The ledger check (`dlbot_wallets_mismatched`) reads every ledger row,
|
|
so it runs at most every ten minutes, and logs an error when it finds
|
|
a mismatch.
|
|
- The load test drives the real core and workers through the fake Bot
|
|
API, with a yt-dlp stand-in that takes a set time per download. It
|
|
measures the bot, not the sites or Telegram's upload speed.
|
|
- The example Prometheus configuration, alert rules and the Caddyfile were
|
|
not run here. Downloading `promtool` to check the rules was refused by
|
|
this environment's sandbox.
|
|
|
|
### What could and could not be run here
|
|
|
|
- Widget sending, updates, cancel requests, the fallback on a failed or
|
|
unknown `sendWidget`, the pause, and groups without widgets: tested end
|
|
to end against the fake Bot API.
|
|
- The widgets' HTML: rendered in headless Chromium with a stand-in for
|
|
`TelegramWidget`. That is a browser, not Telegram's sandbox, so it shows
|
|
that the scripts run and draw the right things, not how a phone draws
|
|
them.
|
|
- Not seen in a real Telegram client, and not sent through the real Bot
|
|
API: this environment has no bot token.
|
|
- Load test: 90 of 90 and 240 of 240 requests delivered (embedded worker;
|
|
three remote workers). Numbers in [MONITORING.md](MONITORING.md).
|
|
|
|
## Update round: flows, Stars, affiliate program
|
|
|
|
Decisions made while improving the flows and adding Telegram Stars and
|
|
the affiliate program. What was found and planned is in
|
|
[UPDATE_NOTES.md](UPDATE_NOTES.md).
|
|
|
|
### Phase 1: quick flow fixes
|
|
|
|
- **One message per job.** Once the file is in the chat, the status
|
|
message (the card, the placeholder or the status widget) is deleted.
|
|
If Telegram refuses the delete, the message is cut down to "Sent.".
|
|
`editMessageMedia` could have turned the status into the file instead,
|
|
but the file then could not quote the link message in groups, and an
|
|
upload through an edit cannot fall back to a document. Deleting is
|
|
simpler and works in every case.
|
|
- **Quotes.** Answers in private chats never quote the user's message;
|
|
groups still do. The rule sits in one place (`replyParams`) and uses
|
|
the chat ID: private chats have the user's positive ID, groups have
|
|
negative IDs.
|
|
- **Queue noise.** "Position N" is shown when the expected wait is above
|
|
`QUEUE_NOTICE_THRESHOLD_SECONDS` or somebody is queued ahead. Position
|
|
counts queued jobs ahead, as before. The wait estimate now gives 0 when
|
|
a worker slot is free, and ignores a job that was claimed between being
|
|
loaded and being measured. Before, such a job could count itself as
|
|
running and show a wait of half a job.
|
|
- **Edit throttle.** Every status message is edited at most once per
|
|
2.5 s, phase changes included. A state that arrives too soon is kept
|
|
and shown when the gap is over. It is never dropped, so the last state
|
|
before the file arrives is always correct.
|
|
- **Caption.** The caption has the title, then the uploader and duration,
|
|
then a short link without tracking parameters, then the optional
|
|
`via @bot` line. A title counts as generic when it is empty, the video
|
|
ID, the uploader's name, a site placeholder ("Video", "Instagram") or
|
|
"Video by ...". It is then replaced by "uploader · upload date" in the
|
|
reader's date format. The removed parameters are: `utm_*`, `igsh`,
|
|
`igshid`, `jplx`, `fbclid`, `gclid`, `dclid`, `gbraid`, `wbraid`,
|
|
`msclkid`, `yclid`, `twclid`, `ttclid`, `si`, `mc_cid`, `mc_eid`,
|
|
`mibextid`, `ref_src`, `ref_url`, `_hsenc`, `_hsmi`, `feature`,
|
|
`share_id` and `rdt`. On X and Twitter `s` and `t` are removed too, and
|
|
on TikTok its share parameters. Everything else stays, `v` and `t` on
|
|
YouTube included.
|
|
- **Thumbnail with the video.** Telegram only takes an uploaded JPEG of
|
|
at most 320 px and under 200 kB, never a URL. The core fetches the
|
|
source's thumbnail image (5 MB, 8 s, no private addresses, also after
|
|
DNS) and shrinks it. YouTube WebP thumbnails are swapped for their JPEG
|
|
copy; other WebP images are skipped, since the standard library cannot
|
|
read WebP. A failure only means no thumbnail: Telegram makes its own
|
|
from an MP4. The worker protocol was not changed for this.
|
|
- **faststart.** yt-dlp is given `-movflags +faststart` for its Merger
|
|
and FixupM3u8 steps, the ffmpeg runs that write MP4s. A single file
|
|
downloaded as is, without ffmpeg, keeps the layout the site served.
|
|
Transcoded profiles already had faststart.
|
|
- **Result buttons.** The buttons are Audio (MP3), Other quality,
|
|
Thumbnail and Delete. Each one is only offered when it makes sense:
|
|
there is no MP3 button under an MP3, and no thumbnail button when the
|
|
source has none. Each follow-up is a new download under the usual
|
|
limits. Callback data carries the request ID only. In groups only the
|
|
requester may press them.
|
|
- **Language.** The language is resolved once per update, before routing,
|
|
and travels in the context. The order is: the user's stored choice,
|
|
then Telegram's `language_code`, then English. A group's own language
|
|
wins inside that group. The i18n bundle now logs a text that falls
|
|
back to English like a missing message, so every app test that runs in
|
|
Spanish or Dutch fails on a fallback. `TestEveryScreenInSpanishAndDutch`
|
|
walks every user screen in both languages. It fails on any word that
|
|
only the English catalog uses, which catches hardcoded strings too.
|
|
The fake Bot API now sends each user's language with their button
|
|
presses, like Telegram does. It used to send "en" for every press.
|
|
- **Sizes.** Sizes drop a decimal that is zero ("50 MB", "1.5 GB"), in
|
|
the bot and in the Mini App, and keep the locale's decimal separator.
|
|
- **First run and quality values.** `users.default_quality` now has
|
|
three special values. "" means the user never chose, "ask" means ask
|
|
every time, and "fit" means the best quality that fits the limit.
|
|
Before, "" meant ask, so an existing user who once picked "ask every
|
|
time" sees the card one more time and then gets "fit", like a new
|
|
user. The card says so, and /quality changes it. The Mini App keeps
|
|
writing "" for "ask"; the API maps it.
|
|
- **"Best that fits my limit"** compares yt-dlp's size estimates of Best,
|
|
1080p, 720p and 480p with the user's size cap, which is capped by the
|
|
upload limit. A quality without an estimate only counts when no quality
|
|
has one; the worker's `--max-filesize` then still guards the real file.
|
|
When nothing fits, the smallest quality is started, which fails the
|
|
limit check and leads to the over-limit offer.
|
|
- **Errors.** A lookup that fails with a passing error (network, rate
|
|
limit, a lost worker) is tried once more after a second, before the
|
|
user sees anything. Timeouts are not retried, since they already took
|
|
the full probe time. Download failures keep the scheduler's existing
|
|
single retry. The error buttons are:
|
|
- Try again after a passing failure.
|
|
- Smaller quality and Upgrade after "too large".
|
|
- Upgrade after "too long" and after the daily limits.
|
|
- Open app after content errors (private, login, region, unsupported).
|
|
|
|
A failed lookup is kept as a failed request, so that "Try again" knows
|
|
the link.
|
|
- **Several links.** Up to `MULTI_LINK_MAX` links per message are
|
|
handled, each with its own status. A link counts as already sent when
|
|
the same user got a file for it in the same chat within the last 10
|
|
minutes. Links are compared without their tracking parameters. The
|
|
10 minutes are a constant, not a setting. Commands (/dl, /fresh,
|
|
/audio) never answer "already sent".
|
|
- **Menu button.** The default menu button opens the Mini App with the
|
|
source language's label. `setChatMenuButton` takes no language, so
|
|
each private chat gets its own label the first time the user writes,
|
|
and again when they change language. What was set is remembered in the
|
|
`kv` table, so a restart does not repeat the calls. The "/" button of
|
|
the message field keeps the command list.
|
|
- **Personal /settings.** It shows the default format, the audio-only and
|
|
ask-every-time switches, the language, the pass and balance, invited
|
|
friends, Open app, and "Add me to a group"
|
|
(`https://t.me/<bot>?startgroup=settings`). The bot username comes from
|
|
`getMe`.
|
|
|
|
### Phase 2: command screens
|
|
|
|
- **/help** is an introduction (how to send a link, the user's default
|
|
format and how to switch to "Ask every time", the limits on one line)
|
|
with the buttons Commands, Account, Groups, Open app and Upgrade. Each
|
|
button edits the same message, and each section has Back. Upgrade is
|
|
left out for paying users. In a private chat the Groups section names
|
|
no group command; it explains groups and has "Add me to a group". In a
|
|
group it lists the group commands. Anyone in a group may switch
|
|
sections: the message is help, not a personal setting.
|
|
- **/quality** lists Ask every time, Best that fits my limit, Best, 1080p,
|
|
720p, 480p and Audio only (MP3), with a check on the active one. A user
|
|
who never chose sees "Best that fits my limit" checked, since that is
|
|
what they get. Free users see a warning sign on the qualities that a
|
|
video as long as their duration limit would push over their size limit.
|
|
This uses typical bitrates: Best 6 Mbit/s, 1080p 4.5, 720p 2.5, 480p
|
|
1.2, MP3 192 kbit/s. A note explains the sign. Paying users get no
|
|
signs.
|
|
- **Best that fits my limit.** With no size estimate at all, Best is
|
|
picked and the worker's `--max-filesize` guards the real file. The
|
|
720p choice means "the best up to 720p", so on a source without a
|
|
720p format it is the 480p format and its size.
|
|
- **/history rows.** Migration 00007 adds `extractor`, `title`,
|
|
`uploader`, `profile` and `hidden` to `deliveries`, the rows history is
|
|
built from (they already have `created_at`). The columns are filled
|
|
from the job when a delivery is sent, and backfilled for old sent rows
|
|
on both databases with correlated subqueries.
|
|
- **/history list.** Pages of five. Each download is one button,
|
|
"site · title · format · when", for example "Instagram · nasa · 720p ·
|
|
today". A generic title becomes the uploader. "When" is today,
|
|
yesterday, N days ago, then the date. Site names come from the
|
|
extractor; yt-dlp's generic extractor shows the host. The separate
|
|
text list is gone; the message only has a header with the count and
|
|
page.
|
|
- **Thumbnails** are not listed as downloads. Tapping a video shows it
|
|
with Send again, Thumbnail (when the source has one), Remove from
|
|
history and Back.
|
|
- **Removing** from history hides the row and does not delete it, because
|
|
deliveries also hold usage and billing facts. Clear history asks first
|
|
and hides every row. The Mini App's history follows the same rules.
|
|
- Send again from history is a new download through the same path as
|
|
every other one, so limits, quota and price apply. A cache hit still
|
|
counts as a download.
|
|
- **Screens for review.** `docs/SCREENS.md` shows every screen of a
|
|
scripted walk through the bot in English, Spanish and Dutch. It is
|
|
generated by the language test
|
|
(`DLBOT_SCREENS=$PWD/docs/SCREENS.md go test ./internal/app -run TestEveryScreen`).
|
|
|
|
### Phase 3: own referral system (sats)
|
|
|
|
- **Codes.** A code is 8 characters of RFC 4648 base32 (A to Z, 2 to 7)
|
|
from 40 random bits, made when a user first needs a link and stored in
|
|
`users.ref_code` under a unique index (migration 00008). A clash is
|
|
retried with a new code. Codes are matched in upper case.
|
|
- **Links** are `https://t.me/<bot>?start=rf_<CODE>`, with the username
|
|
from `getMe`. Old links (`?start=ref_<Telegram ID>`) still record the
|
|
inviter, but no screen shows them any more. The new prefix is `rf_`
|
|
rather than `ref_`, because a code can be all digits, like an old ID.
|
|
- **Who can be referred.** Only somebody who is new to the bot (the
|
|
first update from them is the /start with the link) can be referred,
|
|
once, and never by themselves. That covers "the same Telegram account":
|
|
one account cannot be credited for referring itself. An unknown or
|
|
broken code is ignored and the welcome is shown as usual.
|
|
- **Rewards.**
|
|
- The reward is `REFERRAL_REWARD_SATS` (the older `REFERRAL_REWARD`
|
|
still works). It is paid when the invited user settles their first
|
|
purchase, inside the same database transaction as the settlement.
|
|
An unpaid invoice earns nothing.
|
|
- Donations do not count. In Phase 4 only Lightning purchases count.
|
|
- Each invited user earns their inviter one reward, ever: a row in
|
|
`referral_rewards`, keyed by the invited user. Credits go through
|
|
the ledger with a dedupe key. Repeated webhooks and polls cannot pay
|
|
twice, because settlement itself is idempotent.
|
|
- **Daily cap.** `REFERRAL_DAILY_CAP` (default 2000 sats; 0 means no cap)
|
|
limits what one inviter is paid per UTC day. A reward over the cap is
|
|
recorded as pending and paid by the billing loop (about once a
|
|
minute) on a later day, as the cap allows, oldest first. Rewards paid
|
|
before this round were copied from the ledger into the new table, as
|
|
paid.
|
|
- **Stats.** /referral shows:
|
|
- Invited: users with this inviter.
|
|
- Bought something: rewards recorded.
|
|
- Earned: sats paid.
|
|
- Waiting: sats pending.
|
|
|
|
The buttons are Share (Telegram's share URL with a line of text), Copy
|
|
link (a `copy_text` button) and QR code (a PNG sent in the chat). The
|
|
Mini App Me page shows the same numbers, copy and share, and the QR
|
|
code as an image in the profile response.
|
|
|
|
### Phase 4: Telegram Stars payments
|
|
|
|
- **Where the prices live.** "A separate config table (stars_prices)" is
|
|
read as a configuration table: `[stars_prices]` in the TOML file, or
|
|
`STARS_PRICES="pass_day=50,credits_1000=70"`. It is not a database
|
|
table. Keys are `pass_day`, `pass_week`, `pass_month` and
|
|
`credits_<sats>`, one per credit pack. A product without a price is
|
|
not sold for Stars; nothing is converted from sats. The defaults
|
|
(50, 200, 600; 70, 330, 1300) are placeholders for the owner to set.
|
|
`STARS_ENABLED` is off by default, so existing setups keep working
|
|
unchanged.
|
|
- **What Stars buy.** Stars buy passes and credit packs, for the user's
|
|
own wallet. Stars purchases from the Mini App can also be for a group.
|
|
Skipping the queue, one-off payments for a single file, donations and
|
|
group top-ups from the chat stay Lightning only. One-off prices depend
|
|
on the file size, and a fixed Stars price per size step was not asked
|
|
for.
|
|
- **How it is paid.**
|
|
- The invoice uses currency XTR, an empty provider token and exactly
|
|
one price, with payload `dlp:<purchase id>`.
|
|
- The pre-checkout answer checks that the payload belongs to this payer
|
|
and is still pending, and that currency and amount match.
|
|
- `successful_payment` settles through the same transaction as
|
|
Lightning, so a pass or credits are granted exactly the same way and
|
|
the follow-up (the download behind an over-limit offer) runs the
|
|
same way.
|
|
- The `telegram_payment_charge_id` is stored under a unique index, so
|
|
a repeated event settles nothing twice.
|
|
- A Stars purchase gets a placeholder payment hash (`stars:<id>`) and
|
|
is never sent to LNbits, by the poll or by "Check payment".
|
|
- **The books.** `purchases.payment_method` and `ledger.payment_method`
|
|
(migration 00009) say lightning or stars; older rows are lightning.
|
|
`purchases.amount_sats` of a Stars purchase is the sats value of what
|
|
it bought: the credit pack, or the pass's Lightning price.
|
|
`stars_amount` is what was paid in Stars. /stats shows revenue per
|
|
method: sats for Lightning, Stars for Stars, refunds counted apart.
|
|
- **Refunds.**
|
|
- `/refund <purchase id or charge id>` calls `refundStarPayment` and
|
|
then takes back what the purchase granted: credits as far as they
|
|
are left, or the pass. Passes stacked after a refunded pass move up
|
|
by its length.
|
|
- The old `/refund <user> <sats>` form still gives sats back.
|
|
- A `refunded_payment` message from Telegram (for example after the
|
|
owner's refund) undoes the purchase too. That only happens once.
|
|
- A payment that cannot be matched to an order is logged with its
|
|
charge ID, so the owner can refund it.
|
|
- **A failed download after a Stars payment** follows the Lightning
|
|
policy unchanged. The scheduler retries a job once. What a download
|
|
charged is given back when it finally fails. A pass that was bought
|
|
stays, and a pass bought for a download that can no longer start stays
|
|
too. No extension of the pass was added, since Lightning has none.
|
|
- **In the chat.** The buy screen, /credits and /account show the
|
|
Lightning buttons first and a "Pay with Stars" button that switches the
|
|
message to Stars prices and back. The over-limit offer adds a Stars
|
|
button that shows the Stars passes in a message of their own. Once
|
|
paid, a new message confirms the payment, because Telegram's invoice
|
|
message cannot be edited into "paid".
|
|
- **In the Mini App**, Buy has a Lightning and Stars switch. A Stars
|
|
purchase returns an invoice link (`createInvoiceLink`), which the app
|
|
opens with `WebApp.openInvoice`. The status the app gets back only
|
|
closes or keeps the view. The app learns about the payment by asking
|
|
the core, which settles it from Telegram's `successful_payment` update.
|
|
- `pre_checkout_query` was added to the update types the bot asks
|
|
Telegram for.
|