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

# Definir Websocket

> Habilita ou desabilita o WebSocket da instância e define filtro de eventos e mídia em base64

**Auth:** `TokenAccount` ou `TokenInstance` • **Rate-limit:** `Global` (100/min) • **Idempotente:** sim (upsert)

## Descrição

Habilita / desabilita o canal WebSocket da instância e define o filtro de eventos. Diferente do webhook, existe **uma única configuração** por instância (não há `label`). Esse endpoint **não abre conexão**, apenas autoriza o upgrade posterior em [`GET /ws/:instance`](/pt/api/websocket).

## Exemplos

### Habilitar tudo

Liga o WebSocket sem filtro: como `events` é omitido, o cliente recebe os 6 tipos de evento, e `mediaBase64` permanece em `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 estreito

Habilita o WebSocket recebendo somente `message.exchange` e `message.status` e ativa `mediaBase64: true` para que os frames com mídia já tragam o conteúdo binário codificado em 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>

### Desativar o websocket

Desliga o WebSocket enviando `enabled: false`. A linha de configuração é preservada, `events` e `mediaBase64` são zerados, e novas conexões em `/ws/:instance` passam a ser rejeitadas.

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

## Resposta de sucesso

A resposta devolve o objeto `websocket` com a configuração efetivamente persistida (`enabled`, `events`, `mediaBase64`), espelha o body do request após o upsert. Quando `enabled=false`, `events` e `mediaBase64` voltam zerados; conexões já abertas em `/ws/:instance` permanecem até serem fechadas naturalmente, mas novas conexões passam a ser rejeitadas com `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 rota

<ParamField path="instance" type="string" required>
  Nome da instância.
</ParamField>

## Headers

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

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

## Request body

<ParamField body="enabled" type="boolean" required>
  Liga/desliga o WebSocket. Quando `false`, `events` e `mediaBase64` são **zerados antes do save**.
</ParamField>

<ParamField body="events" type="string[]" default="[]">
  Filtro. Array vazio = recebe todos os 6 tipos. Valores devem estar em `{message.exchange, message.status, call.update, group.flow, instance.state, label.update}`.
</ParamField>

<ParamField body="mediaBase64" type="boolean" default="false">
  Quando `true`, eventos `message.exchange` com mídia incluem `media.base64` nos frames WS.
</ParamField>

## Notas

<Note>
  * **Não persiste eventos**: WebSocket é efêmero. Se ninguém estiver conectado no momento do evento, ele é descartado (fast-path `HasClients` antes de qualquer trabalho de serialização).
  * **Sem retry**: se o socket cair durante o envio, a mensagem é perdida. Para entrega garantida, use webhook.
  * **`enabled=false` não desconecta clientes já abertos**: as conexões existentes em `/ws/:instance` permanecem até serem fechadas naturalmente; novas conexões falham com `400`.
  * **Sem limite documentado de conexões**: cada instância pode ter N clientes simultâneos (broadcast). O hub mantém buffer de 256 mensagens por cliente, clientes lentos são desconectados automaticamente.
  * **Configuração na criação**: o mesmo bloco pode ser passado em [`POST /api/instance/new`](/pt/api/instance/create) via `websocketEnabled`, `websocketEvents`, `websocketMediaBase64`.
</Note>

## Erros

| 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`                |

Envelope:

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

## Próximo

<CardGroup cols={2}>
  <Card title="Verificar config WebSocket" icon="eye" href="/pt/api/events/websocket-read">
    `GET /api/events/getWebsocket/:instance`
  </Card>

  <Card title="Conectar via WebSocket" icon="bolt" href="/pt/api/websocket">
    `GET /ws/:instance`, protocolo, auth, reconexão.
  </Card>
</CardGroup>
