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

# Enviar mensagem

> Envia texto, mídia ou template. Requer scope `messages:send`.

Idempotência obrigatória via `client_message_id` (único por organização).
Retry com o mesmo id e mesmo body retorna `200` com `deduplicated: true`
e **não** reenvia à Meta.

Informe `thread_id` **ou** `to` (resolve/cria contato + thread).
O envio pela API não reabre conversa fechada nem altera atribuição.




## OpenAPI

````yaml /openapi.yaml post /api/public/v1/messages
openapi: 3.1.0
info:
  title: aidesk Public API
  version: 1.0.0
  summary: API pública para envio de mensagens, consulta de status e webhooks
  description: >
    Base oficial: `https://api.aideskbr.com`


    Autenticação com API key (`ak_live_...`). A organização é resolvida pela key
    —

    não envie `organization_id` nestas rotas.
  contact:
    name: aidesk
    url: https://developers.aideskbr.com
servers:
  - url: https://api.aideskbr.com
    description: Produção
security:
  - bearerAuth: []
  - apiKeyAuth: []
tags:
  - name: Health
    description: Verificação de autenticação e escopos
  - name: Messages
    description: Envio e consulta de mensagens
  - name: Webhooks
    description: Endpoints para receber eventos de delivery
paths:
  /api/public/v1/messages:
    post:
      tags:
        - Messages
      summary: Enviar mensagem
      description: >
        Envia texto, mídia ou template. Requer scope `messages:send`.


        Idempotência obrigatória via `client_message_id` (único por
        organização).

        Retry com o mesmo id e mesmo body retorna `200` com `deduplicated: true`

        e **não** reenvia à Meta.


        Informe `thread_id` **ou** `to` (resolve/cria contato + thread).

        O envio pela API não reabre conversa fechada nem altera atribuição.
      operationId: sendMessage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/SendMessageRequest'
            examples:
              text:
                summary: Texto com thread existente
                value:
                  channel_id: d8247551-1dde-4488-95cc-0402233701d9
                  thread_id: 11111111-1111-1111-1111-111111111111
                  client_message_id: crm-order-123-msg-1
                  type: text
                  text:
                    body: Olá, seu pedido saiu.
              template:
                summary: Template para número WhatsApp
                value:
                  channel_id: d8247551-1dde-4488-95cc-0402233701d9
                  to:
                    kind: whatsapp
                    handle: '5511999998888'
                  client_message_id: crm-welcome-1
                  type: template
                  template:
                    name: 1607
                    language: pt_BR
                    variables: {}
              document:
                summary: Documento com s3_key
                value:
                  thread_id: 11111111-1111-1111-1111-111111111111
                  client_message_id: crm-pdf-1
                  type: document
                  media:
                    s3_key: org/.../file.pdf
                    filename: boleto.pdf
                    mime_type: application/pdf
                  text:
                    body: Segue o boleto
      responses:
        '200':
          description: Retry idempotente (deduplicado) ou re-enqueue stale
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SendMessageResponse'
              example:
                message_id: 26c1638a-949a-4e52-a8ea-228d325bc697
                thread_id: 11111111-1111-1111-1111-111111111111
                contact_id: 22222222-2222-2222-2222-222222222222
                delivery_state: queued
                client_message_id: crm-order-123-msg-1
                deduplicated: true
        '201':
          description: Mensagem criada e enfileirada
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SendMessageResponse'
              example:
                message_id: 26c1638a-949a-4e52-a8ea-228d325bc697
                thread_id: 11111111-1111-1111-1111-111111111111
                contact_id: 22222222-2222-2222-2222-222222222222
                delivery_state: queued
                client_message_id: crm-order-123-msg-1
                deduplicated: false
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '409':
          $ref: '#/components/responses/Conflict'
        '422':
          $ref: '#/components/responses/Unprocessable'
        '429':
          $ref: '#/components/responses/RateLimited'
      security:
        - bearerAuth: []
        - apiKeyAuth: []
