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

# Histórico de chat

> Consulte o histórico de mensagens de um bot

Recupere o histórico de conversas de um bot para auditar interações, analisar métricas ou depurar fluxos. Este endpoint retorna mensagens enviadas e recebidas com suporte a paginação e filtros de tempo.

***

## Endpoint

```
GET https://api.jelou.ai/v1/external/messages/history/{botId}
```

***

## Parâmetros de Path

| Campo     | Localização | Tipo   | Obrigatório | Descrição                                                        |
| --------- | ----------- | ------ | ----------- | ---------------------------------------------------------------- |
| **botId** | Path        | string | Sim         | Identificador único do bot cujo histórico você deseja consultar. |

***

## Parâmetros de Query

| Campo         | Localização | Tipo    | Obrigatório | Valor padrão | Descrição                                                                    |
| ------------- | ----------- | ------- | ----------- | ------------ | ---------------------------------------------------------------------------- |
| **limit**     | Query       | integer | Não         | 10           | Número de mensagens a solicitar. Máximo: 50.                                 |
| **page**      | Query       | integer | Não         | 1            | Número da página.                                                            |
| **startAt**   | Query       | date    | Não         | -            | Data de início do intervalo a consultar. Formato ISO 8601.                   |
| **endAt**     | Query       | date    | Não         | -            | Data de término do intervalo a consultar. Formato ISO 8601.                  |
| **clientId**  | Query       | string  | Não         | -            | Filtra o histórico por um clientId específico associado às suas integrações. |
| **messageId** | Query       | string  | Não         | -            | Retorna a conversa que contém a mensagem com este identificador.             |

<Tip>
  Se você omitir campos opcionais, a API aplicará valores padrão para entregar a primeira página com as mensagens mais recentes.
</Tip>

***

## Exemplos de Requisição

### Consulta básica

```bash theme={null}
curl --request GET \
  --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=10&page=1' \
  --header 'Authorization: Basic {{Base64EncodedUsername:Password}}'
```

### Com filtro de data

```bash theme={null}
curl --request GET \
  --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=20&page=1&startAt=2025-01-01T00:00:00.000Z&endAt=2025-01-31T23:59:59.000Z' \
  --header 'Authorization: Basic {{Base64EncodedUsername:Password}}'
```

### Com filtro de cliente

```bash theme={null}
curl --request GET \
  --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=10&page=1&clientId=CLIENT_ID' \
  --header 'Authorization: Basic {{Base64EncodedUsername:Password}}'
```

***

## Respostas

