---
name: telegram-service-bots
description: "Use when building a buyer-facing Telegram bot wizard."
version: 0.1.0
author: Nexus
license: MIT
platforms: [linux]
metadata:
  hermes:
    tags: [telegram, bot, wizard, on-chain, payout, turkish]
    related_skills: [telegram-mini-apps, bsc-minimal-launch, onchain-wallet-monitoring]
---

# Telegram Service Bots (buyer-facing wizards)

## When to Use

- The owner asks for a bot that guides CUSTOMERS (buyers, participants) through
  a flow: buy a token, sell it back, submit a TX hash, register a payout.
- A bot must be set up from a BotFather token (description, picture, commands),
  run 24/7, and notify the owner of completed business events.
- Not for Telegram Mini Apps (see `telegram-mini-apps`) or owner-only scripts
  without a customer chat wizard.

Class: bots where a customer (not the owner) is guided through a business flow in
chat — buy a token, sell it back, submit a TX hash, get a payout. Typical shape:
long-poll Python bot + on-chain verification + owner notification + payout ledger.

## Always-on rules

- **One project = one bot account.** Never reuse a bot from another project
  (owner separation rule: no shared references between ventures). New bots are
  created by the owner via BotFather; he pastes the token in chat.
- **Token storage:** save immediately to `~/.secrets/<project>_bot.json`
  (chmod 600) with `token`, `bot_username`, `purpose`. Never in code, vault or
  logs. Load with `os.path.expanduser("~/.secrets/…")`.
- **Buyer-facing text in Turkish** when the buyer community is Turkish (the
  default for this owner's community programs). Wizard style: numbered inline
  buttons (1️⃣ 2️⃣ 3️⃣), short sentences, copy-able `<code>` addresses, friendly
  error messages that tell the user exactly what to resend.
- **Verify on-chain instead of asking.** Never make the buyer type amounts,
  wallet addresses or dollar values — users mistype and can overstate claims.
  Parse everything from the submitted transaction (see
  `references/onchain-verification.md`).
- **No bots in the community**: only real humans may complete the flow; design
  verification so each completion ties to a real on-chain TX by a unique wallet.
- **Owner notification:** on each completed business event, send a compact
  summary to the owner chat (6231972678); append the record to a JSON ledger
  (e.g. `payouts.json`) in the bot directory — the ledger is the source of
  truth for payouts.
- **Mobile speed is a feature.** Telegram's in-app browser is the default
  browser for buyers. For any swap/DEX link, offer the **Trust Wallet deep
  link first** and the raw DEX link second:
  `https://link.trustwallet.com/open_url?coin_id=20000714&url=<urlencoded DEX link>`
  (opens the Trust app's DApp browser with the wallet auto-connected; on
  desktop it shows an "Open in Trust Wallet" page, hence the second button).
  Add the hint "sayfa yavaş açılırsa: ⋮ → Tarayıcıda aç" when a heavy web page
  is involved — DEX frontends take 20+ s in Telegram's in-app browser and look
  like "page doesn't open".

## Procedure

1. **Save the token** to `~/.secrets/<project>_bot.json`, then `getMe` to
   confirm it is live and the username matches.
2. **Profile setup** via Bot API: `setMyDescription`,
   `setMyShortDescription`, `setMyCommands` (plain form fields work).
   `setMyProfilePhoto` is multipart-JSON, see pitfall below.
3. **Write `bot.py`**: long-poll `getUpdates` loop (timeout 30, offset
   advance), `USERS = {chat_id: state}` dict, callback-button handlers for the
   wizard steps, TX-hash messages (starts with `0x`, len >= 60) routed by the
   user's current step. Send `parse_mode=HTML`.
4. **Dry-run** with `timeout 8 python3 bot.py` — must print the running line
   and be killed by the timeout (exit 124) without errors.
5. **Run 24/7 as a systemd unit** (e.g. `gkai-buyback.service`) — it survives
   sessions and reboots and journalctl gives clean logs. A `while true; do
   python3 bot.py >> bot.log 2>&1; sleep 5; done` background-terminal loop is
   the fallback when no root is available.
6. **Update website links** (landing page, guide) to the new bot username
   whenever a bot is replaced — check every page that mentions `t.me/<oldbot>`.

## Pitfalls

- `setMyProfilePhoto` refuses a plain multipart file field `photo` with
  "photo isn't specified". The parameter must be a JSON string
  `photo={"type":"static","photo":"attach://p"}` while the file bytes go
  under a *different* multipart field (here `p`). Resize the image to
  512×512 PNG first.
- `getUpdates` returns HTTP 409 Conflict while another poller for the same
  token runs — kill the old instance (old bot.py from a previous session
  counts) before starting the new one.
- `pkill -f "python3 bot.py"` also matches the bash restart-loop wrapper (its
  command line contains the string) and can SIGTERM your own terminal call —
  kill bot processes by PID taken from `ps aux | grep bot[.]py` instead.
- Don't serve buyer pages from exotic wildcard domains when a real domain is
  pending; verify global reachability (check-host.net TCP check) before
  blaming the page, and re-test the actual DEX link in a real browser — the
  slow thing is usually the DEX frontend, not your page.
- **Own OTC quick-buy beats DEX links** when buyers struggle with PancakeSwap:
  buyer sends plain BNB to the program wallet, the bot (needs web3 — run it
  with a venv python that has web3, e.g. ~/goldcoin-launch/.venv) auto-sends
  the token at the pair-oracle price minus ~1.5% margin from a stocked program
  wallet. Seed that wallet with token stock beforehand; BNB inflows from buyers
  then self-fund the 110% sell-back payouts.
- **Auto-payout worker** (thread in bot.py, scans the JSON ledger every ~20 s)
  makes "real-time" promises true: status `ausstehend` → sign+send → status
  `bezahlt` + owner notification. Keep hard caps (max BNB per payout) and a
  minimum wallet buffer check before signing; notify the owner when stock or
  buffer runs low.
- SideShift API (as of Nov 2026): POST /api/v2/quotes needs
  depositCoin/settleCoin/depositNetwork/settleNetwork; /shifts/fixed now
  REQUIRES `affiliateId` — the own account `id` from the secrets file works.
- Multi-language wizard: detect `msg.from.language_code` (tr default), store
  per-chat `lang` in USERS, offer a toggle button; texts as a TEXTS dict.
- **web3 v7: `Web3.to_checksum_address()` returns a plain str** — never call
  `.address` on it (contract objects have `.address`, checksummed strs do not).
  A minimal ERC20 ABI for sending must also include `balanceOf` if the worker
  checks stock.
- **Duplicate-TX protection is mandatory**: the same buy/sell TX hash can be
  submitted multiple times (different chats, retries). Before appending a
  ledger entry, look up `buy_tx`/`sell_tx` in the ledger and answer "already
  registered" — otherwise the worker pays out per submission.
- **Never gate TX-hash processing on wizard step**: in-memory user state is
  lost on every restart, so a customer pasting a hash from the "wrong" step
  (or after a restart) gets silently ignored and payouts stall. Route ANY
  0x…64-hex message by what the TX IS on-chain (tokens to us = sellback,
  BNB to us = buy), with the ledger lookup as the only dedup gate. Back this up
  with **USERS persistence**: `load_users()` from `users.json` at startup,
  `save_users()` in a `finally:` after every handled update — user steps,
  wallet addresses and referral data then survive restarts.
- **Long-poll loop robustness**: server `timeout: 30` with a client urlopen
  timeout of 60 s; read timeouts are NORMAL long-poll behaviour (VPS→Telegram
  is sometimes slow) — only log them after ~3 consecutive failures, back off
  `min(5 * fails, 30)` s, and reset the counter on every successful poll.
  Otherwise the log fills with spurious `poll ERR` lines that look like an
  outage.
- **`/start`-resets must preserve cross-session fields**: `u.clear()` empties
  the very dict `USERS[chat]` points at, so reading the old value via
  `USERS.get(chat)` AFTER the clear returns None — copy surviving fields
  (referral `ref_by`/`ref_credited`, opt-ins) to locals BEFORE `u.clear()`
  and restore them after. Same applies to any handler that resets state.
- **Referral/level systems**: valid friends = referred users who complete their
  first VERIFIED deal (not mere joins — owner rule "only real humans"); make
  crediting idempotent with a `ref_credited` flag on the referred user.
  Parse `/start ref_<chat_id>` payloads defensively: candidate must be
  `isdigit()`, not the user's own chat id, and exist in USERS (referrer sent
  the link, so they are known). Per-user limits/premiums replace global
  constants at the business-rule sites (range checks, payout factor), and the
  displayed percentage in canned texts must be replaced dynamically
  (`text.replace("%110", f"%{pct}")` style) or tiers lie to users.
