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

# Configurar Websocket

> Habilita o deshabilita el WebSocket de la instancia y define el filtro de eventos y media en base64

**Auth:** `TokenAccount` o `TokenInstance` • **Rate limit:** `Global` (100/min) • **Idempotente:** sí (upsert)

## Descripción

Habilita / deshabilita el canal WebSocket de la instancia y define el filtro de eventos. A diferencia del webhook, hay **una única configuración** por instancia (sin `label`). Este endpoint **no abre una conexión**, solo autoriza el upgrade posterior en [`GET /ws/:instance`](/es/api/websocket).

## Ejemplos

### Habilitar todo

Activa el WebSocket sin ningún filtro: como `events` se omite, el cliente recibe los 6 tipos de eventos, y `mediaBase64` permanece como `false`.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{"enabled": true}'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ enabled: true })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={"enabled": True}
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{"enabled": true}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Filtro estrecho

Habilita el WebSocket recibiendo solo `message.exchange` y `message.status` y activa `mediaBase64: true` para que los frames con media ya incluyan el contenido binario codificado en base64.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "enabled":     true,
      "events":      ["message.exchange", "message.status"],
      "mediaBase64": true
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      enabled:     true,
      events:      ["message.exchange", "message.status"],
      mediaBase64: true
    })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "enabled":     True,
          "events":      ["message.exchange", "message.status"],
          "mediaBase64": True
      }
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{
          "enabled":     true,
          "events":      ["message.exchange", "message.status"],
          "mediaBase64": true
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

### Deshabilitar el websocket

Desactiva el WebSocket enviando `enabled: false`. La fila de configuración se preserva, `events` y `mediaBase64` se limpian, y las nuevas conexiones a `/ws/:instance` empiezan a ser rechazadas.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/events/websocket/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{"enabled": false}'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/events/websocket/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ enabled: false })
  });
  ```

  ```python Python theme={null}
  import os, requests

  requests.post(
      f"https://ryzeapi.cloud/api/events/websocket/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={"enabled": False}
  )
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
      "os"
      "strings"
  )

  func main() {
      body := strings.NewReader(`{"enabled": false}`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/events/websocket/"+os.Getenv("Instance_Name"), body)
      req.Header.Set("token", os.Getenv("Token_Instance"))
      req.Header.Set("Content-Type", "application/json")
      http.DefaultClient.Do(req)
  }
  ```
</CodeGroup>

## Respuesta exitosa

La respuesta retorna el objeto `websocket` con la configuración efectivamente persistida (`enabled`, `events`, `mediaBase64`), refleja el body de la solicitud después del upsert. Cuando `enabled=false`, `events` y `mediaBase64` regresan limpios; las conexiones ya abiertas en `/ws/:instance` se mantienen hasta cerrarse naturalmente, pero las nuevas conexiones empiezan a ser rechazadas con `400`.

```json 200 OK theme={null}
{
  "success": true,
  "message": "WebSocket configured successfully",
  "websocket": {
    "enabled":     true,
    "events":      ["message.exchange", "instance.state"],
    "mediaBase64": false
  }
}
```

## Parámetros de ruta

<ParamField path="instance" type="string" required>
  Nombre de la instancia.
</ParamField>

## Cabeceras

<ParamField header="token" type="string" required>
  `TokenAccount` o `TokenInstance`.
</ParamField>

<ParamField header="Content-Type" type="string" required>
  `application/json`
</ParamField>

## Cuerpo de la solicitud

<ParamField body="enabled" type="boolean" required>
  Activa/desactiva el WebSocket. Cuando es `false`, `events` y `mediaBase64` se **limpian antes de guardar**.
</ParamField>

<ParamField body="events" type="string[]" default="[]">
  Filtro. Array vacío = recibir los 6 tipos. Los valores deben estar en `{message.exchange, message.status, call.update, group.flow, instance.state, label.update}`.
</ParamField>

<ParamField body="mediaBase64" type="boolean" default="false">
  Cuando es `true`, los eventos `message.exchange` con media incluyen `media.base64` en los frames del WS.
</ParamField>

## Notas

<Note>
  * **No persiste eventos**: el WebSocket es efímero. Si nadie está conectado en el momento del evento, se descarta (fast-path `HasClients` antes de cualquier trabajo de serialización).
  * **Sin retry**: si el socket cae durante el envío, el mensaje se pierde. Para entrega garantizada, usa webhook.
  * **`enabled=false` no desconecta clientes ya abiertos**: las conexiones existentes en `/ws/:instance` se mantienen hasta cerrarse naturalmente; las nuevas conexiones fallan con `400`.
  * **No hay límite de conexión documentado**: cada instancia puede tener N clientes simultáneos (broadcast). El hub mantiene un buffer de 256 mensajes por cliente; los clientes lentos son desconectados automáticamente.
  * **Configuración al momento de la creación**: el mismo bloque puede pasarse a [`POST /api/instance/new`](/es/api/instance/create) vía `websocketEnabled`, `websocketEvents`, `websocketMediaBase64`.
</Note>

## Errores

| HTTP | `error.message`                         |
| ---- | --------------------------------------- |
| 400  | `Invalid request body`                  |
| 401  | `Invalid token`                         |
| 404  | `Instance not found`                    |
| 429  | `Rate limit exceeded. Try again later.` |
| 500  | `Failed to get instance`                |

Envoltorio:

```json theme={null}
{
  "success": false,
  "error": { "message": "Invalid request body" }
}
```

## Siguiente

<CardGroup cols={2}>
  <Card title="Consultar configuración del WebSocket" icon="eye" href="/es/api/events/websocket-read">
    `GET /api/events/getWebsocket/:instance`
  </Card>

  <Card title="Conectar vía WebSocket" icon="bolt" href="/es/api/websocket">
    `GET /ws/:instance`, protocolo, autenticación, reconexión.
  </Card>
</CardGroup>
