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

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