---
name: telegram-mini-apps
description: Use when deploying a Telegram Mini App or bot-wired web app.
version: 0.1.0
author: Nexus
license: MIT
metadata:
  hermes:
    tags: [Telegram, MiniApp, Bot, HTTPS, Caddy]
    related_skills: [anonymous-service-signup]
---

# Telegram Mini App deployment (bot + HTTPS web app)

## When to Use

- The owner wants a web app/game inside Telegram ("Telegram-Spiel", "Mini App", "App über Bot einrichten") or a bot whose menu button opens a web page.
- A bot needs wiring: menu button, description, commands, or server-side Telegram-user validation.
- A BOT-ONLY customer flow (no web app): menu, step-by-step instructions, buttons, and a human-in-the-loop payout — see "Bot-only flows" below.

Covers hosting, TLS, bot menu-button setup, and initData validation.

## Procedure

1. **Bot token**: a bot can only be created by a human via @BotFather — hand the owner the instruction (open @BotFather → /newbot → name + username → forward the token). Store token + username in `~/.secrets/<project>_bot.json` (chmod 600), never in the vault. Verify immediately: `curl https://api.telegram.org/bot<TOKEN>/getMe`.
2. **Build the app self-contained**: single index.html (vanilla JS, no CDNs except `https://telegram.org/js/telegram-web-app.js`), optional PHP backend for leaderboard/storage (SQLite). Include a standalone browser fallback (works without Telegram initData) so it is testable anywhere.
3. **Host with HTTPS** — Telegram rejects non-HTTPS and invalid-certificate URLs:
   - App server: systemd unit running `php -S 127.0.0.1:<port>` with `WorkingDirectory=<appdir>` (auto-restart, survives reboots).
   - TLS termination: Caddy with a reverse_proxy to the local port. For an instant hostname without owning a domain, use the sslip.io trick: `Caddyfile` site block `178-17-240-21.sslip.io { reverse_proxy 127.0.0.1:<port> }` — Let's Encrypt issues certs for sslip.io names on demand (hostname = IPv4 with dashes).
   - **Open the firewall first**: `ufw allow 80/tcp` + `ufw allow 443/tcp` BEFORE restarting Caddy — LE challenges arrive on port 80; a closed firewall shows as "Timeout during connect (likely firewall problem)" and every retry burns LE rate limits.
   - sslip.io/VPS hosting is fine as staging; production moves to the project's own anonymous host + real domain (owner's separation rule) — the menu-button URL can simply be re-set later.
4. **Wire the bot via Bot API** (curl, no webhook needed):
   - Global menu button: `setChatMenuButton` with body `{"menu_button":{"type":"web_app","text":"…","web_app":{"url":"https://…"}}}` — omit `chat_id` entirely; passing `chat_id:""` returns "invalid chat_id".
   - `setMyDescription` (long, shows on empty bot chat), `setMyShortDescription` (profile), `setMyCommands` (e.g. `/spiel`).
5. **Validate Telegram users server-side**: parse `initData` per Telegram spec — HMAC-SHA256 with secret_key = HMAC("WebAppData", bot_token), check `hash` with hash_equals, include a replay window (24h). Only with BOT_TOKEN set; otherwise anonymous mode.
6. **Verify end-to-end**: HTTPS page returns 200 and shows the app title; backend endpoint returns JSON; then have the owner press START + menu button in the real client.

## Bot-only flows (no Mini App)

For guiding a customer through an on-chain flow (buy link, paste TX hash, verify, payout) a plain long-poll bot beats a Mini App — no HTTPS app, no initData. Verified pattern (`~/gkai-buyback-bot/bot.py`):

