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

# Conversas de agentes

> Consulte conversas atendidas por agentes humanos

Recupere conversas atendidas por um agente humano para analisar tempos de resposta, estados de encerramento e atribuições. Você recebe metadados sobre operadores, usuários e bots envolvidos dentro de um intervalo de datas definido.

***

## Endpoint

```
POST https://api.jelou.ai/v1/metrics/conversations/attended/external
```

***

## Autenticação

| Campo             | Localização | Tipo   | Obrigatório | Descrição                                       |
| ----------------- | ----------- | ------ | ----------- | ----------------------------------------------- |
| **Authorization** | Header      | string | Sim         | Credenciais no formato `clientId:clientSecret`. |

***

## Parâmetros de Query

| Campo     | Localização | Tipo    | Obrigatório | Valor padrão | Descrição                              |
| --------- | ----------- | ------- | ----------- | ------------ | -------------------------------------- |
| **limit** | Query       | integer | Não         | 10           | Número máximo de conversas por página. |
| **page**  | Query       | integer | Não         | 1            | Número da página para paginação.       |

***

## Corpo da Requisição

| Campo       | Tipo    | Obrigatório | Descrição                                                                              |
| ----------- | ------- | ----------- | -------------------------------------------------------------------------------------- |
| **startAt** | string  | Sim         | Data de início do intervalo no formato ISO 8601. Exemplo: `2025-01-01T00:00:00-05:00`  |
| **endAt**   | string  | Sim         | Data de término do intervalo no formato ISO 8601. Exemplo: `2025-01-01T23:59:59-05:00` |
| **getJson** | boolean | Sim         | Deve ser `true` para receber a resposta em formato JSON.                               |

<Tip>
  Use janelas de tempo delimitadas para otimizar a consulta e evitar intervalos muito amplos se você gerencia altos volumes de conversas.
</Tip>

***

