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

# Enviar mensagem

> Envio síncrono WhatsApp: aguarda o retorno imediato do provedor. Exige conteúdo ou anexos; fora da janela é necessário template. Texto e arquivos podem gerar vários records. Tipos interactive e location exigem as rotas próprias. Envio manual pode atribuir responsável e pausar fluxo WhatsApp ativo. `type` assume text quando omitido; para template, envie type=template e não envie body, pois o texto é enviado no lugar do template. Com type=template, os arquivos enviados servem apenas como mídia do cabeçalho. Cada arquivo aceita até 100 MB (16 MB para áudio); a falha de um arquivo volta em records com status=failed, ainda com resposta 201. Permissão da chave: crm/chats.write. O acesso também respeita a empresa e as permissões do usuário criador da chave.



## OpenAPI

````yaml /openapi.json post /integrations/external/chats/{id}/messages
openapi: 3.0.3
info:
  title: >-
    Integração Externa - Leads, Oportunidades, Tarefas, Arquivos, Propostas,
    Chats, Satisfação e Campos Personalizados
  version: 1.0.0
  description: >
    Documentação oficial da API externa da Wegly para campos personalizados,
    leads, oportunidades, tarefas, arquivos, propostas, chats e satisfação
    (`/integrations/external/custom-fields`, `/integrations/external/files`,
    `/integrations/external/leads`, `/integrations/external/deals`,
    `/integrations/external/tasks`, `/integrations/external/proposals`,
    `/integrations/external/chats` e `/integrations/external/satisfaction`).
    Todas as descrições estão em português e refletem as regras aplicadas pelo
    serviço.
servers:
  - url: https://api.wegly.com.br
    description: Ambiente de produção Wegly
security:
  - bearerAuth: []
tags:
  - name: Campos Personalizados
    description: >-
      Consulta dos campos personalizados disponíveis para uso nas integrações
      externas.
  - name: Arquivos
    description: >-
      Upload e consulta de arquivos vinculados diretamente a leads ou
      oportunidades. Arquivos de proposta usam as rotas de anexos em Propostas.
  - name: Leads
    description: >-
      Operações de listagem, criação, consulta e atualização de leads via
      integração externa.
  - name: Oportunidades
    description: Operações de criação de oportunidades (deals) via integração externa.
  - name: Tarefas
    description: >-
      Operações de listagem, criação, consulta, atualização e remoção de tarefas
      vinculadas a leads, oportunidades, entregas, pessoas, organizações ou
      clientes.
  - name: Satisfação
    description: >-
      Geração de links públicos para formulários de satisfação via integração
      externa.
  - name: Propostas
    description: >-
      Operações de listagem, criação, consulta, atualização e remoção de
      propostas via integração externa, incluindo seus anexos (arquivos e
      documentos da biblioteca).
  - name: Chats
    description: >-
      Operações principais de listagem, criação, consulta e resumo de não lidas
      de chats via integração externa.
paths:
  /integrations/external/chats/{id}/messages:
    post:
      tags:
        - Chats
      summary: Enviar mensagem
      description: >-
        Envio síncrono WhatsApp: aguarda o retorno imediato do provedor. Exige
        conteúdo ou anexos; fora da janela é necessário template. Texto e
        arquivos podem gerar vários records. Tipos interactive e location exigem
        as rotas próprias. Envio manual pode atribuir responsável e pausar fluxo
        WhatsApp ativo. `type` assume text quando omitido; para template, envie
        type=template e não envie body, pois o texto é enviado no lugar do
        template. Com type=template, os arquivos enviados servem apenas como
        mídia do cabeçalho. Cada arquivo aceita até 100 MB (16 MB para áudio); a
        falha de um arquivo volta em records com status=failed, ainda com
        resposta 201. Permissão da chave: crm/chats.write. O acesso também
        respeita a empresa e as permissões do usuário criador da chave.
      operationId: externalChatsSendMessage
      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: string
            format: uuid
          description: UUID da conversa.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SendExternalChatMessage'
            examples:
              texto:
                value:
                  type: text
                  body: Olá, tudo bem?
              template:
                value:
                  type: template
                  template:
                    name: saudacao_inicial
                    language: pt_BR
                  template_fields:
                    - component: BODY
                      type: TEXT
                      index: 1
                      value: João
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/SendExternalChatMessageMultipart'
            encoding:
              template:
                contentType: application/json
              template_fields:
                contentType: application/json
              files:
                style: form
                explode: true
              file:
                style: form
                explode: true
      responses:
        '201':
          description: Operação realizada.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatMessagesResponse'
        '400':
          description: Payload ou regra de negócio inválidos.
        '401':
          description: >-
            Chave de integração ausente, inválida, inativa ou expirada, ou
            domínio de origem não autorizado para a chave.
        '403':
          description: Permissão da chave ou do usuário insuficiente para o recurso.
        '404':
          description: Conversa ou recurso associado não encontrado no escopo acessível.
        '429':
          description: Limite de requisições da integração excedido.
        '500':
          description: Falha interna ou na comunicação com o provedor.