components:
  schemas:
    SendMessageRequest:
      type: object
      required:
        - client_message_id
        - type
      properties:
        client_message_id:
          type: string
          minLength: 1
          maxLength: 128
          description: Idempotência — único por organização
        type:
          type: string
          enum:
            - text
            - image
            - audio
            - video
            - document
            - template
        channel_id:
          type: string
          format: uuid
          description: UUID público do canal WhatsApp (recomendado)
        thread_id:
          type: string
          format: uuid
          description: UUID da conversa (um de `thread_id` ou `to`)
        to:
          $ref: '#/components/schemas/DestinationTo'
        text:
          type: object
          properties:
            body:
              type: string
        media:
          $ref: '#/components/schemas/MediaObject'
        template:
          $ref: '#/components/schemas/TemplateObject'
    SendMessageResponse:
      type: object
      required:
        - message_id
        - thread_id
        - contact_id
        - delivery_state
        - client_message_id
        - deduplicated
      properties:
        message_id:
          type: string
          format: uuid
        thread_id:
          type: string
          format: uuid
        contact_id:
          type: string
          format: uuid
        delivery_state:
          type: string
          examples:
            - queued
            - sent
            - delivered
            - read
            - failed
        client_message_id:
          type: string
        deduplicated:
          type: boolean
    DestinationTo:
      type: object
      required:
        - kind
        - handle
      properties:
        kind:
          type: string
          enum:
            - whatsapp
        handle:
          type: string
          description: Número E.164 sem `+` (ex. `5511999998888`)
          examples:
            - '5511999998888'
    MediaObject:
      type: object
      properties:
        s3_key:
          type: string
          description: Preferencial — chave de upload prévio
        url:
          type: string
          format: uri
          description: URL pública HTTPS (anti-SSRF aplicado)
        filename:
          type: string
          description: Obrigatório/recomendado para `document`
        mime_type:
          type: string
    TemplateObject:
      type: object
      properties:
        template_submission_id:
          type: string
          format: uuid
          description: Preferencial — ID interno da submission
        name:
          type: string
        language:
          type: string
          examples:
            - pt_BR
        variables:
          type: object
          additionalProperties:
            type: string
          description: Mapa de variáveis do template (ex. {"1":"Maria"})
    ErrorEnvelope:
      type: object
      required:
        - error
      properties:
        error:
          type: object
          required:
            - code
            - message
          properties:
            code:
              type: string
              examples:
                - api_key_required
                - rate_limited
                - idempotency_key_reused
            message:
              type: string
  responses:
    BadRequest:
      description: Validação / janela 24h / mídia inválida
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
    Unauthorized:
      description: API key ausente, inválida, revogada ou expirada
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          examples:
            missing:
              value:
                error:
                  code: api_key_required
                  message: API key ausente
    Forbidden:
      description: Scope ou canal não permitido
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          examples:
            scope:
              value:
                error:
                  code: missing_scope
                  message: Scope insuficiente
    Conflict:
      description: Idempotência ou identidade em conflito
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          examples:
            idempotency:
              value:
                error:
                  code: idempotency_key_reused
                  message: client_message_id já usado com body diferente
    Unprocessable:
      description: Regra de negócio (ex. template não aprovado)
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          examples:
            template:
              value:
                error:
                  code: template_not_approved
                  message: Template não aprovado
    RateLimited:
      description: Rate limit excedido
      headers:
        Retry-After:
          $ref: '#/components/headers/Retry-After'
        X-RateLimit-Limit:
          $ref: '#/components/headers/X-RateLimit-Limit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/X-RateLimit-Remaining'
        X-RateLimit-Reset:
          $ref: '#/components/headers/X-RateLimit-Reset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorEnvelope'
          example:
            error:
              code: rate_limited
              message: Rate limit exceeded
  headers:
    Retry-After:
      description: Segundos para retry (em 429)
      schema:
        type: integer
    X-RateLimit-Limit:
      description: Limite do bucket na janela atual
      schema:
        type: integer
    X-RateLimit-Remaining:
      description: Restante no bucket
      schema:
        type: integer
    X-RateLimit-Reset:
      description: Unix timestamp do reset
      schema:
        type: integer
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: ak_live
      description: 'Authorization: Bearer ak_live_<secret>'
    apiKeyAuth:
      type: apiKey
      in: header
      name: X-Api-Key
      description: 'Alternativa ao Bearer — X-Api-Key: ak_live_<secret>'

````