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

# Encerrar conversa

> Encerra uma conversa ativa com um usuário final

## Descrição

Encerra uma conversa ativa no painel de atendimento externo. Permite especificar uma mensagem de encerramento que será enviada ao usuário e o motivo do encerramento.

Ao ser executado, o Jelou emite o evento `conversation.close` para o webhook configurado na integração.

## Endpoint

```
POST https://gateway.jelou.ai/platform/v1/external-support/{projectId}/conversations/close
```

## Parâmetros de rota

<ParamField path="projectId" type="string" required>
  Identificador único do projeto Jelou a partir do qual a conversa é encerrada.
</ParamField>

## Parâmetros do corpo

<ParamField body="botId" type="string" required>
  Identificador do bot do Jelou associado à conversa.
</ParamField>

<ParamField body="userId" type="string" required>
  Identificador do usuário final cuja conversa se deseja encerrar.
</ParamField>

<ParamField body="redirectPayload" type="object">
  Mensagem que será enviada ao usuário no momento do encerramento da conversa.

  * `type` — Tipo de mensagem: `text` ou `edge`.
  * `text` — Texto da mensagem de encerramento (quando `type` é `text`).
</ParamField>

## Autenticação

Todas as requisições devem incluir o cabeçalho `x-api-key` com a API key do projeto Jelou.

```
x-api-key: API_KEY
```

## Exemplo de requisição

O exemplo a seguir encerra a conversa do usuário `USER_ID` e inclui uma mensagem de encerramento:

```bash cURL theme={null}
curl --request POST \
  --url https://gateway.jelou.ai/platform/v1/external-support/PROJECT_ID/conversations/close \
  --header 'x-api-key: API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "botId": "BOT_ID",
    "userId": "USER_ID",
    "redirectPayload": {
      "type": "text",
      "text": "Mensagem de encerramento da conversa"
    }
  }'
```

## Respostas

| Código | Status                | Descrição                                                                 |
| ------ | --------------------- | ------------------------------------------------------------------------- |
| 200    | OK                    | Conversa encerrada com sucesso.                                           |
| 401    | Unauthorized          | Credenciais de autenticação inválidas ou ausentes.                        |
| 404    | Not Found             | Bot ou usuário não encontrado.                                            |
| 422    | Unprocessable Entity  | Os campos enviados contêm valores inválidos ou não passam nas validações. |
| 500    | Internal Server Error | Erro interno do servidor.                                                 |

## Exemplo de resposta

```json theme={null}
{
  "message": [
    "Conversation closed successfully"
  ],
  "statusMessage": "success",
  "status": 1,
  "data": {
    "conversationId": "CONVERSATION_ID",
    "status": "closed",
    "endedReason": "closed_by_operator"
  }
}
```

***

## Evento webhook `conversation.close`

Ao executar este recurso, o Jelou emitirá o evento `conversation.close` ao webhook configurado na integração. O payload inclui o motivo do encerramento e a mensagem enviada ao usuário.

```json theme={null}
{
  "event": "conversation.close",
  "timestamp": 1777992928697,
  "field": "conversation",
  "object": "conversation_event",
  "event_type": "close",
  "project_id": "PROJECT_ID",
  "room_id": "ROOM_ID",
  "contact": {
    "id": "USER_ID",
    "name": "USER_NAME"
  },
  "conversation": {
    "id": "CONVERSATION_ID"
  },
  "bot": {
    "id": "BOT_ID",
    "name": "BOT_NAME"
  },
  "value": {
    "reason": "closed_by_operator",
    "redirectPayload": {
      "type": "text",
      "text": "Mensagem de encerramento da conversa"
    }
  }
}
```

### Campos do payload

| Campo                        | Tipo   | Descrição                                                    |
| ---------------------------- | ------ | ------------------------------------------------------------ |
| `event`                      | string | Nome do evento: `conversation.close`                         |
| `timestamp`                  | number | Marca de tempo Unix em milissegundos do momento do evento.   |
| `project_id`                 | string | Identificador do projeto Jelou.                              |
| `room_id`                    | string | Identificador da sala de conversa.                           |
| `contact.id`                 | string | Identificador do usuário final.                              |
| `contact.name`               | string | Nome do usuário final.                                       |
| `conversation.id`            | string | Identificador único da conversa encerrada.                   |
| `bot.id`                     | string | Identificador do bot associado.                              |
| `bot.name`                   | string | Nome do bot associado.                                       |
| `value.reason`               | string | Motivo do encerramento: `closed_by_operator`.                |
| `value.redirectPayload.type` | string | Tipo da mensagem de encerramento: `text` ou `edge`.          |
| `value.redirectPayload.text` | string | Texto da mensagem enviada ao usuário ao encerrar (opcional). |


## OpenAPI

````yaml POST /v1/external-support/{projectId}/conversations/close
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-support/{projectId}/conversations/close:
    servers:
      - url: https://gateway.jelou.ai/platform
        description: External Support Panel API
    post:
      tags:
        - External Support Panel
      summary: Close Conversation
      description: Close an active conversation in the external support panel.
      operationId: closeExternalConversation
      parameters:
        - name: projectId
          in: path
          required: true
          description: Unique identifier of the Jelou project
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - botId
                - userId
              properties:
                botId:
                  type: string
                userId:
                  type: string
                redirectPayload:
                  type: object
                  properties:
                    type:
                      type: string
                    text:
                      type: string
      responses:
        '200':
          description: Conversation closed successfully
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '422':
          $ref: '#/components/responses/UnprocessableEntity'
        '500':
          $ref: '#/components/responses/InternalServerError'
      security:
        - apiKey: []
components:
  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'
    InternalServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  schemas:
    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
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic
      description: Basic authentication using Base64 encoded clientId:clientSecret
    apiKey:
      type: apiKey
      in: header
      name: x-api-key
      description: API key del proyecto de Jelou

````