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

# Quick Start

> Do zero ao primeiro envio no Telegram: escolha bot ou conta pessoal e siga o passo a passo.

<Tip>
  Este guia leva você da **conta ao primeiro envio**. Escolha o modo abaixo: **bot** para produção ou **conta pessoal** só quando o bot não resolver.
</Tip>

## Em poucas palavras

* **Bot:** token do [@BotFather](https://t.me/BotFather), instância **ACTIVE** na hora, o usuário precisa ter dado **`/start`** antes
* **Conta pessoal:** crie a instância, **escaneie o QR** (ou envie o link) e conecte até ficar **ACTIVE**
* Nos dois casos você usa a **mesma API** de envio; só muda como conecta

Dúvida sobre qual escolher? Veja [Modos de conexão](/telegram-api/como-funciona/modos-de-conexao).

## Antes de começar

* Uma **chave de API** (`sk_live_...` ou `sk_test_...` para sandbox)
* Escopos de instância e envio na chave, [Escopos](/telegram-api/como-funciona/escopos-api-key)
* Troque `sk_live_xxxxx` e `https://api.notifique.dev` nos exemplos

<Note>
  Começando agora? Use `sk_test_...` e confira a [Caixa sandbox](/guides/sandbox/index).
</Note>

***

<Tabs>
  <Tab title="Bot">
    <Info>
      No Telegram, o **usuário precisa falar com o bot primeiro** (`/start`). Sem isso, o envio costuma falhar, é regra da Bot API.
    </Info>

    ### 1. Conectar o bot

    Quatro caminhos, escolha o que combina com sua integração:

    #### 1A, Pelo painel

    1. Telegram → Nova instância → **Bot**
    2. Cole o **token** do [@BotFather](https://t.me/BotFather)
    3. Quando o status ficar **ativo**, anote o **id da instância** e o `@botUsername`

    #### 1B, Pela API com token

    ```http theme={null}
    POST /v1/telegram/instances
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "name": "Meu atendimento",
      "mode": "BOT",
      "botToken": "123456789:ABCdefGHIjklMNOpqrsTUVwxyz"
    }
    ```

    Resposta esperada: **200** com status **ACTIVE**:

    ```json theme={null}
    {
      "success": true,
      "data": {
        "id": "clxx_inst_bot",
        "name": "Meu atendimento",
        "status": "ACTIVE",
        "mode": "BOT",
        "botUsername": "@meubot",
        "webhookUrl": "https://api.notifique.dev/webhooks/telegram/clxx_inst_bot"
      }
    }
    ```

    Token inválido → `TELEGRAM_BOT_TOKEN_INVALID`. Guarde o **`id`**.

    <Info>
      O `webhookUrl` é **informativo**. A Notifique já registra esse endpoint na Bot API do Telegram, você **não** precisa hospedar nem configurar nada com essa URL. Serve para auditoria e debug (conferir para onde a Telegram entrega os updates).
    </Info>

    ### 2. Pedir que o usuário inicie o bot

    Mande o link `https://t.me/SEU_BOT` e peça para tocar em **Iniciar** (`/start`).

    Liste quem já iniciou:

    ```http theme={null}
    GET /v1/telegram/chats?instanceId=clxx_inst&page=1&limit=20
    Authorization: Bearer sk_live_xxxxx
    ```

    Use `chatId` ou `@username` do retorno em `to`.

    ### 3. Enviar mensagem de texto

    ```http theme={null}
    POST /v1/telegram/messages
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "instanceId": "clxx_inst_bot",
      "to": ["123456789"],
      "type": "text",
      "payload": { "message": "Olá! Teste pelo Notifique." }
    }
    ```

    ### Enviar com template

    ```json theme={null}
    {
      "instanceId": "clxx_inst_bot",
      "to": ["123456789"],
      "type": "template",
      "payload": {
        "templateId": "ID_DO_TEMPLATE",
        "variables": { "code": "482910" }
      }
    }
    ```

    Referência: [template-api](/template-api/como-funciona/variaveis-disponiveis-e-crud).

    `to` é um **array** (até **100** destinatários). Pode usar `@username` se o chat já existir.

    Resposta esperada: **202**:

    ```json theme={null}
    {
      "success": true,
      "data": {
        "messageIds": ["cltg1..."],
        "telegramIds": ["cltg1..."],
        "status": "QUEUED",
        "count": 1
      }
    }
    ```
  </Tab>

  <Tab title="Conta pessoal">
    <Warning>
      Use conta pessoal **só** quando o bot não resolver. Automatizar DM em massa viola os Termos do Telegram. É obrigatório `acceptUserTerms: true`.
    </Warning>

    ### 1. Criar instância e conectar

    Quatro caminhos, escolha o que combina com sua integração:

    #### 1A, Pelo painel

    1. Telegram → Nova instância → **Conta (USER)**
    2. Aceite os **termos de uso** exibidos
    3. Escaneie o **QR** no app Telegram ou abra o link de login
    4. Quando o status ficar **ativo**, anote o **id da instância**

    #### 1B, Pela API com QR na sua interface

    Cria a conexão e devolve o QR em `connection`, igual ao WhatsApp não oficial:

    ```http theme={null}
    POST /v1/telegram/instances
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "name": "Conta suporte",
      "mode": "USER",
      "acceptUserTerms": true
    }
    ```

    Resposta esperada: **200** com status **PENDING** e o QR em `connection`:

    ```json theme={null}
    {
      "success": true,
      "data": {
        "id": "clxx_inst_user",
        "name": "Conta suporte",
        "status": "PENDING",
        "mode": "USER",
        "connection": {
          "status": "WAITING_QR",
          "loginUrl": "tg://login?token=...",
          "expiresSeconds": 30,
          "base64": "data:image/png;base64,..."
        },
        "code": "TELEGRAM_USER_PENDING_SESSION"
      }
    }
    ```

    Use `connection.base64` para mostrar o **QR** na sua UI ou abra `connection.loginUrl` no app Telegram.

    #### 1C, Pela API com link para o cliente escanear

    Passe `generateShareableLink: true` para receber também um link hospedado, útil quando quem vai escanear não está na sua tela:

    ```http theme={null}
    POST /v1/telegram/instances
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "name": "Conta suporte",
      "mode": "USER",
      "acceptUserTerms": true,
      "generateShareableLink": true
    }
    ```

    Resposta esperada: **200** com QR **e** link compartilhável:

    ```json theme={null}
    {
      "success": true,
      "data": {
        "id": "clxx_inst_user",
        "name": "Conta suporte",
        "status": "PENDING",
        "mode": "USER",
        "connection": {
          "status": "WAITING_QR",
          "loginUrl": "tg://login?token=...",
          "expiresSeconds": 30,
          "base64": "data:image/png;base64,..."
        },
        "shareableLink": {
          "hostedUrl": "https://api.notifique.dev/w/instance-connect/...?token=...",
          "embedUrl": "https://api.notifique.dev/w/embed/instance-connect/...?token=...",
          "publicId": "..."
        },
        "code": "TELEGRAM_USER_PENDING_SESSION"
      }
    }
    ```

    Envie `shareableLink.hostedUrl` para o cliente abrir e concluir o login. Quando conectar, o status fica **ativo**.

    <Warning>
      Quem tiver o link pode autenticar a sessão na instância. Depois do uso, rotacione o secret com `POST /v1/telegram/instances/:instanceId/connect-page/rotate-secret`.
    </Warning>

    #### 1D, Pela API com string de sessão

    Útil com **2FA** ou quando o QR interativo não funciona, crie a instância USER primeiro, depois:

    ```http theme={null}
    POST /v1/telegram/instances/clxx_inst_user/session
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "sessionString": "SUA_STRING_DE_SESSAO"
    }
    ```

    Instância passa para **ACTIVE**. **409** ao pedir QR em paralelo: `TELEGRAM_QR_LOGIN_IN_PROGRESS`.

    <Info>
      Resumo: **painel** para o caminho mais simples; **API com QR** para embutir o código na sua UI; **`generateShareableLink: true`** quando outra pessoa precisa escanear; **sessão** quando o QR não resolve.
    </Info>

    ### 2. Renovar o QR (se expirar)

    O QR expira rápido. Peça outro **sem criar instância nova**:

    ```http theme={null}
    GET /v1/telegram/instances/clxx_inst_user/qr
    Authorization: Bearer sk_live_xxxxx
    ```

    Enquanto prepara (`CONNECTING`):

    ```json theme={null}
    {
      "success": true,
      "data": {
        "status": "CONNECTING",
        "loginUrl": null,
        "expiresSeconds": 0,
        "base64": null
      }
    }
    ```

    QR pronto (`WAITING_QR`):

    ```json theme={null}
    {
      "success": true,
      "data": {
        "status": "WAITING_QR",
        "loginUrl": "tg://login?token=...",
        "expiresSeconds": 30,
        "base64": "data:image/png;base64,..."
      }
    }
    ```

    Você também pode receber um novo QR por [webhook](/telegram-api/como-funciona/eventos-do-webhooks) (`telegram.instance.qrcode`).

    ### 3. Recuperar o link compartilhável depois

    Perdeu o `hostedUrl` da criação? Consulte ou habilite de novo, mesmo padrão do WhatsApp:

    **Ver status** (URLs só aparecem se o secret ainda estiver disponível no servidor):

    ```http theme={null}
    GET /v1/telegram/instances/clxx_inst_user/connect-page
    Authorization: Bearer sk_live_xxxxx
    ```

    **Habilitar ou gerar de novo** (devolve `shareableLink`):

    ```http theme={null}
    POST /v1/telegram/instances/clxx_inst_user/connect-page/enable
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {}
    ```

    Resposta esperada: **200** com `hostedUrl` e `embedUrl`.

    **Invalidar links antigos** (se o link vazou ou o cliente já conectou):

    ```http theme={null}
    POST /v1/telegram/instances/clxx_inst_user/connect-page/rotate-secret
    Authorization: Bearer sk_live_xxxxx
    ```

    **Desligar a página pública:**

    ```http theme={null}
    POST /v1/telegram/instances/clxx_inst_user/connect-page/disable
    Authorization: Bearer sk_live_xxxxx
    ```

    ### 4. Enviar mensagem de texto

    Com instância **ACTIVE**:

    ```http theme={null}
    POST /v1/telegram/messages
    Content-Type: application/json
    Authorization: Bearer sk_live_xxxxx
    ```

    ```json theme={null}
    {
      "instanceId": "clxx_inst_user",
      "to": ["123456789"],
      "type": "text",
      "payload": { "message": "Olá pela conta conectada." }
    }
    ```

    Resposta esperada: **202** (mesmo formato da aba Bot).
  </Tab>
</Tabs>

***

## Depois do primeiro envio

* **Liste enviados:** `GET /v1/telegram/messages`
* **Cancele** na fila: `POST /v1/telegram/messages/:id/cancel` (webhook `telegram.cancelled`)
* **Inbound:** `GET /v1/telegram/messages/inbound`, configure em Settings → Received messages
* **Webhooks:** `telegram.sent`, `telegram.received`, `telegram.failed`, **não** use `message.*` (WhatsApp). Guia: [Eventos dos webhooks](/telegram-api/como-funciona/eventos-do-webhooks)

## Todos os tipos de envio

Na referência da API (aba Telegram), abra **Enviar mensagem no Telegram** (`POST /v1/...`) e escolha o exemplo no playground: Texto, Imagem, Vídeo, Áudio, Documento, Localização, Template, Agendada.

## Próximos passos

* [Introdução](/telegram-api/como-funciona/introducao)
* [Modos de conexão](/telegram-api/como-funciona/modos-de-conexao)
* [Escopos](/telegram-api/como-funciona/escopos-api-key)
