Files
Media-download-telegram-bot/docs/ASSUMPTIONS.md
T
MichilisandClaude Fable 5.2 51371da0e0 Phase 5: groups
Group wallets, group passes, spending rules and admin-only settings.

- Groups recorded from my_chat_member; admin rights verified with
  getChatMember and cached for five minutes
- Group context in entitlement resolution: group pass, group credits under
  the spending rule (anyone, admins only, capped per person per day) and
  the group's daily cap; refunds go back to the wallet that paid
- Group gate before any lookup: bot on or off, who may use it, allowed
  and blocked sites, plus the owner's maintenance mode
- /settings with inline toggles checked on every press, /grouplang,
  /autodetect, /allow, /block, /spending, /groupwallet, /grouppass,
  /groupstats
- Deep links with the target pre-selected: paying for a group happens in
  the private chat; a refused download in a group offers "Buy for me" and
  "Add group credits"
- Optional link detection, tidy mode, default quality and language per
  group; per-member usage
- /quality, /language, /app, /privacy, /terms, /support
- Remaining owner tools: /stats, /queue all, /user, /group, /ban, /unban,
  /grant (passes and gift codes), /credit, /refund, /blocklist,
  /broadcast with confirmation, /maint, /reload i18n

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 09:46:32 +00:00

25 KiB

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.
  • 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.