<AccordionGroup>
  <Accordion title="200 - Resposta bem-sucedida">
    ```json theme={null}
    {
      "pagination": {
        "limit": 10,
        "page": 1,
        "total": 1,
        "offset": 0,
        "totalPages": 1
      },
      "_metadata": {},
      "results": [
        {
          "recipient": {
            "id": "RECIPIENT_ID",
            "names": "Example Customer"
          },
          "sender": {
            "id": "BOT_ID",
            "name": "My Bot",
            "type": "WhatsApp"
          },
          "by": "bot",
          "messageId": "msg-12345-67890-4a38-abcde-fghij",
          "status": "DELIVERED_USER",
          "bubble": {
            "type": "TEXT",
            "text": "Hello, welcome to Jelou"
          },
          "createdAt": "2025-01-15T10:30:00.000Z"
        }
      ]
    }
    ```
  </Accordion>

  <Accordion title="401 - Não Autorizado">
    ```json theme={null}
    {
      "message": "Authentication failed"
    }
    ```
  </Accordion>

  <Accordion title="404 - Não Encontrado">
    ```json theme={null}
    {
      "message": ["The Bot could not be found at the moment."],
      "statusMessage": "failed",
      "status": 0,
      "error": {
        "code": "E1019",
        "key": "BOT_NOT_FOUND",
        "description": "Error to be thrown when trying to get a Bot.",
        "developerMessages": {
          "es": "El botId no se encuentra en la base de datos o ha sido eliminado.",
          "en": "The botId is not found in the database or has been deleted."
        },
        "clientMessages": {
          "es": "El Bot no se pudo encontrar por el momento.",
          "en": "The Bot could not be found at the moment."
        }
      }
    }
    ```
  </Accordion>

  <Accordion title="422 - Entidade não processável">
    ```json theme={null}
    {
      "message": ["The values entered are not correct."],
      "statusMessage": "failed",
      "status": 0,
      "error": {
        "code": "E0422",
        "key": "VALIDATOR_ERROR",
        "description": "Error to be thrown when cannot process request because of incoming values",
        "developerMessages": {
          "es": "Los valores del request no son correctos para ser procesados.",
          "en": "The request values are not correct for processing."
        },
        "clientMessages": {
          "es": "Los valores ingresados no son correctos.",
          "en": "The values entered are not correct."
        }
      },
      "validationError": {
        "startAt": [
          {
            "es": "el campo startAt debe ser una fecha",
            "en": "the startAt field must be a Date"
          }
        ]
      }
    }
    ```
  </Accordion>

  <Accordion title="500 - Erro Interno do Servidor">
    ```json theme={null}
    {
      "message": ["We are having trouble processing your request. Please try again later."],
      "statusMessage": "failed",
      "status": 0,
      "error": {
        "code": "E0000",
        "key": "UNKNOWN_ERROR",
        "description": "Error to be thrown when it couldn't be determined the reason of failure",
        "developerMessages": {
          "es": "Error inesperado ocurrido, revisar logs.",
          "en": "Unexpected error occurred, check logs."
        },
        "clientMessages": {
          "es": "Estamos teniendo problemas procesando la solicitud. Por favor intenta más tarde.",
          "en": "We are having trouble processing your request. Please try again later."
        }
      }
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Detalhes da Resposta

### Objeto pagination

| Campo          | Tipo    | Descrição                        |
| -------------- | ------- | -------------------------------- |
| **limit**      | integer | Número de registros por página.  |
| **page**       | integer | Página atual.                    |
| **total**      | integer | Total de registros.              |
| **offset**     | integer | Deslocamento a partir do início. |
| **totalPages** | integer | Total de páginas disponíveis.    |

### Objeto results

| Campo         | Tipo   | Descrição                                                               |
| ------------- | ------ | ----------------------------------------------------------------------- |
| **recipient** | object | Informações do destinatário (id, names).                                |
| **sender**    | object | Informações do remetente (id, name, type).                              |
| **by**        | string | Indica quem enviou a mensagem: `bot` ou `user`.                         |
| **messageId** | string | Identificador único da mensagem.                                        |
| **status**    | string | Status da mensagem: `DELIVERED_USER`, `DELIVERED_CHANNEL`, `READ`, etc. |
| **bubble**    | object | Conteúdo da mensagem (type, text, mediaUrl, etc.).                      |
| **createdAt** | date   | Data de criação da mensagem no formato ISO 8601.                        |

***

## Limites e restrições

<Note>
  **Limites importantes:**

  * **limit**: O valor máximo permitido é `50`
  * **page**: Deve ser um inteiro positivo
  * **startAt/endAt**: Devem estar no formato ISO 8601 (ex.: `2025-01-15T10:30:00.000Z`)
</Note>


## OpenAPI

````yaml GET /v1/external/messages/history/{botId}
openapi: 3.1.0
info:
  title: Jelou API
  description: >-
    API for the Jelou platform. Send messages, manage campaigns, handle
    conversations, users, databases, and widgets.
  version: 1.0.0
servers:
  - url: https://api.jelou.ai
    description: Production server
security:
  - basicAuth: []
tags:
  - name: Messages
    description: Send messages to users
  - name: Campaigns
    description: HSM campaigns and templates
  - name: Conversations
    description: Chat history and metrics
  - name: Users
    description: User state and cache management
  - name: Resources
    description: Media resource management
  - name: Datum
    description: Database CRUD operations
  - name: Widget
    description: Widget and room management
  - name: PMA Custom
    description: External support panel integration
paths:
  /v1/external/messages/history/{botId}:
    get:
      tags:
        - Conversations
      summary: Get Chat History
      description: Retrieve message history for a bot with pagination and date filters.
      operationId: getChatHistory
      parameters:
        - name: botId
          in: path
          required: true
          schema:
            type: string
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
            maximum: 50
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: startAt
          in: query
          schema:
            type: string
            format: date-time
        - name: endAt
          in: query
          schema:
            type: string
            format: date-time
        - name: clientId
          in: query
          schema:
            type: string
        - name: messageId
          in: query
          schema:
            type: string
      responses:
        '200':
          description: History retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatHistoryResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
components:
  schemas:
    ChatHistoryResponse:
      type: object
      properties:
        pagination:
          $ref: '#/components/schemas/Pagination'
        _metadata:
          type: object
        results:
          type: array
          items:
            $ref: '#/components/schemas/ChatMessage'
    Pagination:
      type: object
      properties:
        limit:
          type: integer
        page:
          type: integer
        total:
          type: integer
        offset:
          type: integer
        totalPages:
          type: integer
    ChatMessage:
      type: object
      properties:
        recipient:
          type: object
          properties:
            id:
              type: string
            names:
              type: string
        sender:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
            type:
              type: string
        by:
          type: string
          enum:
            - bot
            - user
        messageId:
          type: string
        status:
          type: string
        bubble:
          type: object
          properties:
            type:
              type: string
            text:
              type: string
            mediaUrl:
              type: string
        createdAt:
          type: string
          format: date-time
    Error:
      type: object
      properties:
        message:
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        statusMessage:
          type: string
        status:
          type: integer
        error:
          type: object
          properties:
            code:
              type: string
            key:
              type: string
            description:
              type: string
            developerMessages:
              type: object
            clientMessages:
              type: object
        validationError:
          type: object
  responses:
    Unauthorized:
      description: Unauthorized - Invalid authentication credentials
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    NotFound:
      description: Not found - Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    UnprocessableEntity:
      description: Unprocessable entity - Validation error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: Basic authentication using Base64 encoded clientId:clientSecret

````