components:
  schemas:
    SendExternalChatMessage:
      type: object
      description: >-
        Payload para envio de mensagem textual, template ou mídia em um chat
        existente.
      properties:
        type:
          $ref: '#/components/schemas/SendExternalChatMessageTypeEnum'
        body:
          type: string
          description: >-
            Texto da mensagem. Se houver anexos, o texto é enviado como mensagem
            separada e também como legenda de cada imagem, vídeo ou documento.
            Com type=template, não envie body: o texto seria enviado no lugar do
            template. Texto aberto admite até 4096 caracteres.
        reference_wamid:
          type: string
          maxLength: 200
          description: >-
            WAMID ou UUID local de uma mensagem de referência pertencente ao
            chat; a API resolve o WAMID antes do envio.
        template:
          $ref: '#/components/schemas/ChatTemplateInfo'
        template_fields:
          type: array
          items:
            $ref: '#/components/schemas/ChatTemplateField'
      example:
        type: text
        body: Olá, tudo bem?
    SendExternalChatMessageMultipart:
      allOf:
        - $ref: '#/components/schemas/SendExternalChatMessage'
        - type: object
          description: >-
            Payload multipart para envio de mídia. Os campos `template` e
            `template_fields`, quando enviados por formulário, podem ser
            serializados como JSON.
          properties:
            files:
              type: array
              description: Arquivos enviados no campo `files`.
              items:
                type: string
                format: binary
              maxItems: 10
            file:
              type: array
              description: Arquivos enviados no campo alternativo `file`.
              items:
                type: string
                format: binary
              maxItems: 10
    ChatMessagesResponse:
      type: object
      properties:
        total:
          type: integer
          description: >-
            Quantidade de mensagens enviadas nesta operação; pode superar 1
            quando houver texto e anexos.
        records:
          type: array
          items:
            $ref: '#/components/schemas/ChatMessage'
      required:
        - total
        - records
    SendExternalChatMessageTypeEnum:
      type: string
      enum:
        - text
        - reaction
        - image
        - video
        - audio
        - document
        - location
        - template
        - interactive
        - call
      description: >-
        Valores aceitos pelo DTO. Quando omitido, assume text; o template não é
        inferido pelo conteúdo e exige type=template. interactive e location são
        recusados nesta rota com 400; use as rotas dedicadas.
    ChatTemplateInfo:
      type: object
      required:
        - name
        - language
      properties:
        name:
          type: string
        language:
          type: string
    ChatTemplateField:
      type: object
      required:
        - component
        - type
        - value
      properties:
        component:
          type: string
          enum:
            - HEADER
            - BODY
            - BUTTONS
        type:
          type: string
          enum:
            - TEXT
            - IMAGE
            - VIDEO
            - DOCUMENT
            - LOCATION
        value:
          type: string
          description: >-
            Valor do campo. Em campos IMAGE, VIDEO ou DOCUMENT, aceita uma URL
            http(s) ou `file:<n>`, em que n é a posição (a partir de 0) do
            arquivo enviado no mesmo formulário, contando primeiro os de `files`
            e depois os de `file`.
        index:
          type: number
        button_index:
          type: number
        card_index:
          type: number
    ChatMessage:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          $ref: '#/components/schemas/ChatMessageTypeEnum'
        origin:
          $ref: '#/components/schemas/ChatMessageOriginEnum'
        from_me:
          type: boolean
        sent_via:
          $ref: '#/components/schemas/ChatMessageSentViaEnum'
        status:
          $ref: '#/components/schemas/ChatMessageDeliveryStatusEnum'
        body_text:
          type: string
          nullable: true
        content_payload:
          type: object
          nullable: true
          additionalProperties: true
        reactions:
          type: array
          items:
            $ref: '#/components/schemas/ChatReaction'
        meta_timestamp:
          type: string
          format: date-time
        is_history:
          type: boolean
        history_phase:
          type: integer
          nullable: true
        history_chunk_order:
          type: integer
          nullable: true
        history_progress:
          type: integer
          nullable: true
        is_media_placeholder:
          type: boolean
        agent:
          type: object
          nullable: true
          properties:
            id:
              type: string
              format: uuid
            user:
              type: object
              allOf:
                - $ref: '#/components/schemas/ExternalUserSummary'
              nullable: true
        user:
          type: object
          allOf:
            - $ref: '#/components/schemas/ExternalUserSummary'
          nullable: true
        transcription:
          type: string
          nullable: true
        is_forwarded:
          type: boolean
        error_code:
          type: integer
          nullable: true
        error_message:
          type: string
          nullable: true
        created_at:
          type: string
          format: date-time
        media:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatMedia'
          nullable: true
        call:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatMessageCall'
          nullable: true
        quoted_message:
          $ref: '#/components/schemas/ChatQuotedMessage'
        whatsapp_ai_agent_id:
          type: string
          format: uuid
          nullable: true
          description: Agente de IA que enviou a mensagem; null para pessoas e automações.
      required:
        - id
        - type
        - origin
        - from_me
        - sent_via
        - status
        - body_text
        - transcription
        - meta_timestamp
        - created_at
        - media
        - call
    ChatMessageTypeEnum:
      type: string
      enum:
        - text
        - reaction
        - image
        - video
        - audio
        - document
        - template
        - interactive
        - location
        - call
        - contacts
        - unsupported
        - sticker
        - button
      description: >-
        Tipos mais comuns. Mensagens recebidas guardam o tipo informado pelo
        provedor, de modo que outros valores podem aparecer.
    ChatMessageOriginEnum:
      type: string
      enum:
        - INBOUND
        - API_OUTBOUND
        - MOBILE_APP_ECHO
        - SYSTEM
    ChatMessageSentViaEnum:
      type: string
      enum:
        - CONTACT
        - API
        - MOBILE_DEVICE
        - SYSTEM
    ChatMessageDeliveryStatusEnum:
      type: string
      enum:
        - processing
        - sent
        - delivered
        - read
        - failed
        - received
        - deleted
        - delivery_unknown
      description: >-
        Status persistido da mensagem; delivery_unknown indica que o resultado
        do envio ainda não foi confirmado.
    ChatReaction:
      type: object
      properties:
        id:
          type: string
          format: uuid
        emoji:
          type: string
        actor:
          type: string
          enum:
            - CONTACT
            - BUSINESS
            - SYSTEM
          description: '`SYSTEM` pode aparecer em reações do Instagram.'
        reactor_wa_id:
          type: string
        reactor_user_id:
          type: string
          format: uuid
          nullable: true
        created_at:
          type: string
          format: date-time
    ExternalUserSummary:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        avatar:
          type: string
          nullable: true
    ChatMedia:
      type: object
      properties:
        id:
          type: string
          format: uuid
        mime_type:
          type: string
        file_name:
          type: string
          nullable: true
        is_downloaded:
          type: boolean
        url:
          type: string
          nullable: true
      required:
        - id
        - mime_type
        - file_name
        - is_downloaded
        - url
    ChatMessageCall:
      type: object
      properties:
        id:
          type: string
          format: uuid
        status:
          type: string
          enum:
            - RINGING
            - IN_PROGRESS
            - COMPLETED
            - MISSED
            - REJECTED
            - FAILED
            - CANCELED
        direction:
          type: string
          enum:
            - INBOUND
            - OUTBOUND
        started_at:
          type: string
          format: date-time
          nullable: true
        ended_at:
          type: string
          format: date-time
          nullable: true
        duration_ms:
          type: integer
        recording_processed:
          type: boolean
        recording_available:
          type: boolean
        has_recording:
          type: boolean
    ChatQuotedMessage:
      type: object
      properties:
        id:
          type: string
          format: uuid
        type:
          $ref: '#/components/schemas/ChatMessageTypeEnum'
        origin:
          $ref: '#/components/schemas/ChatMessageOriginEnum'
        from_me:
          type: boolean
        sent_via:
          $ref: '#/components/schemas/ChatMessageSentViaEnum'
        status:
          $ref: '#/components/schemas/ChatMessageDeliveryStatusEnum'
        body_text:
          type: string
          nullable: true
        content_payload:
          type: object
          nullable: true
          additionalProperties: true
        reactions:
          type: array
          items:
            $ref: '#/components/schemas/ChatReaction'
        meta_timestamp:
          type: string
          format: date-time
        is_history:
          type: boolean
        history_phase:
          type: integer
          nullable: true
        history_chunk_order:
          type: integer
          nullable: true
        history_progress:
          type: integer
          nullable: true
        is_media_placeholder:
          type: boolean
        agent:
          type: object
          nullable: true
          properties:
            id:
              type: string
              format: uuid
            user:
              type: object
              allOf:
                - $ref: '#/components/schemas/ExternalUserSummary'
              nullable: true
        user:
          type: object
          allOf:
            - $ref: '#/components/schemas/ExternalUserSummary'
          nullable: true
        transcription:
          type: string
          nullable: true
        is_forwarded:
          type: boolean
        error_code:
          type: integer
          nullable: true
        error_message:
          type: string
          nullable: true
        created_at:
          type: string
          format: date-time
        media:
          type: object
          allOf:
            - $ref: '#/components/schemas/ChatMedia'
          nullable: true
        page:
          type: integer
          description: Página da mensagem citada na mesma ordenação/paginação.
        whatsapp_ai_agent_id:
          type: string
          format: uuid
          nullable: true
          description: Agente de IA que enviou a mensagem; null para pessoas e automações.
      required:
        - id
        - type
        - origin
        - status
        - page
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: API key
      description: >-
        Chave de integração com prefixo wegly_, enviada em Authorization: Bearer
        <chave>. Não é JWT. A chave deve estar ativa, não excluída e dentro da
        validade. Com allowed_domain, Origin (ou Referer na ausência de Origin)
        precisa informar o hostname permitido. A empresa e as permissões são
        obtidas pela chave.

````

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