1. **Reuse an existing bot only when free**: `curl https://api.telegram.org/bot<TOKEN>/getWebhookInfo` — `url` must be empty ("pending_update_count" alone is fine); a set webhook would eat the long-poll updates.
2. **Write the bot in stdlib Python** (urllib/json, no python-telegram-bot dependency): `getUpdates?timeout=25&offset=<last+1>` loop, `sendMessage` with `reply_markup` inline keyboards, answer `callback_query` with `answerCallbackQuery`. Store per-user state in a dict + a JSON ledger (e.g. `payouts.json`) for durable records.
3. **On-chain TX verification**: user pastes the TX hash → web3 `getTransactionReceipt` → check `to` == the expected wallet, decode the ERC-20 `Transfer` log (topic + data slicing) for sender/amount → accept when amount ≥ expected min. Never trust a bare hash string. **Derive the payout base from the transaction itself**: read the buyer's wallet and the BNB they spent from their BUY transaction (pair→buyer Transfer log + tx `value`), and pay out on that — asking the user to type the amount invites both typos and understated-amount fraud, and it lets the bot show the buyer their own payout wallet without them pasting it.
4. **Notify the owner chat instead of auto-paying** (money safety): bot registers the verified payout in the ledger and sends a payout alert to the owner chat id; the owner (or agent cron watcher on the wallet balance) triggers the actual send.
5. **Run as a daemon with restart loop**: `nohup bash -c 'while true; do python3 bot.py; sleep 5; done' > bot.log 2>&1 &`. Verify: `pgrep -af bot.py`, `tail bot.log`, and a `getUpdates?timeout=0&offset=-1` that returns 0 pending updates (bot is consuming them).
6. **Fresh BotFather bot: complete the profile via API, not via BotFather chat**: `setMyDescription`, `setMyShortDescription`, `setMyCommands` (plain JSON bodies), and the profile photo via `setMyProfilePhoto`. Profile photo is NOT a plain multipart file field — send `photo` as a JSON InputProfilePhoto referencing an attached file: `requests.post(url, data={'photo': json.dumps({'type': 'static', 'photo': 'attach://p'})}, files={'p': ('p.png', img, 'image/png')})`. A raw `files={'photo': ...}` fails with "photo isn't specified" no matter the field type/size. Resize to a square (512×512) first.
7. **One getUpdates consumer per bot**: before starting a long-poll (or switching a bot to a new token), kill the old poll loop first — two concurrent `getUpdates` callers yield HTTP 409 Conflict on every poll. Kill by PID, not `pkill -f <script>` — the terminal tool's own wrapper command line contains the script name, so pattern-kill can SIGTERM the wrapper mid-run.
8. **Groups cannot be created by a bot** — only a human via the Telegram app. Have the owner create the group (2 taps) and add the bot as admin, then wire group announcements from the bot.

## Monetization-Funnel (Freemium-Mini-App: Gratis-Fragen → Paywall → Kauf)

Owner-Standardfunnel für Verkaufs-Mini-Apps: Werbung → Mini App → 3-4 Gratis-KI-Fragen pro Gerät/Tag → Paywall → Registrierung → Bezahllink (Payment-Provider) → sofort weiternutzen.