- Validate ALL i18n texts for balanced HTML tags before going live: a single
  unclosed `<b>` makes every sendMessage in that language fail with HTTP 400
  ("can't parse entities"). Balanced static texts are still not enough —
  **dynamic values (user first names!) can contain `<`, `>` or `&` and break
  HTML parsing at runtime.** Harden the `tg()` wrapper itself: catch
  `urllib.error.HTTPError` code 400 when the call had `parse_mode`, retry once
  with `parse_mode` removed — the message then always arrives (plain text beats
  a lost message).
- **Test bot flows with synthetic updates, not by hand**: import bot.py via
  `importlib.util.spec_from_file_location`, set `m.USERS[chat_id]` to the
  desired step, then call `m.handle({"update_id": …, "message": {"chat": …,
  "text": "<tx-hash>", "from": {"language_code": "de"}}})`. This exercises
  TX-submission handling and kicks off the worker without a real chat message or
  touching the long-poll process.
- **Full end-to-end test with a fresh account before going live**: generate an
  EOA (key → `~/.secrets/`), fund gas from the program wallet, run the whole
  customer cycle (payment TX → submit hash via synthetic update → verify token
  delivery in the ledger AND on-chain → sell back → verify auto-payout
  arrives). Only a completed real-money cycle proves the flow; unit checks do
  not.
- **Custom tokens are invisible in MetaMask until imported** — buyers who
  received tokens think they are lost. Ship a web wallet page with a
  `wallet_watchAsset` button (see `references/web-wallet-page.md`); never
  explain the loss away in chat alone.
