> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# 转录 Telegram 机器人

> **Note**
>
> **操作指南** · 假定你已完成[语音转文本快速入门](/docs/zh/eleven-api/guides/cookbooks/speech-to-text)，并拥有 Telegram 机器人令牌和 Supabase 账户。

## 简介

本教程将介绍如何使用 TypeScript 和语音转文本 API 中的 ElevenLabs Scribe 模型，构建一个可转录 90 多种语言音频和视频消息的 Telegram 机器人。

## 要求

* 拥有 [API 密钥](https://elevenlabs.io/app/settings/api-keys)的 ElevenLabs 账户。
* 一个 [Supabase](https://supabase.com) 账户（可通过 [database.new](https://database.new) 免费注册）。
* 本机已安装 [Supabase CLI](https://supabase.com/docs/guides/local-development)。
* 本机已安装 [Deno runtime](https://docs.deno.com/runtime/getting_started/installation/)，也可选择在[常用 IDE 中配置](https://docs.deno.com/runtime/getting_started/setup_your_environment)。
* 一个 [Telegram](https://telegram.org) 账户。

## 设置

### 注册 Telegram 机器人

使用 [BotFather](https://t.me/BotFather) 创建新的 Telegram 机器人。运行 `/newbot` 命令，并按照说明创建机器人。最后会收到私密机器人令牌。请安全保存，供下一步使用。

![BotFather](/docs/_fern-img/28aa856bb6ace1b49b82076a18f1e281a8a4f37bbb6cfc59c22d644564377248.webp)

### 在本地创建 Supabase 项目

安装 [Supabase CLI](https://supabase.com/docs/guides/local-development) 后，运行以下命令在本地创建新的 Supabase 项目：

```bash
supabase init
```

### 创建用于记录转录结果的数据库表

接下来，创建一个用于记录转录结果的数据库表：

```bash
supabase migrations new init
```

这将在 `supabase/migrations` 目录中创建新的迁移文件。打开该文件并添加以下 SQL：

**`supabase/migrations/init.sql`**

```sql supabase/migrations/init.sql
CREATE TABLE IF NOT EXISTS transcription_logs (
  id BIGSERIAL PRIMARY KEY,
  file_type VARCHAR NOT NULL,
  duration INTEGER NOT NULL,
  chat_id BIGINT NOT NULL,
  message_id BIGINT NOT NULL,
  username VARCHAR,
  transcript TEXT,
  language_code VARCHAR,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  error TEXT
);

ALTER TABLE transcription_logs ENABLE ROW LEVEL SECURITY;
```

### 创建处理 Telegram webhook 请求的 Supabase Edge Function

接下来，创建一个处理 Telegram webhook 请求的 Edge Function：

```bash
supabase functions new scribe-bot
```

如果使用 VS Code 或 Cursor，在 CLI 提示 "Generate VS Code settings for Deno? \[y/N]" 时选择 `y`！

### 设置环境变量

在 `supabase/functions` 目录中创建新的 `.env` 文件，并添加以下变量：

**`supabase/functions/.env`**

```env supabase/functions/.env
# Find / create an API key at https://elevenlabs.io/app/settings/api-keys
ELEVENLABS_API_KEY=your_api_key

# The bot token you received from the BotFather.
TELEGRAM_BOT_TOKEN=your_bot_token

# A random secret chosen by you to secure the function.
FUNCTION_SECRET=random_secret
```

### 依赖项

项目使用以下依赖项：

* 开源 [grammY Framework](https://grammy.dev/) 用于处理 Telegram webhook 请求。
* [@supabase/supabase-js](https://supabase.com/docs/reference/javascript) 库用于与 Supabase 数据库交互。
* ElevenLabs [JavaScript SDK](/docs/zh/eleven-api/quickstart) 用于与语音转文本 API 交互。

由于 Supabase Edge Function 使用 [Deno runtime](https://deno.land/)，无需安装依赖项，可通过 `npm:` 前缀[导入](https://docs.deno.com/examples/npm/)它们。

## 编写 Telegram 机器人代码

在新创建的 `scribe-bot/index.ts` 文件中添加以下代码：

**`supabase/functions/scribe-bot/index.ts`**

```ts supabase/functions/scribe-bot/index.ts
import { Bot, webhookCallback } from "https://deno.land/x/grammy@v1.34.0/mod.ts";
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { createClient } from "jsr:@supabase/supabase-js@2";
import { ElevenLabsClient } from "npm:elevenlabs@1.50.5";

console.log(`Function "elevenlabs-scribe-bot" up and running!`);

const elevenlabs = new ElevenLabsClient({
  apiKey: Deno.env.get("ELEVENLABS_API_KEY") || "",
});

const supabase = createClient(
  Deno.env.get("SUPABASE_URL") || "",
  Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") || ""
);

async function scribe({
  fileURL,
  fileType,
  duration,
  chatId,
  messageId,
  username,
}: {
  fileURL: string;
  fileType: string;
  duration: number;
  chatId: number;
  messageId: number;
  username: string;
}) {
  let transcript: string | null = null;
  let languageCode: string | null = null;
  let errorMsg: string | null = null;
  try {
    const sourceFileArrayBuffer = await fetch(fileURL).then((res) => res.arrayBuffer());
    const sourceBlob = new Blob([sourceFileArrayBuffer], {
      type: fileType,
    });

    const scribeResult = await elevenlabs.speechToText.convert({
      file: sourceBlob,
      model_id: "scribe_v2",
      tag_audio_events: false,
    });

    transcript = scribeResult.text;
    languageCode = scribeResult.language_code;

    // Reply to the user with the transcript
    await bot.api.sendMessage(chatId, transcript, {
      reply_parameters: { message_id: messageId },
    });
  } catch (error) {
    errorMsg = error.message;
    console.log(errorMsg);
    await bot.api.sendMessage(chatId, "Sorry, there was an error. Please try again.", {
      reply_parameters: { message_id: messageId },
    });
  }
  // Write log to Supabase.
  const logLine = {
    file_type: fileType,
    duration,
    chat_id: chatId,
    message_id: messageId,
    username,
    language_code: languageCode,
    error: errorMsg,
  };
  console.log({ logLine });
  await supabase.from("transcription_logs").insert({ ...logLine, transcript });
}

const telegramBotToken = Deno.env.get("TELEGRAM_BOT_TOKEN");
const bot = new Bot(telegramBotToken || "");
const startMessage = `Welcome to the ElevenLabs Scribe Bot\\! I can transcribe speech in 90\\+ languages with super high accuracy\\!
    \nTry it out by sending or forwarding me a voice message, video, or audio file\\!
    \n[Learn more about Scribe](https://elevenlabs.io/speech-to-text) or [build your own bot](https://elevenlabs.io/developers/guides/cookbooks/speech-to-text/telegram-bot)\\!
  `;
bot.command("start", (ctx) => ctx.reply(startMessage.trim(), { parse_mode: "MarkdownV2" }));

bot.on([":voice", ":audio", ":video"], async (ctx) => {
  try {
    const file = await ctx.getFile();
    const fileURL = `https://api.telegram.org/file/bot${telegramBotToken}/${file.file_path}`;
    const fileMeta = ctx.message?.video ?? ctx.message?.voice ?? ctx.message?.audio;

    if (!fileMeta) {
      return ctx.reply("No video|audio|voice metadata found. Please try again.");
    }

    // Run the transcription in the background.
    EdgeRuntime.waitUntil(
      scribe({
        fileURL,
        fileType: fileMeta.mime_type!,
        duration: fileMeta.duration,
        chatId: ctx.chat.id,
        messageId: ctx.message?.message_id!,
        username: ctx.from?.username || "",
      })
    );

    // Reply to the user immediately to let them know we received their file.
    return ctx.reply("Received. Scribing...");
  } catch (error) {
    console.error(error);
    return ctx.reply(
      "Sorry, there was an error getting the file. Please try again with a smaller file!"
    );
  }
});

const handleUpdate = webhookCallback(bot, "std/http");

Deno.serve(async (req) => {
  try {
    const url = new URL(req.url);
    if (url.searchParams.get("secret") !== Deno.env.get("FUNCTION_SECRET")) {
      return new Response("not allowed", { status: 405 });
    }

    return await handleUpdate(req);
  } catch (err) {
    console.error(err);
  }
});
```

### 代码详解

代码中有几个值得注意的地方。下面逐步讲解。

#### 处理传入请求

使用 `Deno.serve` 处理器处理传入请求。该处理器会检查请求是否包含正确的密钥，然后将请求传递给 `handleUpdate` 函数。

```ts {1,6,10}
const handleUpdate = webhookCallback(bot, 'std/http');

Deno.serve(async (req) => {
  try {
    const url = new URL(req.url);
    if (url.searchParams.get('secret') !== Deno.env.get('FUNCTION_SECRET')) {
      return new Response('not allowed', { status: 405 });
    }

    return await handleUpdate(req);
  } catch (err) {
    console.error(err);
  }
});
```

#### 处理语音、音频和视频消息

grammY 框架提供了便捷方式，可针对特定消息类型进行[筛选](https://grammy.dev/guide/filter-queries#combining-multiple-queries)。这里，机器人会监听语音、音频和视频消息。

机器人使用请求上下文提取文件元数据，然后通过 [Supabase Background Tasks](https://supabase.com/docs/guides/functions/background-tasks) `EdgeRuntime.waitUntil` 在后台运行转录任务。

这样可以立即回复用户，并在后台处理文件转录。

```ts {1,3,12,24}
bot.on([':voice', ':audio', ':video'], async (ctx) => {
  try {
    const file = await ctx.getFile();
    const fileURL = `https://api.telegram.org/file/bot${telegramBotToken}/${file.file_path}`;
    const fileMeta = ctx.message?.video ?? ctx.message?.voice ?? ctx.message?.audio;

    if (!fileMeta) {
      return ctx.reply('No video|audio|voice metadata found. Please try again.');
    }

    // Run the transcription in the background.
    EdgeRuntime.waitUntil(
      scribe({
        fileURL,
        fileType: fileMeta.mime_type!,
        duration: fileMeta.duration,
        chatId: ctx.chat.id,
        messageId: ctx.message?.message_id!,
        username: ctx.from?.username || '',
      })
    );

    // Reply to the user immediately to let them know we received their file.
    return ctx.reply('Received. Scribing...');
  } catch (error) {
    console.error(error);
    return ctx.reply(
      'Sorry, there was an error getting the file. Please try again with a smaller file!'
    );
  }
});
```

#### 使用 ElevenLabs API 转录

最后，在后台工作器中，机器人使用 ElevenLabs JavaScript SDK 转录文件。转录完成后，机器人会将转录文本回复给用户，并使用 [supabase-js](https://supabase.com/docs/reference/javascript) 向 Supabase 数据库写入日志条目。

```ts {29-38,43-46,54-65}
const elevenlabs = new ElevenLabsClient({
  apiKey: Deno.env.get('ELEVENLABS_API_KEY') || '',
});

const supabase = createClient(
  Deno.env.get('SUPABASE_URL') || '',
  Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') || ''
);

async function scribe({
  fileURL,
  fileType,
  duration,
  chatId,
  messageId,
  username,
}: {
  fileURL: string;
  fileType: string;
  duration: number;
  chatId: number;
  messageId: number;
  username: string;
}) {
  let transcript: string | null = null;
  let languageCode: string | null = null;
  let errorMsg: string | null = null;
  try {
    const sourceFileArrayBuffer = await fetch(fileURL).then((res) => res.arrayBuffer());
    const sourceBlob = new Blob([sourceFileArrayBuffer], {
      type: fileType,
    });

    const scribeResult = await elevenlabs.speechToText.convert({
      file: sourceBlob,
      model_id: 'scribe_v2',
      tag_audio_events: false,
    });

    transcript = scribeResult.text;
    languageCode = scribeResult.language_code;

    // Reply to the user with the transcript
    await bot.api.sendMessage(chatId, transcript, {
      reply_parameters: { message_id: messageId },
    });
  } catch (error) {
    errorMsg = error.message;
    console.log(errorMsg);
    await bot.api.sendMessage(chatId, 'Sorry, there was an error. Please try again.', {
      reply_parameters: { message_id: messageId },
    });
  }
  // Write log to Supabase.
  const logLine = {
    file_type: fileType,
    duration,
    chat_id: chatId,
    message_id: messageId,
    username,
    language_code: languageCode,
    error: errorMsg,
  };
  console.log({ logLine });
  await supabase.from('transcription_logs').insert({ ...logLine, transcript });
}
```

## 部署到 Supabase

如果还没有 Supabase 账户，请前往 [database.new](https://database.new) 创建一个，然后将本地项目关联到 Supabase 账户：

```bash
supabase link
```

### 应用数据库迁移

运行以下命令，应用 `supabase/migrations` 目录中的数据库迁移：

```bash
supabase db push
```

前往 Supabase 控制台的[表编辑器](https://supabase.com/dashboard/project/_/editor)，应能看到空的 `transcription_logs` 表。

![空表](/docs/_fern-img/c1493deafcd6c53712dcb4fa7a44b3253b571ade0bb2e9c2b4fdb090088b0695.webp)

最后，运行以下命令部署 Edge Function：

```bash
supabase functions deploy --no-verify-jwt scribe-bot
```

前往 Supabase 控制台的 [Edge Functions 视图](https://supabase.com/dashboard/project/_/functions)，应能看到已部署的 `scribe-bot` 函数。记下函数 URL，稍后会用到，格式应类似 `https://<project-ref>.functions.supabase.co/scribe-bot`。

![已部署的 Edge Function](/docs/_fern-img/d12141a51a09563d625b379201de844800e0c7dcfa9e6c7f21484cbca7ff37cf.webp)

### 设置 webhook

将机器人的 webhook URL 设为 `https://<PROJECT_REFERENCE>.functions.supabase.co/telegram-bot`（将 `<...>` 替换为相应值）。只需向以下 URL 发起 GET 请求即可完成设置（例如在浏览器中）：

```
https://api.telegram.org/bot<TELEGRAM_BOT_TOKEN>/setWebhook?url=https://<PROJECT_REFERENCE>.supabase.co/functions/v1/scribe-bot?secret=<FUNCTION_SECRET>
```

注意，`FUNCTION_SECRET` 是在 `.env` 文件中设置的密钥。

![设置 webhook](/docs/_fern-img/ac72044bd3df138da3d8a0df09e8413e8a9fd8a5c3156a525d6b13664854482f.webp)

### 设置函数密钥

现在已在本地设置好所有密钥，可以运行以下命令在 Supabase 项目中设置这些密钥：

```bash
supabase secrets set --env-file supabase/functions/.env
```

## 测试机器人

最后，可以向机器人发送语音消息、音频或视频文件来测试它。

![测试机器人](/docs/_fern-img/a42c784e6324f15575e0299bafe02a253a2bdc57f2ad5844f83e5b64297780e7.webp)

收到作为回复的转录文本后，返回 Supabase 控制台的表编辑器，应能在 `transcription_logs` 表中看到新行。

![表中的新行](/docs/_fern-img/25c008858276b7cd4af6f8e72473891176bb9e2ce62e7002af353a2dac205e06.webp)

## 后续步骤

#### [API 参考文档](/docs/zh/api-reference/speech-to-text)

完整的语音转文本 API 参考文档和参数。

#### [Twilio 集成](/docs/zh/eleven-api/guides/how-to/text-to-speech/twilio)

将 ElevenLabs TTS 与 Twilio 集成，用于基于电话的语音应用。