> 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.

# Bot do Telegram para transcrição

> **Note**
>
> **Guia prático** · Pressupõe que você concluiu o [guia de início rápido do Speech to Text ](/docs/pt/eleven-api/guides/cookbooks/speech-to-text) e tem um token de bot do Telegram e uma
> conta no Supabase.

## Introdução

Neste tutorial, você aprenderá a criar um bot do Telegram que transcreve mensagens de áudio e vídeo em mais de 90 idiomas usando TypeScript e o modelo ElevenLabs Scribe pela API de Speech to Text.

## Requisitos

* Uma conta ElevenLabs com uma [chave de API](https://elevenlabs.io/app/settings/api-keys).
* Uma conta no [Supabase](https://supabase.com) (você pode criar uma conta gratuita pelo [database.new](https://database.new)).
* A [CLI do Supabase](https://supabase.com/docs/guides/local-development) instalada na sua máquina.
* O [runtime Deno](https://docs.deno.com/runtime/getting_started/installation/) instalado na sua máquina e, opcionalmente, [configurado na sua IDE favorita](https://docs.deno.com/runtime/getting_started/setup_your_environment).
* Uma conta no [Telegram](https://telegram.org).

## Configuração

### Registre um bot do Telegram

Use o [BotFather](https://t.me/BotFather) para criar um novo bot do Telegram. Execute o comando `/newbot` e siga as instruções para criar um novo bot. Ao final, você receberá o token secreto do seu bot. Anote-o com segurança para a próxima etapa.

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

### Crie um projeto Supabase localmente

Depois de instalar a [CLI do Supabase](https://supabase.com/docs/guides/local-development), execute o comando a seguir para criar um novo projeto Supabase localmente:

```bash
supabase init
```

### Crie uma tabela de banco de dados para registrar os resultados das transcrições

Em seguida, crie uma nova tabela de banco de dados para registrar os resultados das transcrições:

```bash
supabase migrations new init
```

Isso criará um novo arquivo de migração no diretório `supabase/migrations`. Abra o arquivo e adicione o seguinte 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;
```

### Crie uma Supabase Edge Function para processar solicitações de webhook do Telegram

Em seguida, crie uma nova Edge Function para processar solicitações de webhook do Telegram:

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

Se você usa o VS Code ou o Cursor, selecione `y` quando a CLI perguntar "Generate VS Code settings for Deno? \[y/N]"!

### Configure as variáveis de ambiente

No diretório `supabase/functions`, crie um novo arquivo `.env` e adicione as seguintes variáveis:

**`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
```

### Dependências

O projeto usa algumas dependências:

* O [framework grammY](https://grammy.dev/) de código aberto para processar as solicitações de webhook do Telegram.
* A biblioteca [@supabase/supabase-js](https://supabase.com/docs/reference/javascript) para interagir com o banco de dados do Supabase.
* O [SDK JavaScript](/docs/pt/eleven-api/quickstart) da ElevenLabs para interagir com a API de Speech to Text.

Como a Supabase Edge Function usa o [runtime Deno](https://deno.land/), você não precisa instalar as dependências. Em vez disso, pode [importá-las](https://docs.deno.com/examples/npm/) com o prefixo `npm:`.

## Programe o bot do Telegram

No arquivo `scribe-bot/index.ts` que você acabou de criar, adicione o código a seguir:

**`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);
  }
});
```

### Análise detalhada do código

Há alguns pontos importantes sobre o código. Vamos analisá-lo passo a passo.

#### Processamento da solicitação recebida

Para processar a solicitação recebida, use o manipulador `Deno.serve`. O manipulador verifica se a solicitação contém o segredo correto e então a passa para a função `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);
  }
});
```

#### Processamento de mensagens de voz, áudio e vídeo

O framework grammY oferece uma forma prática de [filtrar](https://grammy.dev/guide/filter-queries#combining-multiple-queries) tipos específicos de mensagem. Neste caso, o bot escuta mensagens de voz, áudio e vídeo.

Usando o contexto da solicitação, o bot extrai os metadados do arquivo e usa `EdgeRuntime.waitUntil` das [tarefas em segundo plano do Supabase](https://supabase.com/docs/guides/functions/background-tasks) para executar a transcrição em segundo plano.

Assim, você pode dar uma resposta imediata ao usuário e processar a transcrição do arquivo em segundo plano.

```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!'
    );
  }
});
```

#### Transcrição com a API da ElevenLabs

Por fim, no worker em segundo plano, o bot usa o SDK JavaScript da ElevenLabs para transcrever o arquivo. Quando a transcrição é concluída, o bot responde ao usuário com a transcrição e grava uma entrada de log no banco de dados do Supabase usando [supabase-js](https://supabase.com/docs/reference/javascript).

```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 });
}
```

## Faça o deploy no Supabase

Se ainda não tiver feito isso, crie uma nova conta no Supabase em [database.new](https://database.new) e vincule o projeto local à sua conta do Supabase:

```bash
supabase link
```

### Aplique as migrações do banco de dados

Execute o comando a seguir para aplicar as migrações do banco de dados do diretório `supabase/migrations`:

```bash
supabase db push
```

Acesse o [editor de tabelas](https://supabase.com/dashboard/project/_/editor) no painel do Supabase e você verá uma tabela `transcription_logs` vazia.

![Tabela vazia](/docs/_fern-img/c1493deafcd6c53712dcb4fa7a44b3253b571ade0bb2e9c2b4fdb090088b0695.webp)

Por fim, execute o comando a seguir para fazer o deploy da Edge Function:

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

Acesse a [visualização de Edge Functions](https://supabase.com/dashboard/project/_/functions) no painel do Supabase e você verá a função `scribe-bot` implantada. Anote a URL da função, pois precisará dela mais tarde. Ela deve ser parecida com `https://<project-ref>.functions.supabase.co/scribe-bot`.

![Edge Function implantada](/docs/_fern-img/d12141a51a09563d625b379201de844800e0c7dcfa9e6c7f21484cbca7ff37cf.webp)

### Configure o webhook

Defina a URL do webhook do seu bot como `https://<PROJECT_REFERENCE>.functions.supabase.co/telegram-bot` (substituindo `<...>` pelos respectivos valores). Para isso, basta executar uma solicitação GET para a seguinte URL (no seu navegador, por exemplo):

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

Observe que `FUNCTION_SECRET` é o segredo que você definiu no arquivo `.env`.

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

### Defina os segredos da função

Agora que todos os seus segredos estão configurados localmente, você pode executar o comando a seguir para defini-los no seu projeto Supabase:

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

## Teste o bot

Por fim, você pode testar o bot enviando uma mensagem de voz, um arquivo de áudio ou vídeo.

![Testar o bot](/docs/_fern-img/a42c784e6324f15575e0299bafe02a253a2bdc57f2ad5844f83e5b64297780e7.webp)

Depois que a transcrição aparecer como resposta, volte ao editor de tabelas no painel do Supabase e você verá uma nova linha na tabela `transcription_logs`.

![Nova linha na tabela](/docs/_fern-img/25c008858276b7cd4af6f8e72473891176bb9e2ce62e7002af353a2dac205e06.webp)

## Próximas etapas

#### [Referência da API](/docs/pt/api-reference/speech-to-text)

Referência completa e parâmetros da API de Speech to Text.

#### [Integração com Twilio](/docs/pt/eleven-api/guides/how-to/text-to-speech/twilio)

Integre o TTS da ElevenLabs ao Twilio para aplicações de voz por telefone.