1. **Mini App auf der Domäne des Chat-API-Backends hosten** (`<api-host>/app`), nicht als statische Seite auf einer anderen Domain — Registrierungs-/Session-Cookies laufen dann same-origin ohne CORS- und Auth-Umbau; der Bot-Menü-Button zeigt auf genau diese URL.
2. **Gast-Trial serverseitig**: Endpunkt `/api/guest` leitet aus einer Geräte-ID (localStorage, permanent) einen Pseudo-Account (z. B. `guest_<id>@trial.local`) mit Tageslimit 3-4 ab; Limit serverseitig führen und im Client nur anzeigen — client-seitige Zähler sind umgehbar.
3. **Paywall + In-App-Registrierung**: bei 0 Restfragen Registrierungsform zeigen (gleiche Login-API wie die Web-Plattform), danach unbegrenzter Chat; Session per `GET /api/me` prüfen.
4. **Kampagnen-Attribution**: utm/startapp/ref beim ersten Öffnen in localStorage speichern.
5. **E2E im echten Browser beweisen** (nicht nur curl): echte KI-Antwort auf eine Testfrage, Zähler dekrementiert 3→2→1→0, Paywall erscheint bei 0, Registrierung klappt, weitere Frage wird beantwortet.
6. **Live-Zahlen (Preis, Rabatt) aus einer echten API ziehen** (z. B. GeckoTerminal-Pool-Endpoint), nie aus Platzhaltern rechnen — der angezeigte Rabatt wird vom Owner nachgerechnet; ein falscher %-Wert bricht das Vertrauen im Funnel.
7. **Inline-JS-Patch-Verifikation (kritisch):** Nach JEDEM String-Replace-Patch auf HTML mit Inline-`<script>` das (die) Script-Blöcke extrahieren und `node --check` laufen lassen — VOR dem Deploy. Eine einzige überzählige Klammer im Retry-Pfad tötet das GESAMTE App-JS still (Seite rendert normal, Tabs/Chat/Handler tot, Owner meldet „Chat geht nicht“), und curl+grep-Checks auf Marker im HTML beweisen nichts über JS-Gültigkeit. Gleiche Verifikation auf die LIVE ausgelieferte Datei wiederholen (curl der Produktions-URL → extract → node --check), nicht nur auf die lokale Kopie.
8. **Client-Fehler-Diagnosekanal einbauen:** `window.addEventListener('error', …)` → POST an `/api/jserr` (mit User-Agent). Ohne ihn ist „Owner meldet kaputten Chat, Server-Log zeigt NULL Requests“ nicht diagnostizierbar — keine Requests heißt nämlich JS lief nie, nicht „Backend ok“. Backend-FAIL ≠ Frontend-FAIL: bei „Chat geht nicht“-Meldungen ZUERST die API direkt testen (curl POST /api/guest) — antwortet sie korrekt, ist das Inline-JS der Seite der Täter, nicht das Backend.
9. **Registrierung mit Telegram-Identität + DM-Einwilligung:** bei der Registrierung `telegram_id`/`telegram_username` (aus `Telegram.WebApp.initDataUnsafe.user`, guarded) + `source` (miniapp-tg/miniapp-web) mitsenden und eine VORANGEHAKTE DM-Consent-Checkbox zeigen (Owner-Regel: Kunden per DM dauerhaft erreichbar + Bot-Follow per `tg.openTelegramLink` nach Erfolg).
10. **Zahlungs-Button vor Provider-Aktivierung:** Kauf-Buttons rufen einen eigenen Order-Endpunkt auf; fehlt der Provider-Key, antwortet der mit 503 „wird gerade aktiviert“ und die Bestellung landet schonmal in der DB (pending) — der Funnel bleibt testbar und der Key-Austausch ist ein Ein-Zeilen-Env-Set ohne Frontend-Deploy.
11. **Werbetauglichkeits-Smoke-Check VOR jeder Kampagne** (API-Pfad zuerst — Backend-FAIL ≠ Frontend-FAIL, s. Pkt. 8; erst bei Auffälligkeiten die Agenten-Farm losschicken): (a) `getMe` + `getChatMenuButton` zeigen den richtigen Bot + die App-URL, Beschreibungs-/Promotexte sitzen; (b) `getWebhookInfo.url` ist LEER (ein gesetzter Webhook frisst die Updates); (c) App-URL liefert HTTPS 200; (d) `POST /api/guest` mit dem ECHTEN Feldnamen `guest_id` (serverseitig Regex `^[A-Za-z0-9-]{8,64}$` erzwungen) + `message` posten → echte KI-Antwort + sinkendes `remaining` erwarten — falscher Feldname bringt nur 'Ungueltige Anfrage'; (e) dieselbe guest_id bis zum Limit feuern: HTTP 429 mit `upgrade: true` ist der Paywall-Beweis (Frontend-Zustand daraus ableitbar). GO zum Werbeschalten erst geben, wenn alle fünf Checks live bestanden sind.
12. **Auto-Sprache beim ersten Öffnen** (Owner-Regel für Werbung in EN/TR/ES): direkt nach Deklaration des i18n-Dicts früh im Script Sprache setzen — zuerst URL-Parameter (`lang`/`startapp`/`tgWebAppStartParam`), dann `Telegram.WebApp.initDataUnsafe.user.language_code`, Fallback `navigator.language`, Default `de` als IIFE mit Retry-Timeouts (~300 ms / ~1200 ms); nur das gefundene Präfix übernehmen und `apply()`-Stufe mit Guard `if(I[v]) {L=v; setLang(v);}` aufrufen, alles in try/catch — ein Crash hier tötet das App-JS komplett (Pkt.-7-Gefahr). Drei Beweis-regeln daraus:
    - **NIEMALS eine Default-Sprach-Zuweisung NACH dem Detektor stehen lassen** — ein blankes `setLang('de')` im Start-/Endblock überschreibt die erkannte Sprache still (Retry-Timeouts greifen nur, wenn der ERSTE pick() fehlschlug). Start-Block stattdessen: `if(typeof L==='string'&&I[L]){setLang(L)}else{setLang('de')}`.
    - **Vor jedem Live-Beweis `document.body.innerText` auf Hartkodierungs-Reste durchsuchen**, nie nur `documentElement.lang` prüfen: nur Elemente mit data-i/data-ih-Attribut werden übersetzt — Banner/Badges, deren Text hart im HTML steht, brauchen sowohl das Attribut als auch einen Eintrag in JEDEM Sprach-Dict; fehlt einer, bleibt pro Sprache sichtbarer Alt-Text stehen während `lang` trotzdem korrekt zeigt.
    - **Webview-E2E ohne echtes Telegram simulierbar** über offizielle SDK + URL-HASH: `https://host/app#tgWebAppData=<EINFACH urlencodierter Query `user={"id":…,"language_code":"tr"}&auth_date=…`>&tgWebAppVersion=8.2&tgWebAppPlatform=ios&tgWebAppThemeParams=%7B%7D` (NICHT doppelt encodieren). Parse-Beweis je Seite: `js("JSON.stringify(Telegram.WebApp.initDataUnsafe.user)")`. IMMER eine frische browser_exec-session nehmen — gecachte addScriptToEvaluateOnNewDocument-Injektionen alter Tests erzeugen Phantom-Sprachwechsel und falsche FAILs.
