{"name":"telegram-bot","title":"Telegram bot","description":"A Telegram bot in webhook mode: it sleeps until someone messages it, wakes, and answers in the webhook response.","runtime":"Python 3.11, standard library","size":"small","env":[{"name":"TELEGRAM_BOT_TOKEN","required":true,"description":"The token @BotFather gives you. Without it the bot boots and GET / explains how to set it."},{"name":"TELEGRAM_WEBHOOK_SECRET","required":false,"description":"The secret Telegram sends with every update. Defaults to one derived from the bot token."}],"tags":["telegram","bot","chat","webhooks","python"],"next":"Set TELEGRAM_BOT_TOKEN (oa env set {slug} TELEGRAM_BOT_TOKEN=..., or PUT /v1/artifacts/{slug}/env), then open {url}/setup once to register the webhook.","oa_json":{"type":"service","start":"python3 bot.py"},"files":[{"path":"README.md","content":"# Telegram bot\n\nA Telegram bot in webhook mode, in Python with only the standard library.\nTelegram POSTs each message to the service, the request wakes it, and the\nreply travels back in the webhook's own response, so a quiet bot sleeps and\ncosts nothing. Out of the box it answers `/start`, `/help` and `/time` and\nechoes anything else.\n\n## Set it up\n\n1. In Telegram, message [@BotFather](https://t.me/BotFather), send `/newbot`,\n   and copy the token it gives you (`123456:ABC-...`).\n2. Give it to the service; it restarts with the token:\n\n   ```bash\n   oa env set <slug> TELEGRAM_BOT_TOKEN=123456:ABC-...\n   # or: curl -X PUT <api>/v1/artifacts/<slug>/env -H \"Authorization: Bearer $OA_TOKEN\" \\\n   #       -H 'content-type: application/json' -d '{\"env\":{\"TELEGRAM_BOT_TOKEN\":\"123456:ABC-...\"}}'\n   ```\n\n3. Open `<url>/setup` once. It registers `<url>/telegram` as the bot's\n   webhook, using the URL the platform gives the service (`OA_URL`).\n4. Message the bot.\n\nUntil the token is set, `GET <url>/` answers with these steps instead of\nfailing, so the service boots and stays healthy without it. With the token\nset, `GET <url>/` shows the bot's username, whether the webhook is registered,\nand Telegram's last delivery error if there was one.\n\n## Environment\n\n| Variable | Required | What it does |\n| --- | --- | --- |\n| `TELEGRAM_BOT_TOKEN` | yes | The token from @BotFather. The service boots without it and explains what to do. |\n| `TELEGRAM_WEBHOOK_SECRET` | no | The secret Telegram sends in `X-Telegram-Bot-Api-Secret-Token` with every update; anything without it is refused. Defaults to a value derived from the bot token, so it needs no setting. |\n\nEnvironment variables are set over REST or the CLI (`oa env set`); the MCP\ntools do not set them.\n\n## Extend it\n\n- Change what it says: `reply_to(text)` in `bot.py` turns a message's text\n  into the reply. Call an API or a model there.\n- More update types (buttons, photos, groups): add them to `allowed_updates`\n  in `register_webhook()` and handle them in `do_POST`.\n- Replies that take longer than a few seconds: answer the webhook with `{}`\n  at once and send the reply yourself with `telegram(\"sendMessage\", ...)`,\n  because Telegram resends an update whose webhook is slow to answer.\n\n## What it costs\n\nPrices for `small`, the size this template needs (current prices on\n[openartifacts.sh](https://openartifacts.sh/#cost)):\n\n- **Asleep:** no runtime charge. The bundle is stored at $0.05 per GB-month.\n- **Awake:** $0.03 per awake hour, billed per minute, plus $0.216 per vCPU-hour of CPU actually used. A message wakes it and it stays awake 600 seconds (`sleep_after_s`) after the last one, so an occasional conversation costs about $0.005 plus a little CPU.\n- **Busy all day:** awake around the clock is $0.72 a day plus CPU.\n\nStarting it needs an hour of awake time in credit ($0.03), and an account runs\none service per $1 of balance.\n"},{"path":"bot.py","content":"\"\"\"A Telegram bot in webhook mode. Python standard library only.\n\n    GET  /            status: is the token set, is the webhook registered\n    GET  /setup       register this service's URL (OA_URL) as the bot's webhook\n    POST /telegram    where Telegram delivers updates (checked by secret token)\n\nWebhook mode suits a service that sleeps: Telegram POSTs each message to\n/telegram, the POST wakes the container, and the reply rides back in the\nwebhook's own response ({\"method\": \"sendMessage\", ...}), so answering costs no\nsecond request. Nothing polls, so an idle bot costs nothing.\n\nEvery update must carry X-Telegram-Bot-Api-Secret-Token, which /setup hands\nTelegram: by default an HMAC of the bot token, so it needs no extra setting,\nor TELEGRAM_WEBHOOK_SECRET when set. Anything without it is refused.\n\"\"\"\n\nimport hashlib\nimport hmac\nimport json\nimport os\nimport sys\nimport time\nimport urllib.error\nimport urllib.request\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom urllib.parse import urlsplit\n\nPORT = int(os.environ.get(\"PORT\", \"8080\"))\nTOKEN = os.environ.get(\"TELEGRAM_BOT_TOKEN\", \"\").strip()\nPUBLIC_URL = os.environ.get(\"OA_URL\", f\"http://localhost:{PORT}\").rstrip(\"/\")\nWEBHOOK_URL = f\"{PUBLIC_URL}/telegram\"\nSLUG = os.environ.get(\"OA_ARTIFACT\", \"<slug>\")\nWEBHOOK_SECRET = os.environ.get(\"TELEGRAM_WEBHOOK_SECRET\") or (\n    hmac.new(TOKEN.encode(), b\"openartifacts-telegram-webhook\", hashlib.sha256).hexdigest()[:48] if TOKEN else \"\"\n)\nMAX_BODY = 1_000_000\n\nNEEDS_TOKEN = {\n    \"status\": \"needs_token\",\n    \"message\": \"Set TELEGRAM_BOT_TOKEN: this bot cannot talk to Telegram without it.\",\n    \"steps\": [\n        \"Create a bot with @BotFather in Telegram (/newbot) and copy the token it gives you (123456:ABC-...).\",\n        f\"Set it on this service: oa env set {SLUG} TELEGRAM_BOT_TOKEN=<token>  (or PUT /v1/artifacts/{SLUG}/env with {{\\\"env\\\":{{\\\"TELEGRAM_BOT_TOKEN\\\":\\\"<token>\\\"}}}}). The service restarts with it.\",\n        f\"Open {PUBLIC_URL}/setup once to register the webhook, then message your bot.\",\n    ],\n}\n\n\ndef telegram(method, params=None, timeout=8):\n    \"\"\"Calls the Bot API; returns its JSON ({\"ok\": bool, ...}) even on an HTTP error.\"\"\"\n    request = urllib.request.Request(\n        f\"https://api.telegram.org/bot{TOKEN}/{method}\",\n        data=json.dumps(params or {}).encode(),\n        headers={\"content-type\": \"application/json\"},\n    )\n    try:\n        with urllib.request.urlopen(request, timeout=timeout) as res:\n            return json.loads(res.read())\n    except urllib.error.HTTPError as err:\n        try:\n            return json.loads(err.read())\n        except ValueError:\n            return {\"ok\": False, \"description\": f\"HTTP {err.code}\"}\n    except (urllib.error.URLError, TimeoutError, OSError) as err:\n        return {\"ok\": False, \"description\": f\"could not reach api.telegram.org: {err}\"}\n\n\n_me = {\"at\": 0, \"value\": None}\n\n\ndef bot_identity():\n    \"\"\"getMe, cached for five minutes (GET / would otherwise call Telegram every time).\"\"\"\n    if time.time() - _me[\"at\"] > 300:\n        _me[\"value\"], _me[\"at\"] = telegram(\"getMe\"), time.time()\n    return _me[\"value\"]\n\n\ndef reply_to(text):\n    \"\"\"The bot's behaviour. Extend here: commands, an LLM call, a database.\"\"\"\n    command = text.strip().split()[0].split(\"@\")[0].lower() if text.strip() else \"\"\n    if command == \"/start\":\n        return \"Hello! I am running on OpenArtifacts. Send me any text and I will echo it. /help lists commands.\"\n    if command == \"/help\":\n        return \"/start - greeting\\n/time - the time in UTC\\n/help - this list\\nAnything else is echoed back.\"\n    if command == \"/time\":\n        return time.strftime(\"It is %H:%M:%S UTC on %A, %d %B %Y.\", time.gmtime())\n    return f\"You said: {text}\"\n\n\nclass Handler(BaseHTTPRequestHandler):\n    server_version = \"telegram-bot/1\"\n\n    def send_json(self, status, payload):\n        body = json.dumps(payload).encode()\n        self.send_response(status)\n        self.send_header(\"content-type\", \"application/json\")\n        self.send_header(\"content-length\", str(len(body)))\n        self.end_headers()\n        self.wfile.write(body)\n\n    def do_GET(self):\n        path = urlsplit(self.path).path.rstrip(\"/\") or \"/\"\n        if path in (\"/\", \"/health\"):\n            if not TOKEN:\n                return self.send_json(200, NEEDS_TOKEN)\n            me = bot_identity() or {}\n            hook = telegram(\"getWebhookInfo\").get(\"result\") or {}\n            registered = hook.get(\"url\") == WEBHOOK_URL\n            return self.send_json(200, {\n                \"status\": \"ready\" if registered else \"webhook_not_set\",\n                \"bot\": (me.get(\"result\") or {}).get(\"username\"),\n                \"telegram\": None if me.get(\"ok\") else me.get(\"description\"),\n                \"webhook\": {\"expected\": WEBHOOK_URL, \"registered\": hook.get(\"url\") or None,\n                            \"pending_updates\": hook.get(\"pending_update_count\"),\n                            \"last_error\": hook.get(\"last_error_message\")},\n                \"message\": \"Message the bot in Telegram.\" if registered else f\"Open {PUBLIC_URL}/setup to register the webhook.\",\n            })\n        if path == \"/setup\":\n            return self.register_webhook()\n        self.send_json(404, {\"code\": \"not_found\", \"message\": f\"No route GET {path}. Try / or /setup.\"})\n\n    # Not named setup(): BaseRequestHandler calls self.setup() for every connection.\n    def register_webhook(self):\n        if not TOKEN:\n            return self.send_json(400, NEEDS_TOKEN)\n        if not WEBHOOK_URL.startswith(\"https://\"):\n            return self.send_json(400, {\n                \"status\": \"needs_https\",\n                \"message\": f\"Telegram only delivers to https URLs; this service's URL is {PUBLIC_URL} (a local stack?). Publish it on openartifacts.sh and open /setup there.\",\n            })\n        result = telegram(\"setWebhook\", {\n            \"url\": WEBHOOK_URL,\n            \"secret_token\": WEBHOOK_SECRET,\n            \"allowed_updates\": [\"message\"],\n        })\n        status = 200 if result.get(\"ok\") else 502\n        self.send_json(status, {\n            \"status\": \"webhook_set\" if result.get(\"ok\") else \"telegram_refused\",\n            \"webhook\": WEBHOOK_URL,\n            \"telegram\": result.get(\"description\"),\n        })\n\n    def do_POST(self):\n        path = urlsplit(self.path).path.rstrip(\"/\")\n        if path == \"/setup\":\n            return self.register_webhook()\n        if path != \"/telegram\":\n            return self.send_json(404, {\"code\": \"not_found\", \"message\": f\"No route POST {path}.\"})\n        given = self.headers.get(\"x-telegram-bot-api-secret-token\", \"\")\n        if not WEBHOOK_SECRET or not hmac.compare_digest(given, WEBHOOK_SECRET):\n            return self.send_json(401, {\"code\": \"unauthorized\", \"message\": \"Missing or wrong X-Telegram-Bot-Api-Secret-Token.\"})\n        length = int(self.headers.get(\"content-length\") or 0)\n        if length > MAX_BODY:\n            return self.send_json(413, {\"code\": \"too_large\", \"message\": \"Update too large.\"})\n        try:\n            update = json.loads(self.rfile.read(length) or b\"{}\")\n        except ValueError:\n            return self.send_json(400, {\"code\": \"invalid_request\", \"message\": \"Not JSON.\"})\n        message = update.get(\"message\") or {}\n        text = message.get(\"text\")\n        chat = (message.get(\"chat\") or {}).get(\"id\")\n        if not text or chat is None:\n            return self.send_json(200, {})  # stickers, joins...: acknowledged, no reply\n        print(f\"update {update.get('update_id')} from chat {chat}: {text[:80]!r}\", flush=True)\n        # Answer inside the webhook response: Telegram performs this call itself.\n        self.send_json(200, {\"method\": \"sendMessage\", \"chat_id\": chat, \"text\": reply_to(text)})\n\n    def log_message(self, fmt, *args):\n        # The default log line includes the path, never the token; keep it.\n        sys.stderr.write(\"%s %s\\n\" % (self.address_string(), fmt % args))\n\n\nif __name__ == \"__main__\":\n    note = \"token set\" if TOKEN else \"TELEGRAM_BOT_TOKEN not set: GET / says how to set it\"\n    print(f\"telegram-bot listening on 0.0.0.0:{PORT}; {note}\", flush=True)\n    server = ThreadingHTTPServer((\"0.0.0.0\", PORT), Handler)\n    server.daemon_threads = True\n    server.serve_forever()\n"},{"path":"oa.json","content":"{\n  \"type\": \"service\",\n  \"start\": \"python3 bot.py\"\n}\n"}],"file_count":3,"bytes":11201,"page":"https://openartifacts.sh/templates/telegram-bot","publish":{"curl":"curl -sX POST https://openartifacts.sh/v1/publish -H \"Authorization: Bearer $OA_TOKEN\" -F type=service -F template=telegram-bot -F slug=my-bot","mcp":{"tool":"publish_artifact","arguments":{"type":"service","template":"telegram-bot","slug":"my-bot"}},"cli":"oa deploy --template telegram-bot --slug my-bot"},"hint":"files is in the shape publish_artifact takes. To publish it unchanged: POST /v1/publish -F type=service -F template=telegram-bot. To publish an edited copy: send your changed files alongside -F template=telegram-bot (they replace the files of the same path), or publish the whole edited set without it (type=service; oa.json is among the files)."}