> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hoox.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# telegram-worker Isolate Profile

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

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:

```jsonc theme={null}
{
  "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",
  ],
}
```

***

## 🔑 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.
* **`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`**: Optional comma-separated list of chat IDs allowed to send bot commands. If set, only these chat IDs can interact with the bot.

### Local Development Mocking (`.dev.vars`)

```bash theme={null}
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
```

***

## 🔌 3. Internal REST API Specification

> **Note:** For the canonical endpoint directory with full request/response examples across all workers, see [`/docs/devops/api/endpoints`](../api/endpoints).

### A. Dispatch Notification Endpoint

* **Endpoint**: `/alert`
* **Method**: `POST`
* **Headers**: `X-Internal-Auth-Key: <INTERNAL_KEY_BINDING>`
* **JSON Payload**:
  ```json theme={null}
  {
    "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"
    }
  }
  ```
* **Success Response (200 OK)**:
  ```json theme={null}
  {
    "success": true,
    "result": { "messageId": 482904 },
    "error": null
  }
  ```

***

### B. Telegram Ingress Webhook Route

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

* **Endpoint**: `/telegram/<TELEGRAM_WEBHOOK_SECRET>`
* **Method**: `POST`
* **JSON Payload**: Standard Telegram update JSON schema.
* **Access Control**: The worker extracts the incoming `message.chat.id`. If it does not match your authorized `TELEGRAM_CHAT_ID_DEFAULT` secret, the payload is silently dropped with a `200 OK` return to Telegram to prevent malicious commands.

***

## 🧠 4. AI-Powered Chatbot & RAG Mechanics

The bot does not just return static responses. When you send a natural language question (e.g., *"What is my average entry price on SOL?"*):

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` to retrieve semantically related transaction rows and market summaries from past trades.
3. **Context Construction**: Formats the matched history into a rich LLM context window.
4. **LLM Inference**: Invokes LLaMA-3 instruct via `env.AI` using your multi-provider API keys to generate a highly informed financial summary.

***

<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!
</Tip>

### 🔗 Next Steps

* **[hoox Gateway Profile](hoox)** — Review how incoming commands route to the gateway.
* **[Setting Up Telegram Bot Alerts](../../enduser/tutorials/telegram-bot)** — Step-by-step tutorial for BotFather configuration.
