telegram-worker Isolate Profile

Comprehensive engineering specification for the Hoox Telegram Notification & Command Worker, covering RAG vectorized indexes, R2 uploads, and alert payloads.

This page

The telegram-worker serves as the dynamic communicator of the Hoox trading ecosystem. Running as an isolated edge microservice, it parses incoming chat commands forwarded from Telegram's webhooks, executes retrieval-augmented generation (RAG) queries via Vectorize, analyzes screenshots using AI vision models, and dispatches real-time HTML/Markdown formatting order alerts to your mobile.


⚡ 1. Declared Wrangler Configurations & Bindings

The telegram-worker mounts multiple storage and vector search services to implement AI-powered chatbot features. Its wrangler.jsonc specifies:

{
  "name": "telegram-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-05-19",
  "compatibility_flags": ["nodejs_compat"],
  "account_id": "debc6545e63bea36be059cbc82d80ec8",
  "placement": {
    "mode": "smart",
  },
  "kv_namespaces": [
    {
      "binding": "CONFIG_KV",
      "id": "c5917667a21745e390ff969f32b1847d",
    },
  ],
  "r2_buckets": [
    {
      "binding": "UPLOADS_BUCKET",
      "bucket_name": "user-uploads",
    },
  ],
  "vectorize": [
    {
      "binding": "VECTORIZE_INDEX",
      "index_name": "rag-index",
    },
  ],
  "ai": {
    "binding": "AI",
  },
  "secrets": [
    "INTERNAL_KEY_BINDING",
    "TG_BOT_TOKEN_BINDING",
    "TG_CHAT_ID_BINDING",
    "TELEGRAM_SECRET_TOKEN",
    "AUTHORIZED_CHAT_IDS",
  ],
}

🔑 2. Environmental Variables & Encrypted Secrets

  • TG_BOT_TOKEN_BINDING: Private HTTP bot token generated by @BotFather.
  • TG_CHAT_ID_BINDING: Your default Chat ID for receiving notifications (digits only; optional leading - for groups/channels).
  • TELEGRAM_SECRET_TOKEN: A secure, random token sent as the X-Telegram-Bot-Api-Secret-Token header to validate webhook requests from Telegram.
  • INTERNAL_KEY_BINDING: Shared key used to validate calls from hoox or trade-worker.
  • AUTHORIZED_CHAT_IDS: Comma-separated numeric chat IDs. Inbound /webhook: fail-closed when unset (commands silently dropped). Outbound /alert: when set, destination must be listed; when unset, only TG_CHAT_ID_BINDING is permitted (blocks arbitrary chatId overrides). Align with gateway TELEGRAM_ALLOWED_CHAT_IDS for public notify (gateway already fail-closes independently).

Local Development Mocking (.dev.vars)

TG_BOT_TOKEN_BINDING=mock_telegram_bot_token
TG_CHAT_ID_BINDING=987654321
TELEGRAM_SECRET_TOKEN=local_secure_route_token
INTERNAL_KEY_BINDING=dev_shared_internal_security_key
AUTHORIZED_CHAT_IDS=987654321

🔌 3. Internal REST API Specification

Note: For the canonical endpoint directory with full request/response examples across all workers, see /docs/devops/api/endpoints.

A. Dispatch Notification Endpoint

  • Endpoint: POST /alert (legacy alias: POST /process — same handler, no redirect)
  • Method: POST
  • Headers: X-Internal-Auth-Key: <INTERNAL_KEY_BINDING> (fail-closed if unset)
  • JSON Payload (nested or flat):
    {'{'}
      "requestId": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
      "payload": {'{'}
        "chatId": "987654321",
        "message": "<b>📈 Bybit LONG Filled!</b>\nSymbol: <code>BTCUSDT</code>\nPrice: <code>$68,425.50</code>\nQuantity: <code>0.005</code>",
        "parseMode": "HTML"
      {'}'}
    {'}'}
    
    Flat shape is also accepted: { "message": "...", "chatId": "...", "parseMode": "HTML" }. parseMode may be HTML (default), Markdown, or MarkdownV2. Messages longer than 4096 characters are truncated.
  • Success Response (200 OK):
    {'{'}
      "success": true,
      "result": {'{'} "ok": true, "result": {'{'} "message_id": 482904 {'}'} {'}'}
    {'}'}
    

B. Telegram Ingress Webhook Route

Receives chat commands, /start signals, and image binaries.

  • Endpoint: POST /webhook
  • Method: POST
  • Auth: Header X-Telegram-Bot-Api-Secret-Token must match secret TELEGRAM_SECRET_TOKEN (fail-closed, timing-safe). This is not internal mesh auth.
  • JSON Payload: Standard Telegram update JSON schema.
  • Access Control: After secret validation, message.chat.id must appear in AUTHORIZED_CHAT_IDS (comma-separated). If the allowlist is unset/placeholder, or the chat is not listed, the update is silently dropped with 200 OK (no command execution).

🧠 4. AI-Powered Chatbot & RAG Mechanics

The bot does not just return static responses. When you send /ask <question> (or free-text that is indexed for later search):

  1. Embedding Generation: The worker calls env.AI to generate high-dimensional text embeddings for your prompt using the @cf/baai/bge-base-en-v1.5 model.
  2. Vector Query: Passes the vector to env.VECTORIZE_INDEX (my-rag-index) to retrieve semantically related prior messages.
  3. Context Construction: Formats matched history into a bounded context window; each snippet is sanitized (control chars stripped, injection markers redacted, role tags neutralized) and wrapped in <context> delimiters.
  4. LLM Inference: Invokes LLaMA-3 instruct via env.AI with a system prompt that treats context as untrusted data only (20s timeout).

Bot commands (authorized chats only)

CommandBehavior
/startHelp text
/statusKill-switch state from CONFIG_KV
/latest / /tradesLatest trade signal from R2 (latest_trade_signal.json or signals/*)
/positionsPoints operators to the dashboard
/search <query>Vectorize semantic search over indexed messages
/ask <question>RAG answer over Vectorize context
/kill_on / /kill_offEngage / release global kill switch in KV
(photo)Download → R2 → vision caption (path validated, AI timeout)
(other text)Index into Vectorize for future search

Tip

Secure your bot webhook instantly after deployment: hoox deploy telegram-webhook. The CLI automatically queries your secrets, makes the HTTP setup call to Telegram's servers, and validates the TLS tunnel!

🔗 Next Steps