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

# Iniciar conversación

> Inicia una nueva conversación con un usuario final

## Descripción

Inicia una nueva conversación con un usuario final en el panel de atención externo. Permite especificar el bot que atenderá la conversación, el usuario destinatario, un mensaje inicial y datos de asignación a colas o agentes.

Al ejecutarse, Jelou emite el evento `conversation.start` hacia el webhook configurado en la integración.

## Endpoint

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

## Parámetros de ruta

<ParamField path="projectId" type="string" required>
  Identificador único del proyecto de Jelou desde el que se inicia la conversación.
</ParamField>

## Parámetros del cuerpo

<ParamField body="botId" type="string" required>
  Identificador del bot de Jelou que gestionará la conversación.
</ParamField>

<ParamField body="userId" type="string" required>
  Identificador del usuario final con quien se iniciará la conversación.
</ParamField>

<ParamField body="initialMessage" type="string">
  Mensaje inicial que se enviará al arrancar la conversación. Si se omite, la conversación inicia sin mensaje previo.
</ParamField>

<ParamField body="metadata" type="object">
  Datos adicionales asociados a la conversación. Pueden incluir identificadores externos, números de ticket u otro contexto relevante para tu sistema.

  Ejemplo: `{ "ticketId": "T-12345" }`
</ParamField>

<ParamField body="assignment" type="object">
  Configuración de asignación de la conversación a una cola o agente específico.

  * `type` — Tipo de asignación: `queue` (cola), `operator` (operador) o `team` (equipo).
  * `target` — Nombre de la cola o identificador del agente destino.
</ParamField>

## Autenticación

Todas las peticiones deben incluir el encabezado `x-api-key` con la API key del proyecto de Jelou.

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

## Ejemplo de solicitud

El siguiente ejemplo inicia una conversación con asignación a la cola `SOPORTE` e incluye metadata de ticket:

```bash cURL theme={null}
curl --request POST \
  --url https://gateway.jelou.ai/platform/v1/external-support/PROJECT_ID/conversations/start \
  --header 'x-api-key: API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "botId": "BOT_ID",
    "userId": "USER_ID",
    "initialMessage": "Hola, necesito ayuda",
    "metadata": { "ticketId": "T-12345" },
    "assignment": { "type": "queue", "target": "SOPORTE" }
  }'
```

## Respuestas

| Código | Estado                | Descripción                                          |
| ------ | --------------------- | ---------------------------------------------------- |
| 200    | OK                    | Conversación iniciada exitosamente.                  |
| 401    | Unauthorized          | Credenciales de autenticación inválidas o faltantes. |
| 404    | Not Found             | Bot o usuario no encontrado.                         |
| 422    | Bad Request           | Faltan campos requeridos o el formato es inválido.   |
| 500    | Internal Server Error | Error interno del servidor.                          |

## Ejemplo de respuesta

```json theme={null}
{
  "message": [
    "Conversation started successfully"
  ],
  "statusMessage": "success",
  "status": 1,
  "data": {
    "conversationId": "CONVERSATION_ID",
    "botId": "BOT_ID",
    "userId": "USER_ID",
    "status": "active"
  }
}
```

***

## Evento webhook `conversation.start`

Al ejecutar este recurso, Jelou emitirá el evento `conversation.start` al webhook configurado en la integración. El payload varía según los campos enviados en la solicitud.

<Tabs>
  <Tab title="Payload básico">
    ```json theme={null}
    {
      "event": "conversation.start",
      "timestamp": 1776133797422,
      "field": "conversation",
      "object": "conversation_event",
      "event_type": "start",
      "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": {}
    }
    ```
  </Tab>

  <Tab title="Con asignación y metadata">
    ```json theme={null}
    {
      "event": "conversation.start",
      "timestamp": 1776134145523,
      "field": "conversation",
      "object": "conversation_event",
      "event_type": "start",
      "project_id": "PROJECT_ID",
      "room_id": "ROOM_ID",
      "contact": {
        "id": "USER_ID",
        "name": "USER_NAME"
      },
      "conversation": {
        "id": "CONVERSATION_ID",
        "assignment": {
          "type": "queue",
          "target": "SOPORTE"
        }
      },
      "bot": {
        "id": "BOT_ID",
        "name": "BOT_NAME"
      },
      "value": {
        "initial_message": "Hola buenos días",
        "metadata": {
          "ticketId": "T-12345"
        }
      }
    }
    ```
  </Tab>
</Tabs>

### Campos del payload

| Campo                            | Tipo   | Descripción                                                     |
| -------------------------------- | ------ | --------------------------------------------------------------- |
| `event`                          | string | Nombre del evento: `conversation.start`                         |
| `timestamp`                      | number | Marca de tiempo Unix en milisegundos del momento del evento.    |
| `project_id`                     | string | Identificador del proyecto de Jelou.                            |
| `room_id`                        | string | Identificador de la sala de conversación.                       |
| `contact.id`                     | string | Identificador del usuario final.                                |
| `contact.name`                   | string | Nombre del usuario final.                                       |
| `conversation.id`                | string | Identificador único de la conversación iniciada.                |
| `conversation.assignment.type`   | string | Tipo de asignación: `queue` o `direct`.                         |
| `conversation.assignment.target` | string | Nombre de la cola o ID del agente destino.                      |
| `bot.id`                         | string | Identificador del bot asignado.                                 |
| `bot.name`                       | string | Nombre del bot asignado.                                        |
| `value.initial_message`          | string | Mensaje inicial enviado al arrancar la conversación (opcional). |
| `value.metadata`                 | object | Metadata adicional de la conversación (opcional).               |


## OpenAPI

````yaml POST /v1/external-support/{projectId}/conversations/start
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/start:
    servers:
      - url: https://gateway.jelou.ai/platform
        description: External Support Panel API
    post:
      tags:
        - External Support Panel
      summary: Start Conversation
      description: Start a new conversation with an end user in the external support panel.
      operationId: startExternalConversation
      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
                initialMessage:
                  type: string
                metadata:
                  type: object
                assignment:
                  type: object
                  properties:
                    type:
                      type: string
                    target:
                      type: string
      responses:
        '200':
          description: Conversation started 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

````