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

# Telegram 機器人設置

> 使用 @hitheo/telegram 適配器將 Theo 接入 Telegram。

`@hitheo/telegram` 包可將 Theo 作為機器人接入 Telegram。用戶向你的機器人發送消息，Theo 通過完整的編排流程處理響應，適配器再通過 Bot API 回覆。

<Note>
  Theo 從不託管你的機器人。你需要通過 [@BotFather](https://t.me/BotFather) 創建機器人並持有令牌，並將本適配器部署在**你自己的**基礎設施上；Theo 只處理適配器轉發過來的補全流量。這樣一來，每一條消息、Webhook URL 和憑證都始終掌握在你手中。
</Note>

## 前提條件

1. 從 [@BotFather](https://t.me/BotFather) 獲取的 Telegram 機器人令牌
2. 一個 Theo API 密鑰（`theo_sk_...`）

## 安裝

<CodeGroup>
  ```bash npm theme={null}
  npm install @hitheo/telegram
  ```

  ```bash yarn theme={null}
  yarn add @hitheo/telegram
  ```

  ```bash pnpm theme={null}
  pnpm add @hitheo/telegram
  ```
</CodeGroup>

## 快速設置

`createTelegramHandler` 返回一個異步函數，用於處理單條 Telegram Webhook 更新。你可以將它接入任意 HTTP 框架——Express、Next.js 路由處理器、Cloudflare Workers、AWS Lambda 等。

```typescript theme={null}
import express from "express";
import { createTelegramHandler } from "@hitheo/telegram";

const app = express();
app.use(express.json());

const handle = createTelegramHandler({
  theoApiKey: process.env.THEO_API_KEY!,
  telegramToken: process.env.TELEGRAM_BOT_TOKEN!,
  secretToken: process.env.TELEGRAM_WEBHOOK_SECRET, // 可選，但建議設置
  mode: "auto",
  skills: ["customer-support"],
  persona: "You are a helpful assistant for Acme Corp.",
});

app.post("/webhook", async (req, res) => {
  try {
    await handle(req.body, {
      secretToken: req.header("X-Telegram-Bot-Api-Secret-Token"),
    });
    res.sendStatus(200);
  } catch (err) {
    // TelegramSignatureError indicates an unauthorized POST.
    res.sendStatus(401);
  }
});

app.listen(3000, () => console.log("Telegram bot listening on :3000"));
```

## 工作原理

1. 用戶向你的 Telegram 機器人發送一條消息
2. Telegram 將該更新以 POST 方式推送到你的 Webhook URL
3. 適配器校驗 `X-Telegram-Bot-Api-Secret-Token` 請求頭（當配置了 `secretToken` 時）
4. 適配器將文本（以及任何圖片/文檔附件）轉發至 `POST /api/v1/completions`，並複用與該會話關聯的 `conversation_id`
5. Theo 通過完整流程（分類、技能、代理循環）處理該請求
6. 響應被髮回該 Telegram 聊天，如有需要會拆分為多條消息發送

## 處理器配置

| 選項 | 類型 | 是否必填 | 說明 |
| - | - | - | - |
| `theoApiKey` | `string` | ✅ | 你的 `theo_sk_...` API 密鑰 |
| `telegramToken` | `string` | ✅ | 來自 BotFather 的機器人令牌 |
| `secretToken` | `string` | | 傳給 `setWebhook` 的共享密鑰。設置後，若更新缺少該請求頭或其值不匹配，將拋出 `TelegramSignatureError`。 |
| `theoBaseUrl` | `string` | | API 基礎 URL（默認：`https://www.hitheo.ai`） |
| `mode` | `ChatMode` | | 默認模式 —— `auto`、`fast`、`think`、`code` 等 |
| `persona` | `PersonaInput` | | 自定義角色，或 `"theo"` / `"none"` |
| `skills` | `string[]` | | 每條消息都會激活的技能 slug 列表 |
| `conversationStore` | `ConversationStore` | | 將聊天 ID 映射到 Theo 會話 ID。默認使用進程內的 `Map`；跨實例部署時請替換為 Redis/數據庫實現。 |
| `enableVoice` | `boolean` | | 使用 Theo 語音轉文本轉錄語音/音頻，並將轉錄文本附加到提示詞中。默認關閉（語音轉文本會產生額外費用）。 |
| `maxChunkChars` | `number` | | 每條出站消息的最大字符數。默認 4000。 |

## 內置命令

適配器會自行處理以下三個命令（不會調用 Theo）：

| 命令 | 行為 |
| - | - |
| `/start` | 發送一條介紹消息 |
| `/help` | 列出可用命令 |
| `/reset` | 清除該聊天已存儲的 `conversation_id`，下一條消息將開啓全新上下文 |

其他任何 `/foo` 命令都會返回一條簡短的“未知命令”回覆。

## 附件

消息中附帶的照片（以及圖片類文檔）會在適配器內部下載，並以 **base64 圖片數據**的形式轉發給 Theo——適配器絕不會把 Telegram 的文件 URL 傳給 Theo。這樣可以確保機器人令牌始終留在你的部署環境內。

<Warning>
  請始終使用最新版本的 `@hitheo/telegram`。如果你還在使用 `≤0.1.3` 版本，請升級到 `^0.1.4`，並在升級過程中通過 `@BotFather` 輪換機器人令牌。
</Warning>

語音和音頻消息默認會被忽略，除非你設置了 `enableVoice: true`。啓用後，適配器會下載語音片段，通過 Theo 語音轉文本進行處理，並將轉錄文本以文字形式附加到提示詞中。語音**不會**作為附件發送——Theo 的補全端點只接受圖片附件。

## 設置 Webhook

向 Telegram 註冊你的 Webhook URL，並附上 `secret_token`：

```bash theme={null}
curl -X POST "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-domain.com/webhook",
    "secret_token": "'"$TELEGRAM_WEBHOOK_SECRET"'"
  }'
```

## 跨實例保持會話持久化

默認的 `ConversationStore` 是一個進程內的 `Map`——這對單個長期運行的服務器沒問題，但不適用於無服務器場景（每次調用都是全新進程）。請提供你自己的存儲實現：

```typescript theme={null}
import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

const handle = createTelegramHandler({
  theoApiKey: process.env.THEO_API_KEY!,
  telegramToken: process.env.TELEGRAM_BOT_TOKEN!,
  conversationStore: {
    get: (chatId) => redis.get(`tg:conv:${chatId}`),
    set: async (chatId, id) => {
      await redis.set(`tg:conv:${chatId}`, id, "EX", 60 * 60 * 24 * 30);
    },
    clear: async (chatId) => {
      await redis.del(`tg:conv:${chatId}`);
    },
  },
});
```

## 部署

可以部署為任意 Node.js HTTP 服務器。生產環境建議：

* **Railway / Render / Fly.io** —— 對基於 Webhook 的機器人來說最簡單
* **Vercel / Cloudflare Workers** —— 無服務器（每條消息對應一次調用）；請配合遠程 `conversationStore` 使用
* **Docker + PM2** —— 自託管

<Tip>
  開發階段請使用 `theo_sk_test_` 密鑰，以避免產生計費。
</Tip>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.