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

# Agendar mensagem

> Agendamento WhatsApp. scheduled_at deve estar no futuro. Texto/anexos só podem ser agendados dentro de session_expires_at; após a janela é obrigatório template. cancel_on_inbound=true cancela o envio pendente se houver interação inbound. 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}/scheduled-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}/scheduled-messages:
    post:
      tags:
        - Chats
      summary: Agendar mensagem
      description: >-
        Agendamento WhatsApp. scheduled_at deve estar no futuro. Texto/anexos só
        podem ser agendados dentro de session_expires_at; após a janela é
        obrigatório template. cancel_on_inbound=true cancela o envio pendente se
        houver interação inbound. 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: externalChatsCreateScheduled
      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/CreateExternalChatScheduledMessage'
          multipart/form-data:
            schema:
              $ref: '#/components/schemas/CreateExternalChatScheduledMessageMultipart'
            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/ChatScheduledMessage'
        '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:
    CreateExternalChatScheduledMessage:
      type: object
      properties:
        scheduled_at:
          type: string
          format: date-time
          description: Data/hora futura com fuso, em ISO 8601.
        cancel_on_inbound:
          type: boolean
          default: false
        type:
          type: string
          enum:
            - text
            - template
          description: Quando omitido, template se houver template; caso contrário, text.
        body:
          type: string
        template:
          $ref: '#/components/schemas/ChatTemplateInfo'
        template_fields:
          type: array
          items:
            $ref: '#/components/schemas/ChatTemplateField'
        reference_wamid:
          type: string
          maxLength: 200
      required:
        - scheduled_at
    CreateExternalChatScheduledMessageMultipart:
      type: object
      properties:
        scheduled_at:
          type: string
          format: date-time
          description: Data/hora futura com fuso, em ISO 8601.
        cancel_on_inbound:
          type: boolean
          default: false
        type:
          type: string
          enum:
            - text
            - template
          description: Quando omitido, template se houver template; caso contrário, text.
        body:
          type: string
        template:
          $ref: '#/components/schemas/ChatTemplateInfo'
        template_fields:
          type: array
          items:
            $ref: '#/components/schemas/ChatTemplateField'
        reference_wamid:
          type: string
          maxLength: 200
        files:
          type: array
          items:
            type: string
            format: binary
          maxItems: 10
        file:
          type: array
          items:
            type: string
            format: binary
          maxItems: 10
      required:
        - scheduled_at
      description: >-
        No multipart, template e template_fields aceitam JSON serializado. Use
        files ou file para os anexos.
    ChatScheduledMessage:
      type: object
      properties:
        id:
          type: string
          format: uuid
        chat_id:
          type: string
          format: uuid
        company_id:
          type: string
          format: uuid
        is_scheduled:
          type: boolean
          enum:
            - true
        status:
          type: string
          enum:
            - PENDING
            - PROCESSING
            - SENT
            - CANCELED
            - FAILED
        message_kind:
          type: string
          enum:
            - OPEN_MESSAGE
            - TEMPLATE
        cancel_reason:
          type: string
          enum:
            - USER_REQUEST
            - CHAT_INTERACTION
            - TEMPLATE_INVALID_OR_UNAVAILABLE
          nullable: true
        cancel_reason_description:
          type: string
          nullable: true
        failure_reason:
          type: string
          nullable: true
        cancel_on_inbound:
          type: boolean
        scheduled_at:
          type: string
          format: date-time
        processed_at:
          type: string
          format: date-time
          nullable: true
        sent_at:
          type: string
          format: date-time
          nullable: true
        canceled_at:
          type: string
          format: date-time
          nullable: true
        created_at:
          type: string
          format: date-time
        updated_at:
          type: string
          format: date-time
        created_by_user_id:
          type: string
          format: uuid
        sender_agent_id:
          type: string
          format: uuid
          nullable: true
        canceled_by_user_id:
          type: string
          format: uuid
          nullable: true
        payload:
          type: object
          properties:
            type:
              type: string
              enum:
                - text
                - template
            body:
              type: string
            template:
              $ref: '#/components/schemas/ChatTemplateInfo'
            template_fields:
              type: array
              items:
                $ref: '#/components/schemas/ChatTemplateField'
            reference_wamid:
              type: string
          required:
            - type
        attachments:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
                format: uuid
              file_name:
                type: string
              mime_type:
                type: string
              file_size:
                type: number
        sent_message_ids:
          type: array
          items:
            type: string
            format: uuid
        whatsapp_ai_agent_id:
          type: string
          format: uuid
          nullable: true
          description: >-
            Agente de IA que criou o agendamento; null para agendamentos criados
            por pessoas ou pela integração.
    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
  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.