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

# Enviar encuesta

> Crea una encuesta con opciones de elección única o múltiple

**Auth:** `TokenAccount` o `TokenInstance` • **Rate-limit:** `Global` (100/min) • **Idempotente:** no

## Descripción

Envía una encuesta a un contacto 1-a-1, grupo (`@g.us`) o newsletter (`@newsletter`). Soporta de **2 a 12 opciones** (límite de WhatsApp). El campo `maxAnswer` controla cuántas opciones puede seleccionar el usuario: `1` (default) = elección única; `> 1` = elección múltiple. Si `maxAnswer` se omite, es inválido (`< 1`) o mayor que `len(options)`, el servidor lo normaliza automáticamente a `1` o al número total de opciones, respectivamente. Soporta `delay`, `replyTo` y `replyPrivate`.

## Ejemplos

### Encuesta simple (elección única)

Crea una encuesta con tres opciones (`9am`, `2pm`, `4pm`) y `maxAnswer` establecido implícitamente en `1`, el respondente solo puede elegir una.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/message/poll/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "number":   "5511999999999",
      "question": "Which time works best for the meeting?",
      "options":  ["9am", "2pm", "4pm"]
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/message/poll/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      number:   "5511999999999",
      question: "Which time works best for the meeting?",
      options:  ["9am", "2pm", "4pm"]
    })
  });
  ```

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

  requests.post(
      f"https://ryzeapi.cloud/api/message/poll/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "number":   "5511999999999",
          "question": "Which time works best for the meeting?",
          "options":  ["9am", "2pm", "4pm"]
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "number":   "5511999999999",
          "question": "Which time works best for the meeting?",
          "options":  ["9am", "2pm", "4pm"]
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/message/poll/"+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>

### Encuesta de elección múltiple

`maxAnswer: 3` permite que el respondente elija hasta tres opciones.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/message/poll/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "number":    "120363406289005073@g.us",
      "question":  "Which languages do you use day-to-day?",
      "options":   ["Go", "Python", "JavaScript", "TypeScript", "Rust", "Java"],
      "maxAnswer": 3
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/message/poll/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      number:    "120363406289005073@g.us",
      question:  "Which languages do you use day-to-day?",
      options:   ["Go", "Python", "JavaScript", "TypeScript", "Rust", "Java"],
      maxAnswer: 3
    })
  });
  ```

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

  requests.post(
      f"https://ryzeapi.cloud/api/message/poll/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "number":    "120363406289005073@g.us",
          "question":  "Which languages do you use day-to-day?",
          "options":   ["Go", "Python", "JavaScript", "TypeScript", "Rust", "Java"],
          "maxAnswer": 3
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "number":    "120363406289005073@g.us",
          "question":  "Which languages do you use day-to-day?",
          "options":   ["Go", "Python", "JavaScript", "TypeScript", "Rust", "Java"],
          "maxAnswer": 3
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/message/poll/"+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>

### Encuesta como respuesta a un mensaje

Cita un mensaje existente vía `replyTo`. El mensaje original debe pertenecer a la misma instancia.

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://ryzeapi.cloud/api/message/poll/$Instance_Name" \
    -H "token: $Token_Instance" \
    -H "Content-Type: application/json" \
    -d '{
      "number":   "5511999999999",
      "question": "Are you confirming the event on date X?",
      "options":  ["Yes, confirmed", "Can't make it", "Maybe"],
      "replyTo":  "3EB08FCF27E532F1B0F5",
      "delay":    2
    }'
  ```

  ```javascript JavaScript theme={null}
  await fetch(`https://ryzeapi.cloud/api/message/poll/${process.env.Instance_Name}`, {
    method: "POST",
    headers: {
      "token":        process.env.Token_Instance,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      number:   "5511999999999",
      question: "Are you confirming the event on date X?",
      options:  ["Yes, confirmed", "Can't make it", "Maybe"],
      replyTo:  "3EB08FCF27E532F1B0F5",
      delay:    2
    })
  });
  ```

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

  requests.post(
      f"https://ryzeapi.cloud/api/message/poll/{os.environ['Instance_Name']}",
      headers={
          "token":        os.environ["Token_Instance"],
          "Content-Type": "application/json"
      },
      json={
          "number":   "5511999999999",
          "question": "Are you confirming the event on date X?",
          "options":  ["Yes, confirmed", "Can't make it", "Maybe"],
          "replyTo":  "3EB08FCF27E532F1B0F5",
          "delay":    2
      }
  )
  ```

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

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

  func main() {
      body := strings.NewReader(`{
          "number":   "5511999999999",
          "question": "Are you confirming the event on date X?",
          "options":  ["Yes, confirmed", "Can't make it", "Maybe"],
          "replyTo":  "3EB08FCF27E532F1B0F5",
          "delay":    2
      }`)
      req, _ := http.NewRequest("POST", "https://ryzeapi.cloud/api/message/poll/"+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

El `content` retornado preformatea la pregunta junto con las opciones numeradas (`1. ... 2. ...`), es la representación textual usada para indexar la encuesta en el historial. El `messageId` es lo que necesitas mantener para correlacionar los votos recibidos vía webhook.

```json 200 OK theme={null}
{
  "success": true,
  "message": "Poll sent successfully",
  "status":  "sent",
  "data": {
    "messageId":   "3EB08FCF27E532F1D3D3",
    "direction":   "sent",
    "messageType": "poll",
    "content":     "Which time works best for the meeting?\n\nOptions:\n1. 14:00\n2. 15:00\n3. 16:00\n",
    "source":      "api",
    "timestamp":   "2026-04-30T14:30:00Z",
    "chat": {
      "jid":     "5511999999999@s.whatsapp.net",
      "isGroup": false
    },
    "sender": {
      "jid":      "5511777777777@s.whatsapp.net",
      "instance": "my-instance"
    }
  }
}
```

<Note>
  Las respuestas de los participantes no llegan sincrónicamente en esta respuesta, fluyen como eventos `poll-update` en el webhook/WebSocket configurado, referenciando el `messageId` de la encuesta.
</Note>

## Parámetros de ruta

<ParamField path="instance" type="string" required>
  Nombre de la instancia (p. ej., `$Instance_Name`).
</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="number" type="string" required>
  Destino: teléfono (`5511999999999`) o JID (`@s.whatsapp.net`, `@lid`, `@g.us`, `@newsletter`).
</ParamField>

<ParamField body="question" type="string" required>
  Pregunta mostrada en la parte superior de la encuesta.
</ParamField>

<ParamField body="options" type="string[]" required>
  Lista de opciones. **Mínimo 2, máximo 12** (límite de WhatsApp). Las cadenas duplicadas son aceptadas pero no recomendadas.
</ParamField>

<ParamField body="maxAnswer" type="int" default="1">
  Número máximo de opciones que el respondente puede seleccionar. `1` = elección única; `> 1` = elección múltiple. Los valores `< 1` se normalizan a `1`; los valores mayores que `len(options)` se limitan al tamaño de la lista.
</ParamField>

<ParamField body="delay" type="int" default="0">
  Tiempo en **segundos** a esperar antes de enviar. Durante el intervalo, el servidor muestra el indicador "escribiendo..." al destinatario y dispara "pausado" antes del envío real.
</ParamField>

<ParamField body="replyTo" type="string">
  ID del mensaje a responder. El mensaje original debe pertenecer a la misma instancia y estar guardado en la base de datos.
</ParamField>

<ParamField body="replyPrivate" type="boolean" default="false">
  Cuando es `true` **y** `replyTo` apunta a un mensaje originado en un grupo, la encuesta se redirige al **chat privado** del autor original (manteniendo la cita).
</ParamField>

<ParamField body="source" type="string" default="api">
  Identificador de origen para trazabilidad (p. ej., `crm`, `support-bot`, `n8n`). Guardado en el registro del mensaje y propagado a los webhooks.
</ParamField>

## Notas

<Note>
  * **`delay` es en segundos** (no milisegundos).
  * WhatsApp acepta de **2 a 12 opciones** por encuesta. Cualquier cantidad mayor es truncada por el cliente del destinatario.
  * `maxAnswer` es normalizado por el servidor: `< 1` se convierte en `1`, y cualquier valor mayor que `len(options)` cae a `len(options)`.
  * Los votos no regresan en esta llamada, suscríbete a eventos de webhook/WebSocket para recibir `poll-update` cuando alguien vote.
  * En newsletters (`@newsletter`), las encuestas pueden tener comportamiento limitado dependiendo de los permisos del canal.
</Note>

## Errores

| HTTP | Status interno   | Mensaje                                 |
| ---- | ---------------- | --------------------------------------- |
| 400  | ,                | `Instance name is required`             |
| 400  | ,                | `Invalid request body: <detail>`        |
| 400  | ,                | `Number is required`                    |
| 400  | ,                | `Question is required`                  |
| 400  | ,                | `At least 2 options are required`       |
| 400  | `invalid_number` | `Invalid phone number format: <detail>` |
| 404  | ,                | `Instance not found`                    |
| 500  | `send_failed`    | `Failed to send poll: <reason>`         |
| 503  | `disconnected`   | `Instance is not connected to WhatsApp` |

Envoltorio de error:

```json theme={null}
{
  "success": false,
  "error": { "message": "At least 2 options are required" }
}
```