## Exemplos de Requisição

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl -X POST 'https://api.jelou.ai/v1/metrics/conversations/attended/external?limit=10' \
      -H 'Authorization: <clientId>:<clientSecret>' \
      -H 'Content-Type: application/json;charset=UTF-8' \
      -d '{
        "startAt": "2025-01-01T00:00:00-05:00",
        "endAt": "2025-01-01T23:59:59-05:00",
        "getJson": true
      }'
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const axios = require('axios');

    axios({
      method: 'POST',
      url: 'https://api.jelou.ai/v1/metrics/conversations/attended/external',
      params: { limit: 10 },
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'Authorization': '<clientId>:<clientSecret>'
      },
      data: {
        startAt: '2025-01-01T00:00:00-05:00',
        endAt: '2025-01-01T23:59:59-05:00',
        getJson: true
      }
    });
    ```
  </Tab>
</Tabs>

***

## Respostas

<AccordionGroup>
  <Accordion title="200 - Resposta bem-sucedida">
    ```json theme={null}
    {
      "message": ["Retrieving conversations succeeded"],
      "status": "success",
      "results": [
        {
          "_id": "CONVERSATION_ID",
          "operator": {
            "names": "OPERATOR_NAME"
          },
          "user": {
            "id": "ID"
          },
          "bot": {
            "name": "BOT_NAME"
          },
          "company": {
            "id": "COMPANY_ID"
          },
          "assignationMethod": {
            "teamName": "TEAM_NAME"
          },
          "state": "expired",
          "endedReason": "expired",
          "startAt": "2023-06-08 15:52:41",
          "endAt": "2023-06-08 23:07:56",
          "origin": "ticket",
          "timeRepliedOperator": 795880,
          "conversationDuration": 26115953
        }
      ],
      "pagination": {
        "limit": 1,
        "total": 61,
        "offset": 0,
        "totalPages": 61
      },
      "links": [
        {
          "number": 1,
          "url": "/v1/metrics/conversations/attended/external?limit=1&page=1"
        },
        {
          "number": 2,
          "url": "/v1/metrics/conversations/attended/external?limit=1&page=2"
        }
      ]
    }
    ```
  </Accordion>

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

  <Accordion title="429 - Muitas Requisições">
    ```json theme={null}
    {
      "message": "Rate limit exceeded"
    }
    ```
  </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
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Detalhes da Resposta

### Objeto results

| Campo                    | Tipo   | Descrição                                                      |
| ------------------------ | ------ | -------------------------------------------------------------- |
| **\_id**                 | string | Identificador único da conversa.                               |
| **operator**             | object | Informações sobre o operador que atendeu a conversa (`names`). |
| **user**                 | object | Informações do usuário (`id`).                                 |
| **bot**                  | object | Informações do bot associado (`name`).                         |
| **company**              | object | Informações da empresa (`id`).                                 |
| **assignationMethod**    | object | Método de atribuição e equipe (`teamName`).                    |
| **state**                | string | Estado da conversa: `active`, `closed`, `resolved`, `expired`. |
| **endedReason**          | string | Motivo pelo qual a conversa terminou.                          |
| **startAt**              | string | Data e hora de início da conversa.                             |
| **endAt**                | string | Data e hora de término da conversa.                            |
| **origin**               | string | Origem da conversa (ex.: `ticket`).                            |
| **timeRepliedOperator**  | number | Tempo de resposta do operador em milissegundos.                |
| **conversationDuration** | number | Duração total da conversa em milissegundos.                    |

### Objeto pagination

| Campo          | Tipo    | Descrição                                              |
| -------------- | ------- | ------------------------------------------------------ |
| **limit**      | integer | Conversas retornadas por página.                       |
| **total**      | integer | Total de conversas que correspondem aos filtros.       |
| **offset**     | integer | Conversas ignoradas de acordo com a página solicitada. |
| **totalPages** | integer | Número total de páginas disponíveis.                   |

### Objeto links

| Campo      | Tipo    | Descrição                              |
| ---------- | ------- | -------------------------------------- |
| **number** | integer | Número da página.                      |
| **url**    | string  | URL relativa para acessar essa página. |

***

## Métricas de desempenho

<Tip>
  Use os campos `timeRepliedOperator` e `conversationDuration` para analisar a eficiência da sua equipe de suporte:

  * **timeRepliedOperator**: Mede o tempo que um agente leva para dar a primeira resposta (em milissegundos).
  * **conversationDuration**: Mede a duração total desde o início até o encerramento da conversa (em milissegundos).
</Tip>


## OpenAPI

````yaml POST /v1/metrics/conversations/attended/external
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/metrics/conversations/attended/external:
    post:
      tags:
        - Conversations
      summary: Get Advisor Conversations
      description: Retrieve conversations attended by human advisors within a date range.
      operationId: getAdvisorConversations
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
        - name: page
          in: query
          schema:
            type: integer
            default: 1
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AdvisorConversationsRequest'
      responses:
        '200':
          description: Conversations retrieved successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AdvisorConversationsResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '429':
          description: Rate limit exceeded
components:
  schemas:
    AdvisorConversationsRequest:
      type: object
      required:
        - startAt
        - endAt
        - getJson
      properties:
        startAt:
          type: string
          format: date-time
        endAt:
          type: string
          format: date-time
        getJson:
          type: boolean
    AdvisorConversationsResponse:
      type: object
      properties:
        message:
          type: array
          items:
            type: string
        status:
          type: string
        results:
          type: array
          items:
            $ref: '#/components/schemas/AdvisorConversation'
        pagination:
          $ref: '#/components/schemas/Pagination'
        links:
          type: array
          items:
            type: object
    AdvisorConversation:
      type: object
      properties:
        _id:
          type: string
        operator:
          type: object
          properties:
            names:
              type: string
        user:
          type: object
          properties:
            id:
              type: string
        bot:
          type: object
          properties:
            name:
              type: string
        company:
          type: object
          properties:
            id:
              type: string
        assignationMethod:
          type: object
          properties:
            teamName:
              type: string
        state:
          type: string
          enum:
            - active
            - closed
            - resolved
            - expired
        endedReason:
          type: string
        startAt:
          type: string
        endAt:
          type: string
        origin:
          type: string
        timeRepliedOperator:
          type: integer
        conversationDuration:
          type: integer
    Pagination:
      type: object
      properties:
        limit:
          type: integer
        page:
          type: integer
        total:
          type: integer
        offset:
          type: integer
        totalPages:
          type: integer
    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'
    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

````