13. **Groß-Investitionen manuell abwickeln (Owner-Grundregel)**: neben dem Sofort-Checkout einen Manuell-Bestell-Endpunkt bieten — Kunde wählt FREIE Zahlungswährung (USDT/BNB/ETH/…), Tokens werden NICHT automatisch geliefert, sondern vom Owner nach Geldeingang manuell an das Empfängerkonto des Kunden gesendet. Jede Bestellung landet sofort in der DB (state `pending_manual_check`) UND feuert eine Notify-Nachricht an den Owner-Chat mit Menge/Währung/TX/Kunden-Wallet/Kontakt.

## E2E-Regel: Test-Farm statt Einzel-Check (Owner-Befehl)
E2E-Tests der Mini App IMMER als parallele Subagenten-Farm (delegate_task), NICHT als einzelner Headless-Browser-Check: pro Agent EIN enges Prüfziel mit klarer PASS/FAIL-Liste, jeweils eigener browser_exec-`session`-Name (Agenten teilen sich sonst Tabs/State). Bewährt: 3 Agenten (Gast-Chat-Flow, Telegram-WebView-UA-Simulation, Registrierung+Analytics) — die Farm fand einen fatalen Syntaxfehler, den Einzel-Checks durch grep auf Deploy-Marker verfehlten. Deploy-typischer Fix während laufender Farm: laufende Agenten per `delegate_task(action='steer')` anweisen, die Seite NEU zu laden und auf der frischen Version zu prüfen — sonst melden sie stale FAILs.

## Pitfalls
- Telegram Mini Apps REQUIRE a valid public HTTPS URL — http or self-signed certs fail silently (button does nothing).
- The menu button label and URL can be updated at any time via `setChatMenuButton` — reuse the same bot when the app moves to its final domain instead of creating a new one.
- Long in-page polling via the browser harness can drop the websocket ("no close frame"); recover with `ensure_real_tab()` + fresh `goto_url`, and prefer short state checks over long loops.
- Keep secrets out of the files the web serves: BOT_TOKEN belongs in a config.php read by the backend, and the webroot must not expose `.key`/secret files.
- Never re-read the request body in a Python http.server handler whose dispatch loop (`do_POST`) parses the JSON once at the top — the second `self.rfile.read(...)`/body-json call waits for bytes the client will never send, so the endpoint hangs until client timeout with zero response bytes. Always reuse the centrally parsed `data`; symptom is a fast-loading page but one frozen endpoint.
- Fire owner notifications (Telegram sendMessage etc.) from a daemon `threading.Thread`, never inline in the request handler — slow DNS resolution can block the entire HTTP response for 10+ s while the customer stares at nothing; synchronous external calls are only OK when their result is part of the response (e.g. the invoice URL).
- Never INSERT into an existing order table without checking its real columns — checkout and manual flows want different schemas, and the mismatched INSERT raises `sqlite3.OperationalError` only visible in the service journal while the client silently gets an empty/hanging response. Give each payment flow its own `CREATE TABLE IF NOT EXISTS` built at startup (plus `_ensure_*()` hook before `main()`), and E2E every new endpoint with curl BEFORE declaring it done.
- Payment-provider recipes (NowPayments invoice quick-link, key storage, verification quirks, manual-order notify pattern): see `references/payments-flows.md`.
