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

> ## Agent Instructions
> Integrating Pilot Status end to end? Follow https://docs.pilotstatus.com.br/guides/integrate-with-ai.md (pt-BR: https://docs.pilotstatus.com.br/pt-BR/guides/integrate-with-ai.md). No step requires contacting support: every credential is shown in the dashboard or in an API response, and a lost one is regenerated, not recovered.
> Webhook signing secret: shown ONCE in the Signing secret window right after creating the webhook on /webhooks, and in the `secret` field of the POST /v1/webhooks response (MCP: webhooks_create). Lost it: Edit Webhook → Generate a new secret, POST /v1/webhooks/{id}/rotate-secret, or webhooks_rotate_secret (the old one stops working at once). Verify `x-pilot-status-signature` = hex HMAC-SHA256 of the raw request body keyed with that secret.
> Meta verify token (number connected with the user's own Meta app credentials): Meta Number Created! window after connecting, then the number's card on Numbers (workspace Owner), or webhook.verifyToken in the POST /v1/numbers/meta response. It is not the webhook signing secret.
> REST auth: `x-api-key: ps_...` header, never Authorization: Bearer. MCP: https://mcp.pilotstatus.com.br/mcp (148 tools, OAuth 2.1 or x-api-key); Code Mode: https://mcp.pilotstatus.com.br/code. Destructive MCP tools return a preview and a confirm_token: show the preview and call again only after the user's explicit yes. Over OAuth, revealing or creating ps_ API keys is workspace Owner only.

# n8n

> Automatiza WhatsApp en n8n con el node oficial de Pilot Status: instálalo, recibe eventos con el node Trigger e importa workflows listos para todo tipo de número.

El node oficial de la comunidad `n8n-nodes-pilot-status` agrega dos nodes a n8n:

* **Pilot Status**: llama a la API pública `/v1` para enviar mensajes y plantillas, listar logs y gestionar números, plantillas, Flows, grupos y más.
* **Pilot Status Trigger**: recibe los eventos de tu webhook e inicia un workflow.

Esta página muestra cómo configurar los dos e incluye workflows para importar y adaptar: uno para empezar con cada tipo de número (API Pilot Status, layer Evolution GO, layer Evolution v2, oficial Meta) y cinco recetas. Cada workflow se importó en n8n y se comprobó contra la definición de los nodes, y su lógica de enrutamiento se ejecutó con payloads de ejemplo de todos los formatos de webhook.

## Instala el node

**1. Instala el node de la comunidad**

En n8n, abre **Settings → Community Nodes → Install**, escribe `n8n-nodes-pilot-status` y confirma. Necesitas un n8n self-hosted (ahí los community nodes vienen activados por defecto). En n8n Cloud, n8n decide qué community nodes se pueden instalar; si este no aparece, usa una instancia self-hosted.

**2. Crea la credencial**

Agrega una credencial **Pilot Status API** y pega tu clave de API `ps_` del panel.

Qué otros campos llenar depende del tipo de clave: consulta [Elige la clave de API](#elige-la-clave-de-api) abajo. Deja la **Base URL** por defecto (`https://pilotstatus.com.br`).

**3. Agrega un node Pilot Status**

Elige un **Resource** (por ejemplo **Message**) y una **Operation** (por ejemplo **Send**). El menú **Template ID** carga las plantillas del número de la credencial.

## Elige la clave de API

Pilot Status tiene tres tipos de clave ([detalles](https://docs.pilotstatus.com.br/es/concepts/key-types.md)). La credencial tiene dos campos opcionales, **WhatsApp Number ID** y **Workspace ID**, que se envían en los headers `x-whatsapp-number-id` y `x-workspace-id`. Llénalos según la clave:

| Clave | Prefijo | Dónde crearla | WhatsApp Number ID | Workspace ID |
| - | - | - | - | - |
| **Número** | `ps_number_` | Página **API Keys** | Déjalo vacío: la clave ya lleva su número | Déjalo vacío |
| **Workspace** | `ps_workspace_` | **Workspace keys** | Obligatorio para enviar, leer logs o actuar sobre un número | Déjalo vacío |
| **Cuenta** | `ps_account_` | **Profile → API** | Obligatorio para enviar, leer logs o actuar sobre un número | **Obligatorio**: el workspace en el que actúa la clave |

* **Un workflow, un número:** usa una **clave de número**. Solo alcanza ese número, lo que limita el daño si la clave se filtra.
* **Varios números:** usa una **clave de workspace** y crea una credencial por número, cada una con su **WhatsApp Number ID** (el `id` de **Number → Get Many**). Gestionar números (crear, conectar, eliminar) también requiere una clave de workspace.
* **Clave de cuenta:** solo cuando una persona automatiza varios workspaces. Sin **Workspace ID**, cada llamada responde `400 WORKSPACE_ID_REQUIRED`, y la persona dueña de la clave debe ser **Owner** o **Admin** para gestionar webhooks.
* **Trigger con registro Automatic** funciona con los tres tipos. El webhook se crea en el número de la credencial, así que una clave de workspace o de cuenta sin **WhatsApp Number ID** falla al activar con `400 NUMBER_REQUIRED`.

> [!WARNING]
>
> **Una prueba de credencial verde no demuestra que el envío funcione.** Para una clave de cuenta sin **Workspace ID**, n8n prueba la credencial en `/v1/workspaces`, que no necesita workspace, así que la prueba pasa y el primer **Send** falla. Una clave de workspace sin **WhatsApp Number ID** también pasa la prueba y luego responde `403 TENANT_SCOPE_NOT_ALLOWED` en **Send**.

## Recibe eventos con el Trigger

**1. Agrega el Pilot Status Trigger**

Deja **Registration** en **Manual** y **Event** en **All Events** (la advertencia de abajo explica por qué).

**2. Registra la URL**

Copia la **Production URL** del Trigger y agrégala como webhook del número en la página **Webhooks** del panel de Pilot Status. Usa la **Test URL** mientras haces clic en **Listen for test event** en el editor.

**3. Firma las entregas**

Pega el secreto de firma del webhook en **Signing Secret**. El Trigger responde `401` a cualquier solicitud cuyo `x-pilot-status-signature` no coincida. Sin él, cualquiera que conozca la URL puede iniciar tu workflow.

**4. Activa el workflow**

La **Production URL** solo recibe eventos mientras el workflow está activo.

El Trigger entrega el cuerpo recibido sin cambios: `$json` es exactamente lo que Pilot Status envió.

### Dos formatos de webhook

Lo que llega depende de cómo se conectó el número ([detalles](https://docs.pilotstatus.com.br/es/api/webhooks/events.md)):

| Número | Cuerpo que recibe el Trigger | Texto recibido en |
| - | - | - |
| **API Pilot Status (no oficial, código QR)** | Eventos de Pilot Status: `message.received`, `message.reply`, … | `$json.data.content` |
| **Layer Evolution GO (no oficial)** | Eventos de Evolution GO: `Message`, `SendMessage`, `Receipt`, … | `$json.data.Message.conversation` |
| **Layer Evolution v2 (no oficial)** | Eventos de Evolution v2: `messages.upsert`, `messages.update`, … | `$json.data.message.conversation` |
| **Meta Cloud API (oficial)** | Sobre nativo de Meta: `{ object, entry }` | `$json.entry[0].changes[0].value.messages[0].text.body` |

> [!WARNING]
>
> **En un número oficial, elige All Events.** El sobre de Meta no tiene el campo `event`, así que un Trigger configurado con un evento específico, como **Message Reply**, responde `200 Ignored event` a cada mensaje y el workflow nunca se ejecuta. Por el mismo motivo, no uses el registro **Automatic** con un evento `message.*` en un número oficial: Pilot Status descarta los nombres de evento que el número no emite, así que el webhook se crea con la lista vacía y no entrega nada.

> [!WARNING]
>
> **Una respuesta llega como `message.reply`, no como `message.received`.** En un número por código QR, un mensaje que cita otro, incluido el toque en un botón de plantilla, dispara solo `message.reply`. Un Trigger en **Message Received** nunca ve los toques en botones.

Para no escribir cada workflow cuatro veces, los workflows de abajo empiezan con un node Code **Normalize**. Convierte los cuatro formatos en el mismo ítem plano:

| Campo | Significado |
| - | - |
| `source` | `pilot-status`, `evolution-go`, `evolution-v2` o `meta` |
| `isInbound` | `true` solo para un mensaje que envió el contacto. Los estados y el eco de tus propios envíos son `false` |
| `from` | el número del contacto en E.164 (`+5511999999999`) |
| `name` | el nombre del contacto en WhatsApp, cuando se conoce |
| `text` | texto del mensaje, o la etiqueta del botón o de la fila de lista tocada |
| `buttonId` | id o payload del botón o de la fila de lista tocada, cuando WhatsApp lo informa |
| `quotedMessageId` | el mensaje respondido, cuando lo hay |

```javascript Normalize (node Code) theme={null}
// Turns every webhook format into the same flat item:
// - Pilot Status API (QR code) numbers send { event, data }
// - Evolution GO layer numbers send Evolution GO events ("Message", "SendMessage", ...)
// - Evolution v2 layer numbers send Evolution v2 events ("messages.upsert", ...)
// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }
const phoneOf = (jid) =>
  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';

// Evolution GO and v2 carry the same WhatsApp message object
const readWaMessage = (m = {}) => ({
  text:
    m.conversation ??
    m.extendedTextMessage?.text ??
    m.buttonsResponseMessage?.selectedDisplayText ??
    m.templateButtonReplyMessage?.selectedDisplayText ??
    m.listResponseMessage?.title ??
    m.imageMessage?.caption ??
    m.videoMessage?.caption ??
    '',
  buttonId:
    m.buttonsResponseMessage?.selectedButtonId ??
    m.templateButtonReplyMessage?.selectedId ??
    m.listResponseMessage?.singleSelectReply?.selectedRowId ??
    '',
  quotedMessageId:
    m.extendedTextMessage?.contextInfo?.stanzaId ??
    m.buttonsResponseMessage?.contextInfo?.stanzaId ??
    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??
    m.listResponseMessage?.contextInfo?.stanzaId ??
    '',
});

return $input.all().map(({ json }) => {
  // Meta Cloud API (official)
  if (json.entry) {
    const value = json.entry[0]?.changes?.[0]?.value ?? {};
    const msg = value.messages?.[0];
    return {
      json: {
        source: 'meta',
        isInbound: Boolean(msg),
        from: msg ? '+' + msg.from : '',
        name: value.contacts?.[0]?.profile?.name ?? '',
        text:
          msg?.text?.body ??
          msg?.button?.text ??
          msg?.interactive?.button_reply?.title ??
          msg?.interactive?.list_reply?.title ??
          '',
        buttonId:
          msg?.button?.payload ??
          msg?.interactive?.button_reply?.id ??
          msg?.interactive?.list_reply?.id ??
          '',
        quotedMessageId: msg?.context?.id ?? '',
      },
    };
  }

  // Evolution v2 layer
  if (json.event === 'messages.upsert') {
    const d = json.data ?? {};
    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;
    const from = phoneOf(jid);
    return {
      json: {
        source: 'evolution-v2',
        isInbound: Boolean(from) && !d.key?.fromMe,
        from,
        name: d.pushName ?? '',
        ...readWaMessage(d.message),
      },
    };
  }

  // Evolution GO layer
  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {
    const info = json.data?.Info ?? {};
    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);
    return {
      json: {
        source: 'evolution-go',
        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,
        from,
        name: info.PushName ?? '',
        ...readWaMessage(json.data?.Message),
      },
    };
  }

  // Pilot Status API (QR code)
  const data = json.data ?? {};
  return {
    json: {
      source: 'pilot-status',
      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,
      from: data.from ?? '',
      name: data.participantName ?? '',
      text: data.content ?? '',
      buttonId: data.buttonId ?? '',
      quotedMessageId: data.quotedMessageId ?? '',
    },
  };
});
```

## Importa un workflow

1. Copia el JSON de una receta.
2. En n8n, abre un workflow vacío y presiona **Ctrl+V** (**Cmd+V** en macOS) sobre el canvas. También puedes guardar el JSON en un archivo y usar **⋯ → Import from File**.
3. Abre cada node de Pilot Status, Google Sheets, OpenAI y correo y selecciona tu credencial.
4. Cambia los valores de ejemplo: nombres de plantilla, números de teléfono, id de la hoja, direcciones de correo.

> [!NOTE]
>
> El workflow responde **desde el número de la credencial**. Registra la URL del Trigger en ese mismo número: si el webhook es del número A y la credencial del número B, el contacto escribe a A y recibe la respuesta desde B.

## Empieza por tu tipo de número

Cada workflow de abajo responde cada texto que envía un contacto con `Recibimos tu mensaje: <su texto>`. Importa el de tu número para ver llegar los eventos y luego sigue con las recetas. Los cuatro empiezan igual, **Pilot Status Trigger → Normalize → Inbound text?**; solo cambia la respuesta.

> [tab] API Pilot Status
>
> Número conectado por código QR en el panel. La respuesta sale por el node **Pilot Status** (`POST /v1/messages/send`), con una clave `ps_` en la credencial.
>
> > [accordion] JSON del workflow — API Pilot Status
> >
> > ```json theme={null}
> > {
> >   "name": "Pilot Status - Inicio rápido: número de la API Pilot Status",
> >   "nodes": [
> >     {
> >       "parameters": {
> >         "event": "*"
> >       },
> >       "id": "7496b81a-b333-471a-99ac-e69435b02cc6",
> >       "name": "Pilot Status Trigger",
> >       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
> >       "typeVersion": 1,
> >       "position": [
> >         0,
> >         0
> >       ],
> >       "webhookId": "44d3dea6-9efa-4b4f-99ff-476901f823ce"
> >     },
> >     {
> >       "parameters": {
> >         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
> >       },
> >       "id": "98618831-3e93-449f-a2f1-466e4d3068bc",
> >       "name": "Normalize",
> >       "type": "n8n-nodes-base.code",
> >       "typeVersion": 2,
> >       "position": [
> >         220,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "conditions": {
> >           "options": {
> >             "caseSensitive": true,
> >             "leftValue": "",
> >             "typeValidation": "loose",
> >             "version": 2
> >           },
> >           "conditions": [
> >             {
> >               "id": "5ff04d73-2900-40a5-babc-0140053a54c5",
> >               "leftValue": "={{ $json.isInbound }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "boolean",
> >                 "operation": "true",
> >                 "singleValue": true
> >               }
> >             },
> >             {
> >               "id": "d9149ed7-fa08-4211-8fe6-9e8203c3a25d",
> >               "leftValue": "={{ $json.text }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "string",
> >                 "operation": "notEmpty",
> >                 "singleValue": true
> >               }
> >             }
> >           ],
> >           "combinator": "and"
> >         },
> >         "options": {}
> >       },
> >       "id": "d36e8466-4e0b-4729-adf9-da961f346c93",
> >       "name": "Inbound text?",
> >       "type": "n8n-nodes-base.if",
> >       "typeVersion": 2.2,
> >       "position": [
> >         440,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "resource": "message",
> >         "operation": "send",
> >         "destinationNumber": "={{ $json.from }}",
> >         "additionalFields": {
> >           "text": "=Recibimos tu mensaje: {{ $json.text }}"
> >         }
> >       },
> >       "id": "77402e5d-d643-4a1d-8283-882a26e61270",
> >       "name": "Reply",
> >       "type": "n8n-nodes-pilot-status.pilotStatus",
> >       "typeVersion": 1,
> >       "position": [
> >         660,
> >         0
> >       ]
> >     }
> >   ],
> >   "connections": {
> >     "Pilot Status Trigger": {
> >       "main": [
> >         [
> >           {
> >             "node": "Normalize",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Normalize": {
> >       "main": [
> >         [
> >           {
> >             "node": "Inbound text?",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Inbound text?": {
> >       "main": [
> >         [
> >           {
> >             "node": "Reply",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     }
> >   },
> >   "pinData": {},
> >   "settings": {
> >     "executionOrder": "v1"
> >   }
> > }
> > ```

> [tab] Layer Evolution GO
>
> Número migrado desde Evolution GO. Los eventos llegan en el formato propio de Evolution GO, y la respuesta usa la layer igual que tu código Evolution GO: `POST /send/text` en `https://pilotstatus.com.br/api/layer/evolution-go/`, con el **token de la instancia** en el header `apikey` (no una clave `ps_`). Consulta la [layer Evolution GO](https://docs.pilotstatus.com.br/es/api/layer/evolution-go.md).
>
> Qué cambiar: `YOUR_INSTANCE_TOKEN` en **Reply through the layer**. Para sacar el token del workflow, pásalo a una credencial **Header Auth** de n8n con el nombre `apikey`. También puedes responder con el node **Pilot Status**, como en un número de la API Pilot Status.
>
> > [accordion] JSON del workflow — layer Evolution GO
> >
> > ```json theme={null}
> > {
> >   "name": "Pilot Status - Inicio rápido: número de la layer Evolution GO",
> >   "nodes": [
> >     {
> >       "parameters": {
> >         "event": "*"
> >       },
> >       "id": "7e06e793-af12-4f5c-8a63-11a019221d7b",
> >       "name": "Pilot Status Trigger",
> >       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
> >       "typeVersion": 1,
> >       "position": [
> >         0,
> >         0
> >       ],
> >       "webhookId": "0ad50705-0768-4723-ac41-3d5e96b62545"
> >     },
> >     {
> >       "parameters": {
> >         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
> >       },
> >       "id": "c1bac035-9ef5-43a5-9450-c7e4955391fe",
> >       "name": "Normalize",
> >       "type": "n8n-nodes-base.code",
> >       "typeVersion": 2,
> >       "position": [
> >         220,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "conditions": {
> >           "options": {
> >             "caseSensitive": true,
> >             "leftValue": "",
> >             "typeValidation": "loose",
> >             "version": 2
> >           },
> >           "conditions": [
> >             {
> >               "id": "3d7eca67-2aa5-4c50-8672-4eda90e9940b",
> >               "leftValue": "={{ $json.isInbound }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "boolean",
> >                 "operation": "true",
> >                 "singleValue": true
> >               }
> >             },
> >             {
> >               "id": "24f70be2-fd44-4fb2-b47a-221f86ef9d34",
> >               "leftValue": "={{ $json.text }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "string",
> >                 "operation": "notEmpty",
> >                 "singleValue": true
> >               }
> >             }
> >           ],
> >           "combinator": "and"
> >         },
> >         "options": {}
> >       },
> >       "id": "eddd972a-4fcc-4efe-b4c5-a744a5b0e45d",
> >       "name": "Inbound text?",
> >       "type": "n8n-nodes-base.if",
> >       "typeVersion": 2.2,
> >       "position": [
> >         440,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "method": "POST",
> >         "url": "https://pilotstatus.com.br/api/layer/evolution-go/send/text",
> >         "sendHeaders": true,
> >         "headerParameters": {
> >           "parameters": [
> >             {
> >               "name": "apikey",
> >               "value": "YOUR_INSTANCE_TOKEN"
> >             }
> >           ]
> >         },
> >         "sendBody": true,
> >         "specifyBody": "json",
> >         "jsonBody": "={{ JSON.stringify({ number: $json.from.replace('+', ''), text: \"Recibimos tu mensaje: \" + $json.text }) }}",
> >         "options": {}
> >       },
> >       "id": "5477dff8-9a57-46f0-b024-38d524822179",
> >       "name": "Reply through the layer",
> >       "type": "n8n-nodes-base.httpRequest",
> >       "typeVersion": 4.2,
> >       "position": [
> >         660,
> >         0
> >       ]
> >     }
> >   ],
> >   "connections": {
> >     "Pilot Status Trigger": {
> >       "main": [
> >         [
> >           {
> >             "node": "Normalize",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Normalize": {
> >       "main": [
> >         [
> >           {
> >             "node": "Inbound text?",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Inbound text?": {
> >       "main": [
> >         [
> >           {
> >             "node": "Reply through the layer",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     }
> >   },
> >   "pinData": {},
> >   "settings": {
> >     "executionOrder": "v1"
> >   }
> > }
> > ```

> [tab] Layer Evolution v2
>
> Número migrado desde Evolution API v2. Los eventos llegan en el formato propio de Evolution v2 (`messages.upsert`), y la respuesta llama a `POST /message/sendText/{instance}` en `https://pilotstatus.com.br/api/layer/evolution-v2/`, con el token de la instancia en `apikey`. Consulta en la [layer Evolution V2](https://docs.pilotstatus.com.br/es/api/layer/evolution-v2.md) qué nombre de instancia usar.
>
> Qué cambiar: `YOUR_INSTANCE_NAME` en la URL y `YOUR_INSTANCE_TOKEN` en el header de **Reply through the layer**.
>
> > [accordion] JSON del workflow — layer Evolution v2
> >
> > ```json theme={null}
> > {
> >   "name": "Pilot Status - Inicio rápido: número de la layer Evolution v2",
> >   "nodes": [
> >     {
> >       "parameters": {
> >         "event": "*"
> >       },
> >       "id": "8d0364b0-2305-466a-a895-9aab5e4f2b4b",
> >       "name": "Pilot Status Trigger",
> >       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
> >       "typeVersion": 1,
> >       "position": [
> >         0,
> >         0
> >       ],
> >       "webhookId": "c09bd2b3-67b0-4478-91bb-826c13762b60"
> >     },
> >     {
> >       "parameters": {
> >         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
> >       },
> >       "id": "8b1d5ba8-c67d-4799-b725-9eb5d97b3c86",
> >       "name": "Normalize",
> >       "type": "n8n-nodes-base.code",
> >       "typeVersion": 2,
> >       "position": [
> >         220,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "conditions": {
> >           "options": {
> >             "caseSensitive": true,
> >             "leftValue": "",
> >             "typeValidation": "loose",
> >             "version": 2
> >           },
> >           "conditions": [
> >             {
> >               "id": "7773e1ed-79d5-43fb-a0aa-f601e715df8f",
> >               "leftValue": "={{ $json.isInbound }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "boolean",
> >                 "operation": "true",
> >                 "singleValue": true
> >               }
> >             },
> >             {
> >               "id": "a17fd858-3b4c-4839-8b78-5ce5c3291d07",
> >               "leftValue": "={{ $json.text }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "string",
> >                 "operation": "notEmpty",
> >                 "singleValue": true
> >               }
> >             }
> >           ],
> >           "combinator": "and"
> >         },
> >         "options": {}
> >       },
> >       "id": "5b0c9233-85ad-40ef-a11b-cf4138264f48",
> >       "name": "Inbound text?",
> >       "type": "n8n-nodes-base.if",
> >       "typeVersion": 2.2,
> >       "position": [
> >         440,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "method": "POST",
> >         "url": "https://pilotstatus.com.br/api/layer/evolution-v2/message/sendText/YOUR_INSTANCE_NAME",
> >         "sendHeaders": true,
> >         "headerParameters": {
> >           "parameters": [
> >             {
> >               "name": "apikey",
> >               "value": "YOUR_INSTANCE_TOKEN"
> >             }
> >           ]
> >         },
> >         "sendBody": true,
> >         "specifyBody": "json",
> >         "jsonBody": "={{ JSON.stringify({ number: $json.from.replace('+', ''), text: \"Recibimos tu mensaje: \" + $json.text }) }}",
> >         "options": {}
> >       },
> >       "id": "8fa0637d-c755-42e3-b7c2-05c9bc3f7a6f",
> >       "name": "Reply through the layer",
> >       "type": "n8n-nodes-base.httpRequest",
> >       "typeVersion": 4.2,
> >       "position": [
> >         660,
> >         0
> >       ]
> >     }
> >   ],
> >   "connections": {
> >     "Pilot Status Trigger": {
> >       "main": [
> >         [
> >           {
> >             "node": "Normalize",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Normalize": {
> >       "main": [
> >         [
> >           {
> >             "node": "Inbound text?",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Inbound text?": {
> >       "main": [
> >         [
> >           {
> >             "node": "Reply through the layer",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     }
> >   },
> >   "pinData": {},
> >   "settings": {
> >     "executionOrder": "v1"
> >   }
> > }
> > ```

> [tab] Oficial (Meta)
>
> Número conectado por Embedded Signup o con credenciales de Meta. Los eventos llegan como sobre nativo de Meta, y la respuesta sale por el node **Pilot Status**. La respuesta en texto libre está permitida porque el mensaje del contacto abrió la ventana de atención de 24 horas; fuera de ella, envía una plantilla aprobada.
>
> > [accordion] JSON del workflow — oficial (Meta)
> >
> > ```json theme={null}
> > {
> >   "name": "Pilot Status - Inicio rápido: número oficial (Meta)",
> >   "nodes": [
> >     {
> >       "parameters": {
> >         "event": "*"
> >       },
> >       "id": "0ea38b4a-b448-4cd5-8f98-b3b084f799b0",
> >       "name": "Pilot Status Trigger",
> >       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
> >       "typeVersion": 1,
> >       "position": [
> >         0,
> >         0
> >       ],
> >       "webhookId": "e2a8c469-2cf7-48aa-8cd9-27309a81c10d"
> >     },
> >     {
> >       "parameters": {
> >         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
> >       },
> >       "id": "78e3f85c-4702-4fc9-a4a1-96cec3a38d81",
> >       "name": "Normalize",
> >       "type": "n8n-nodes-base.code",
> >       "typeVersion": 2,
> >       "position": [
> >         220,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "conditions": {
> >           "options": {
> >             "caseSensitive": true,
> >             "leftValue": "",
> >             "typeValidation": "loose",
> >             "version": 2
> >           },
> >           "conditions": [
> >             {
> >               "id": "1bcabc46-796b-4397-ba5c-ae381c661d51",
> >               "leftValue": "={{ $json.isInbound }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "boolean",
> >                 "operation": "true",
> >                 "singleValue": true
> >               }
> >             },
> >             {
> >               "id": "71ece3e5-63fb-4063-b8ef-9a30852e7276",
> >               "leftValue": "={{ $json.text }}",
> >               "rightValue": "",
> >               "operator": {
> >                 "type": "string",
> >                 "operation": "notEmpty",
> >                 "singleValue": true
> >               }
> >             }
> >           ],
> >           "combinator": "and"
> >         },
> >         "options": {}
> >       },
> >       "id": "95070355-ccd1-455c-9b39-8924a9e016ad",
> >       "name": "Inbound text?",
> >       "type": "n8n-nodes-base.if",
> >       "typeVersion": 2.2,
> >       "position": [
> >         440,
> >         0
> >       ]
> >     },
> >     {
> >       "parameters": {
> >         "resource": "message",
> >         "operation": "send",
> >         "destinationNumber": "={{ $json.from }}",
> >         "additionalFields": {
> >           "text": "=Recibimos tu mensaje: {{ $json.text }}"
> >         }
> >       },
> >       "id": "3223394f-355d-409a-a7ef-74dd6af3e0bc",
> >       "name": "Reply",
> >       "type": "n8n-nodes-pilot-status.pilotStatus",
> >       "typeVersion": 1,
> >       "position": [
> >         660,
> >         0
> >       ]
> >     }
> >   ],
> >   "connections": {
> >     "Pilot Status Trigger": {
> >       "main": [
> >         [
> >           {
> >             "node": "Normalize",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Normalize": {
> >       "main": [
> >         [
> >           {
> >             "node": "Inbound text?",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     },
> >     "Inbound text?": {
> >       "main": [
> >         [
> >           {
> >             "node": "Reply",
> >             "type": "main",
> >             "index": 0
> >           }
> >         ]
> >       ]
> >     }
> >   },
> >   "pinData": {},
> >   "settings": {
> >     "executionOrder": "v1"
> >   }
> > }
> > ```

> [!TIP]
>
> ¿No sabes de qué tipo es tu número? [`GET /v1/numbers`](https://docs.pilotstatus.com.br/es/api/numbers/list) devuelve su `provider`, y la tarjeta del número en el panel dice cómo se conectó.

## Receta 1: plantilla con botones, respuesta al tocar

Envías una plantilla aprobada con dos botones de respuesta rápida, **Confirmar** y **Reprogramar**. Cuando el contacto toca uno, el workflow responde con un mensaje distinto para cada botón.

* **Start → Send template** envía la plantilla. Cambia el Manual Trigger por lo que inicia tu flujo (un formulario, un CRM, una programación).
* **Pilot Status Trigger → Normalize → Which button?** enruta el toque por la **etiqueta** del botón. La etiqueta funciona en todo tipo de número; el `buttonId` no siempre llega en botones de plantilla.
* **Reply: …** responde con texto libre. El toque abre la ventana de atención de 24 horas de WhatsApp, así que la respuesta en texto libre está permitida incluso en un número oficial.

Qué cambiar: el `templateId` (`appointment_confirmation`), el número de destino, las variables y las dos etiquetas en **Which button?**, que deben ser iguales a los botones de la plantilla (no distingue mayúsculas de minúsculas).

> [accordion] JSON del workflow — receta 1
>
> ```json theme={null}
> {
>   "name": "Pilot Status - Plantilla con botones, respuesta al tocar",
>   "nodes": [
>     {
>       "parameters": {},
>       "id": "1a9f969d-6aaa-40a0-880d-3559e87ab195",
>       "name": "Start",
>       "type": "n8n-nodes-base.manualTrigger",
>       "typeVersion": 1,
>       "position": [
>         0,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "send",
>         "templateId": "appointment_confirmation",
>         "destinationNumber": "+5511999999999",
>         "variablesMode": "json",
>         "variablesJson": "{ \"name\": \"Maria\" }"
>       },
>       "id": "941cfd0d-cbfd-47d3-85ae-396ad74b4049",
>       "name": "Send template",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         220,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "event": "*"
>       },
>       "id": "9ddfa25b-5891-416d-bc11-a63c762fad66",
>       "name": "Pilot Status Trigger",
>       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
>       "typeVersion": 1,
>       "position": [
>         0,
>         220
>       ],
>       "webhookId": "21f729b5-61da-4534-8aea-ef60501a7319"
>     },
>     {
>       "parameters": {
>         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
>       },
>       "id": "3cff268e-0a16-4180-ad9f-33a09f441a1b",
>       "name": "Normalize",
>       "type": "n8n-nodes-base.code",
>       "typeVersion": 2,
>       "position": [
>         220,
>         220
>       ]
>     },
>     {
>       "parameters": {
>         "rules": {
>           "values": [
>             {
>               "conditions": {
>                 "options": {
>                   "caseSensitive": false,
>                   "leftValue": "",
>                   "typeValidation": "loose",
>                   "version": 2
>                 },
>                 "conditions": [
>                   {
>                     "id": "90cebdc2-3801-4d68-9c5f-0b488c22c0f9",
>                     "leftValue": "={{ $json.isInbound }}",
>                     "rightValue": "",
>                     "operator": {
>                       "type": "boolean",
>                       "operation": "true",
>                       "singleValue": true
>                     }
>                   },
>                   {
>                     "id": "6e2685df-379b-4aec-ba33-d7356777af0b",
>                     "leftValue": "={{ $json.text }}",
>                     "rightValue": "Confirmar",
>                     "operator": {
>                       "type": "string",
>                       "operation": "equals"
>                     }
>                   }
>                 ],
>                 "combinator": "and"
>               },
>               "renameOutput": true,
>               "outputKey": "Confirmar"
>             },
>             {
>               "conditions": {
>                 "options": {
>                   "caseSensitive": false,
>                   "leftValue": "",
>                   "typeValidation": "loose",
>                   "version": 2
>                 },
>                 "conditions": [
>                   {
>                     "id": "849ab91b-51b2-4e55-8611-e2469375a5ad",
>                     "leftValue": "={{ $json.isInbound }}",
>                     "rightValue": "",
>                     "operator": {
>                       "type": "boolean",
>                       "operation": "true",
>                       "singleValue": true
>                     }
>                   },
>                   {
>                     "id": "b39e982c-2afd-4071-9ab1-de397b140548",
>                     "leftValue": "={{ $json.text }}",
>                     "rightValue": "Reprogramar",
>                     "operator": {
>                       "type": "string",
>                       "operation": "equals"
>                     }
>                   }
>                 ],
>                 "combinator": "and"
>               },
>               "renameOutput": true,
>               "outputKey": "Reprogramar"
>             }
>           ]
>         },
>         "options": {}
>       },
>       "id": "f81fdd64-b6f7-4a0c-bd20-2740650e474e",
>       "name": "Which button?",
>       "type": "n8n-nodes-base.switch",
>       "typeVersion": 3.2,
>       "position": [
>         440,
>         220
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "send",
>         "destinationNumber": "={{ $json.from }}",
>         "additionalFields": {
>           "text": "Perfecto, tu cita está confirmada. ¡Nos vemos!"
>         }
>       },
>       "id": "9c628837-2ca5-48cf-b4fd-d99bb031b6ba",
>       "name": "Reply: confirmed",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         660,
>         140
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "send",
>         "destinationNumber": "={{ $json.from }}",
>         "additionalFields": {
>           "text": "No hay problema. Responde con el día y la hora que mejor te queden."
>         }
>       },
>       "id": "968cbd09-1ae0-46b2-8b8f-a903d1abce61",
>       "name": "Reply: reschedule",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         660,
>         300
>       ]
>     }
>   ],
>   "connections": {
>     "Start": {
>       "main": [
>         [
>           {
>             "node": "Send template",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Pilot Status Trigger": {
>       "main": [
>         [
>           {
>             "node": "Normalize",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Normalize": {
>       "main": [
>         [
>           {
>             "node": "Which button?",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Which button?": {
>       "main": [
>         [
>           {
>             "node": "Reply: confirmed",
>             "type": "main",
>             "index": 0
>           }
>         ],
>         [
>           {
>             "node": "Reply: reschedule",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     }
>   },
>   "pinData": {},
>   "settings": {
>     "executionOrder": "v1"
>   }
> }
> ```

## Receta 2: un agente de IA responde los mensajes recibidos

Cada texto que envía un contacto va a un AI Agent de n8n con memoria por contacto, y la respuesta vuelve por WhatsApp.

* **Inbound text?** deja pasar solo los mensajes que envió el contacto. Sin él, el eco de la propia respuesta del agente volvería a iniciar el workflow.
* **Memory per contact** usa el número del contacto como clave de sesión, así que cada conversación tiene su propio historial.
* **Send answer** envía `$json.output`, la respuesta del agente, como texto libre. Es una respuesta dentro de la ventana de 24 horas que el contacto acaba de abrir.

Qué cambiar: el mensaje de sistema del **AI Agent**, el modelo y la credencial de OpenAI (o cambia el node de modelo por cualquier otro modelo de chat).

> [!TIP]
>
> Los mensajes de grupo llegan como `message.group` y no se tratan aquí, así que el agente no responde en grupos.

> [accordion] JSON del workflow — receta 2
>
> ```json theme={null}
> {
>   "name": "Pilot Status - Agente de IA responde mensajes recibidos",
>   "nodes": [
>     {
>       "parameters": {
>         "event": "*"
>       },
>       "id": "ae64b31c-a391-4763-a8a6-acc03ea3683a",
>       "name": "Pilot Status Trigger",
>       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
>       "typeVersion": 1,
>       "position": [
>         0,
>         0
>       ],
>       "webhookId": "7f599378-d83f-4342-b56c-0e02411941cc"
>     },
>     {
>       "parameters": {
>         "jsCode": "// Turns every webhook format into the same flat item:\n// - Pilot Status API (QR code) numbers send { event, data }\n// - Evolution GO layer numbers send Evolution GO events (\"Message\", \"SendMessage\", ...)\n// - Evolution v2 layer numbers send Evolution v2 events (\"messages.upsert\", ...)\n// - Meta Cloud API (official) numbers send Meta's native envelope { object, entry }\nconst phoneOf = (jid) =>\n  typeof jid === 'string' && jid.endsWith('@s.whatsapp.net') ? '+' + jid.split('@')[0].split(':')[0] : '';\n\n// Evolution GO and v2 carry the same WhatsApp message object\nconst readWaMessage = (m = {}) => ({\n  text:\n    m.conversation ??\n    m.extendedTextMessage?.text ??\n    m.buttonsResponseMessage?.selectedDisplayText ??\n    m.templateButtonReplyMessage?.selectedDisplayText ??\n    m.listResponseMessage?.title ??\n    m.imageMessage?.caption ??\n    m.videoMessage?.caption ??\n    '',\n  buttonId:\n    m.buttonsResponseMessage?.selectedButtonId ??\n    m.templateButtonReplyMessage?.selectedId ??\n    m.listResponseMessage?.singleSelectReply?.selectedRowId ??\n    '',\n  quotedMessageId:\n    m.extendedTextMessage?.contextInfo?.stanzaId ??\n    m.buttonsResponseMessage?.contextInfo?.stanzaId ??\n    m.templateButtonReplyMessage?.contextInfo?.stanzaId ??\n    m.listResponseMessage?.contextInfo?.stanzaId ??\n    '',\n});\n\nreturn $input.all().map(({ json }) => {\n  // Meta Cloud API (official)\n  if (json.entry) {\n    const value = json.entry[0]?.changes?.[0]?.value ?? {};\n    const msg = value.messages?.[0];\n    return {\n      json: {\n        source: 'meta',\n        isInbound: Boolean(msg),\n        from: msg ? '+' + msg.from : '',\n        name: value.contacts?.[0]?.profile?.name ?? '',\n        text:\n          msg?.text?.body ??\n          msg?.button?.text ??\n          msg?.interactive?.button_reply?.title ??\n          msg?.interactive?.list_reply?.title ??\n          '',\n        buttonId:\n          msg?.button?.payload ??\n          msg?.interactive?.button_reply?.id ??\n          msg?.interactive?.list_reply?.id ??\n          '',\n        quotedMessageId: msg?.context?.id ?? '',\n      },\n    };\n  }\n\n  // Evolution v2 layer\n  if (json.event === 'messages.upsert') {\n    const d = json.data ?? {};\n    const jid = d.key?.remoteJidAlt || d.key?.remoteJid;\n    const from = phoneOf(jid);\n    return {\n      json: {\n        source: 'evolution-v2',\n        isInbound: Boolean(from) && !d.key?.fromMe,\n        from,\n        name: d.pushName ?? '',\n        ...readWaMessage(d.message),\n      },\n    };\n  }\n\n  // Evolution GO layer\n  if (json.event === 'Message' || json.event === 'MESSAGES_UPSERT') {\n    const info = json.data?.Info ?? {};\n    const from = phoneOf(info.Chat) || phoneOf(info.SenderAlt);\n    return {\n      json: {\n        source: 'evolution-go',\n        isInbound: Boolean(from) && !info.IsFromMe && !info.IsGroup,\n        from,\n        name: info.PushName ?? '',\n        ...readWaMessage(json.data?.Message),\n      },\n    };\n  }\n\n  // Pilot Status API (QR code)\n  const data = json.data ?? {};\n  return {\n    json: {\n      source: 'pilot-status',\n      isInbound: ['message.received', 'message.reply'].includes(json.event) && !data.fromMe,\n      from: data.from ?? '',\n      name: data.participantName ?? '',\n      text: data.content ?? '',\n      buttonId: data.buttonId ?? '',\n      quotedMessageId: data.quotedMessageId ?? '',\n    },\n  };\n});"
>       },
>       "id": "17a4eb58-3731-4a96-8dd4-59f0a488f57a",
>       "name": "Normalize",
>       "type": "n8n-nodes-base.code",
>       "typeVersion": 2,
>       "position": [
>         220,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "conditions": {
>           "options": {
>             "caseSensitive": true,
>             "leftValue": "",
>             "typeValidation": "loose",
>             "version": 2
>           },
>           "conditions": [
>             {
>               "id": "a018d314-6d5b-4139-83c5-bbfc493963e2",
>               "leftValue": "={{ $json.isInbound }}",
>               "rightValue": "",
>               "operator": {
>                 "type": "boolean",
>                 "operation": "true",
>                 "singleValue": true
>               }
>             },
>             {
>               "id": "6ccb4b26-eec0-4789-8c44-96c71883248d",
>               "leftValue": "={{ $json.text }}",
>               "rightValue": "",
>               "operator": {
>                 "type": "string",
>                 "operation": "notEmpty",
>                 "singleValue": true
>               }
>             }
>           ],
>           "combinator": "and"
>         },
>         "options": {}
>       },
>       "id": "cabde03a-a26f-4c1a-ba08-5926c848a454",
>       "name": "Inbound text?",
>       "type": "n8n-nodes-base.if",
>       "typeVersion": 2.2,
>       "position": [
>         440,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "promptType": "define",
>         "text": "={{ $json.text }}",
>         "options": {
>           "systemMessage": "Eres el asistente de WhatsApp de nuestra tienda. Responde en el idioma del cliente, en un máximo de 3 frases cortas. Si no sabes la respuesta, di que una persona responderá pronto."
>         }
>       },
>       "id": "bd7d0525-46e2-40af-ad80-e4ac21ad85f5",
>       "name": "AI Agent",
>       "type": "@n8n/n8n-nodes-langchain.agent",
>       "typeVersion": 1.7,
>       "position": [
>         660,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "model": {
>           "__rl": true,
>           "mode": "list",
>           "value": "gpt-4o-mini"
>         },
>         "options": {}
>       },
>       "id": "04190cbe-83cd-4a44-b7da-e4e8f5b4f7b2",
>       "name": "OpenAI Chat Model",
>       "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
>       "typeVersion": 1.2,
>       "position": [
>         600,
>         220
>       ]
>     },
>     {
>       "parameters": {
>         "sessionIdType": "customKey",
>         "sessionKey": "={{ $('Normalize').item.json.from }}",
>         "contextWindowLength": 10
>       },
>       "id": "214a2217-effc-4230-9f64-2937cb7a020c",
>       "name": "Memory per contact",
>       "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
>       "typeVersion": 1.3,
>       "position": [
>         760,
>         220
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "send",
>         "destinationNumber": "={{ $('Normalize').item.json.from }}",
>         "additionalFields": {
>           "text": "={{ $json.output }}"
>         }
>       },
>       "id": "20e4bde8-260d-4fff-aeda-5d70730c276a",
>       "name": "Send answer",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         960,
>         0
>       ]
>     }
>   ],
>   "connections": {
>     "Pilot Status Trigger": {
>       "main": [
>         [
>           {
>             "node": "Normalize",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Normalize": {
>       "main": [
>         [
>           {
>             "node": "Inbound text?",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Inbound text?": {
>       "main": [
>         [
>           {
>             "node": "AI Agent",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "AI Agent": {
>       "main": [
>         [
>           {
>             "node": "Send answer",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "OpenAI Chat Model": {
>       "ai_languageModel": [
>         [
>           {
>             "node": "AI Agent",
>             "type": "ai_languageModel",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Memory per contact": {
>       "ai_memory": [
>         [
>           {
>             "node": "AI Agent",
>             "type": "ai_memory",
>             "index": 0
>           }
>         ]
>       ]
>     }
>   },
>   "pinData": {},
>   "settings": {
>     "executionOrder": "v1"
>   }
> }
> ```

## Receta 3: enviar una plantilla a cada fila de una hoja

Todos los días a las 9:00, el workflow lee una hoja de Google, envía una plantilla a cada fila que aún no se envió y escribe en la fila la hora del envío.

Crea una pestaña llamada **Contactos** con estas columnas:

| `phone` | `name` | `orderId` | `sent` |
| - | - | - | - |
| `+5511999999999` | Ana | `A-1001` | |

* **Not sent yet?** salta las filas con la columna `sent` llena.
* **Send template** pasa `name` y `orderId` como variables de la plantilla. Las claves del JSON deben ser iguales a los nombres de las variables de la plantilla.
* **Idempotency Key** es `orderId-phone`. Cuando n8n reintenta el node (está configurado con 3 intentos), o el workflow se ejecuta de nuevo antes de que se actualice la hoja, la API devuelve la primera respuesta en lugar de enviar dos veces. Consulta [Idempotencia](https://docs.pilotstatus.com.br/es/api/messages/send.md#idempotencia).
* **Mark row as sent** busca la fila por `orderId` y llena `sent`.

Qué cambiar: `YOUR_SPREADSHEET_ID` (el id en la URL de la hoja), la plantilla y las variables.

> [accordion] JSON del workflow — receta 3
>
> ```json theme={null}
> {
>   "name": "Pilot Status - Enviar plantilla a cada fila pendiente de una hoja",
>   "nodes": [
>     {
>       "parameters": {
>         "rule": {
>           "interval": [
>             {
>               "triggerAtHour": 9
>             }
>           ]
>         }
>       },
>       "id": "e1e55c17-7618-4fbd-af54-ffa5c979f598",
>       "name": "Every day at 9:00",
>       "type": "n8n-nodes-base.scheduleTrigger",
>       "typeVersion": 1.2,
>       "position": [
>         0,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "operation": "read",
>         "documentId": {
>           "__rl": true,
>           "mode": "id",
>           "value": "YOUR_SPREADSHEET_ID"
>         },
>         "sheetName": {
>           "__rl": true,
>           "mode": "name",
>           "value": "Contactos"
>         },
>         "options": {}
>       },
>       "id": "161b7994-f34f-4dcf-b0e1-6ac7582647d9",
>       "name": "Read contacts",
>       "type": "n8n-nodes-base.googleSheets",
>       "typeVersion": 4.5,
>       "position": [
>         220,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "conditions": {
>           "options": {
>             "caseSensitive": true,
>             "leftValue": "",
>             "typeValidation": "loose",
>             "version": 2
>           },
>           "conditions": [
>             {
>               "id": "176ac902-c80d-4aa7-a6c3-3014770992fa",
>               "leftValue": "={{ $json.sent }}",
>               "rightValue": "",
>               "operator": {
>                 "type": "string",
>                 "operation": "empty",
>                 "singleValue": true
>               }
>             }
>           ],
>           "combinator": "and"
>         },
>         "options": {}
>       },
>       "id": "57fefa3f-915c-44ae-9001-230f81e943bc",
>       "name": "Not sent yet?",
>       "type": "n8n-nodes-base.if",
>       "typeVersion": 2.2,
>       "position": [
>         440,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "send",
>         "templateId": "order_shipped",
>         "destinationNumber": "={{ $json.phone }}",
>         "variablesMode": "json",
>         "variablesJson": "={{ JSON.stringify({ name: $json.name, order: $json.orderId }) }}",
>         "additionalFields": {
>           "idempotencyKey": "={{ $json.orderId }}-{{ $json.phone }}"
>         }
>       },
>       "id": "e126486c-6fb8-45fb-bfaa-20f51db5d336",
>       "name": "Send template",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         660,
>         0
>       ],
>       "retryOnFail": true,
>       "maxTries": 3,
>       "waitBetweenTries": 5000
>     },
>     {
>       "parameters": {
>         "operation": "update",
>         "documentId": {
>           "__rl": true,
>           "mode": "id",
>           "value": "YOUR_SPREADSHEET_ID"
>         },
>         "sheetName": {
>           "__rl": true,
>           "mode": "name",
>           "value": "Contactos"
>         },
>         "columns": {
>           "mappingMode": "defineBelow",
>           "value": {
>             "orderId": "={{ $('Not sent yet?').item.json.orderId }}",
>             "sent": "={{ $now.toISO() }}"
>           },
>           "matchingColumns": [
>             "orderId"
>           ],
>           "schema": [
>             {
>               "id": "orderId",
>               "displayName": "orderId",
>               "required": false,
>               "defaultMatch": false,
>               "display": true,
>               "type": "string",
>               "canBeUsedToMatch": true
>             },
>             {
>               "id": "sent",
>               "displayName": "sent",
>               "required": false,
>               "defaultMatch": false,
>               "display": true,
>               "type": "string",
>               "canBeUsedToMatch": true
>             }
>           ]
>         },
>         "options": {}
>       },
>       "id": "6d28fd16-0a1f-4c39-9e6c-6379d05c0f81",
>       "name": "Mark row as sent",
>       "type": "n8n-nodes-base.googleSheets",
>       "typeVersion": 4.5,
>       "position": [
>         880,
>         0
>       ]
>     }
>   ],
>   "connections": {
>     "Every day at 9:00": {
>       "main": [
>         [
>           {
>             "node": "Read contacts",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Read contacts": {
>       "main": [
>         [
>           {
>             "node": "Not sent yet?",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Not sent yet?": {
>       "main": [
>         [
>           {
>             "node": "Send template",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Send template": {
>       "main": [
>         [
>           {
>             "node": "Mark row as sent",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     }
>   },
>   "pinData": {},
>   "settings": {
>     "executionOrder": "v1"
>   }
> }
> ```

## Receta 4: alerta por correo de mensajes fallidos

Cada 15 minutos, el workflow lista los últimos 100 mensajes enviados que fallaron y avisa por correo al equipo de cada uno que no había visto antes.

Consulta [`GET /v1/messages`](https://docs.pilotstatus.com.br/es/api/messages/list) en lugar de escuchar `message.failed`, porque el webhook no cubre todos los casos: un número oficial nunca envía `message.failed` (los fallos llegan dentro de `statuses[]` de Meta), y algunos fallos no llegan a ningún webhook. El log tiene todos los fallos, en todo tipo de número.

* **One item per message** separa la lista `data` de la API en un ítem por mensaje.
* **Only new failures** recuerda los ids de mensaje ya vistos entre ejecuciones, así que cada fallo se avisa una vez.
* El correo muestra el `errorCode` y el motivo. El [catálogo de códigos de error](https://docs.pilotstatus.com.br/es/api/messages/log-error-codes.md) explica cada código.

Qué cambiar: la credencial SMTP y las dos direcciones de correo. Para avisar por Slack o Telegram, cambia el último node.

> [!NOTE]
>
> En la primera ejecución todos los fallos de la lista son nuevos, así que llegan hasta 100 correos. Ejecútalo una vez a mano con el node de correo desactivado para llenar la memoria antes.

> [accordion] JSON del workflow — receta 4
>
> ```json theme={null}
> {
>   "name": "Pilot Status - Alerta por correo de mensajes fallidos",
>   "nodes": [
>     {
>       "parameters": {
>         "rule": {
>           "interval": [
>             {
>               "field": "minutes",
>               "minutesInterval": 15
>             }
>           ]
>         }
>       },
>       "id": "3c093096-a5dc-4fb3-9578-b1030deb9fdd",
>       "name": "Every 15 minutes",
>       "type": "n8n-nodes-base.scheduleTrigger",
>       "typeVersion": 1.2,
>       "position": [
>         0,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "resource": "message",
>         "operation": "getAll",
>         "listPageSize": 100,
>         "listDirection": "out",
>         "listStatus": "FAILED"
>       },
>       "id": "d0f3e8cb-e9c3-4dd9-b2d3-a3389009514e",
>       "name": "List failed messages",
>       "type": "n8n-nodes-pilot-status.pilotStatus",
>       "typeVersion": 1,
>       "position": [
>         220,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "fieldToSplitOut": "data",
>         "options": {}
>       },
>       "id": "13cb9803-5310-4d31-bb0b-c6160b55bc26",
>       "name": "One item per message",
>       "type": "n8n-nodes-base.splitOut",
>       "typeVersion": 1,
>       "position": [
>         440,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "operation": "removeItemsSeenInPreviousExecutions",
>         "dedupeValue": "={{ $json.id }}",
>         "options": {}
>       },
>       "id": "f73b175e-c60a-4988-9af6-3e435f2f8b66",
>       "name": "Only new failures",
>       "type": "n8n-nodes-base.removeDuplicates",
>       "typeVersion": 2,
>       "position": [
>         660,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "fromEmail": "alerts@example.com",
>         "toEmail": "team@example.com",
>         "subject": "=Mensaje de WhatsApp fallido: {{ $json.errorCode }} a {{ $json.to }}",
>         "emailFormat": "text",
>         "text": "=Para: {{ $json.to }}\nPlantilla: {{ $json.template }}\nCódigo de error: {{ $json.errorCode }}\nMotivo: {{ $json.errorMessage }}\nCreado: {{ $json.createdAt }}\nID del mensaje: {{ $json.id }}",
>         "options": {}
>       },
>       "id": "b27b02a7-8e5e-49ce-8347-80b875e35383",
>       "name": "E-mail the team",
>       "type": "n8n-nodes-base.emailSend",
>       "typeVersion": 2.1,
>       "position": [
>         880,
>         0
>       ]
>     }
>   ],
>   "connections": {
>     "Every 15 minutes": {
>       "main": [
>         [
>           {
>             "node": "List failed messages",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "List failed messages": {
>       "main": [
>         [
>           {
>             "node": "One item per message",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "One item per message": {
>       "main": [
>         [
>           {
>             "node": "Only new failures",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Only new failures": {
>       "main": [
>         [
>           {
>             "node": "E-mail the team",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     }
>   },
>   "pinData": {},
>   "settings": {
>     "executionOrder": "v1"
>   }
> }
> ```

## Receta 5: guardar las respuestas de un WhatsApp Flow en una hoja

Cada vez que alguien envía un [WhatsApp Flow](https://docs.pilotstatus.com.br/es/guides/flow-responses.md), las respuestas se convierten en una fila nueva de una hoja de Google.

`flow.response_received` mantiene el formato `{ event, data }` de Pilot Status incluso en números oficiales, así que aquí el Trigger puede escuchar solo ese evento y no hace falta el node Normalize.

* **Answers to columns** guarda la hora, el número del contacto, el id del Flow y las respuestas como texto JSON. En un Flow con endpoint de datos, lo que escribió la persona está en `submitted`, una entrada por pantalla; en los demás, está en `response`.
* **Append to sheet** escribe una fila por envío. Crea una pestaña llamada **Respuestas del Flow** con las columnas `receivedAt`, `phone`, `flowId` y `answers`.

Qué cambiar: `YOUR_SPREADSHEET_ID`. Para tener una columna por pregunta, cambia el campo `answers` por un campo por respuesta, por ejemplo `{{ $json.data.response.nota }}`.

> [accordion] JSON del workflow — receta 5
>
> ```json theme={null}
> {
>   "name": "Pilot Status - Guardar respuestas de WhatsApp Flow en Google Sheets",
>   "nodes": [
>     {
>       "parameters": {
>         "event": "flow.response_received"
>       },
>       "id": "224a8a4b-de26-4129-912b-7672a2131e70",
>       "name": "Pilot Status Trigger",
>       "type": "n8n-nodes-pilot-status.pilotStatusTrigger",
>       "typeVersion": 1,
>       "position": [
>         0,
>         0
>       ],
>       "webhookId": "eda6bf21-1dee-4b14-9dc9-c7522456a524"
>     },
>     {
>       "parameters": {
>         "assignments": {
>           "assignments": [
>             {
>               "id": "3c2424c4-bf19-492f-a158-deb3f78b8b01",
>               "name": "receivedAt",
>               "value": "={{ $json.data.receivedAt }}",
>               "type": "string"
>             },
>             {
>               "id": "e9783605-f132-41cc-bff0-ddd18518a08c",
>               "name": "phone",
>               "value": "={{ $json.data.from }}",
>               "type": "string"
>             },
>             {
>               "id": "1c333ec0-f165-4e67-93f3-185ee1893375",
>               "name": "flowId",
>               "value": "={{ $json.data.flowId }}",
>               "type": "string"
>             },
>             {
>               "id": "14346ce2-6628-4b84-84ab-20a2d45dbd27",
>               "name": "answers",
>               "value": "={{ JSON.stringify($json.data.submitted ? $json.data.submitted.map(s => s.data) : $json.data.response) }}",
>               "type": "string"
>             }
>           ]
>         },
>         "options": {}
>       },
>       "id": "6e8661e5-eadd-4559-9d76-2bd0e82c9e22",
>       "name": "Answers to columns",
>       "type": "n8n-nodes-base.set",
>       "typeVersion": 3.4,
>       "position": [
>         220,
>         0
>       ]
>     },
>     {
>       "parameters": {
>         "operation": "append",
>         "documentId": {
>           "__rl": true,
>           "mode": "id",
>           "value": "YOUR_SPREADSHEET_ID"
>         },
>         "sheetName": {
>           "__rl": true,
>           "mode": "name",
>           "value": "Respuestas del Flow"
>         },
>         "columns": {
>           "mappingMode": "autoMapInputData",
>           "value": {},
>           "matchingColumns": [],
>           "schema": []
>         },
>         "options": {}
>       },
>       "id": "3223ad95-f889-4e8e-8846-e5a84c12104c",
>       "name": "Append to sheet",
>       "type": "n8n-nodes-base.googleSheets",
>       "typeVersion": 4.5,
>       "position": [
>         440,
>         0
>       ]
>     }
>   ],
>   "connections": {
>     "Pilot Status Trigger": {
>       "main": [
>         [
>           {
>             "node": "Answers to columns",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     },
>     "Answers to columns": {
>       "main": [
>         [
>           {
>             "node": "Append to sheet",
>             "type": "main",
>             "index": 0
>           }
>         ]
>       ]
>     }
>   },
>   "pinData": {},
>   "settings": {
>     "executionOrder": "v1"
>   }
> }
> ```

## Solución de problemas

| Síntoma | Causa | Solución |
| - | - | - |
| El Trigger nunca se dispara | El workflow está inactivo (Production URL), o el webhook se registró con la Test URL | Activa el workflow y registra la **Production URL** |
| El Trigger responde `200 Ignored event` | **Event** está en un evento específico, y el cuerpo entregado es otro evento o el sobre de Meta | Usa **All Events** y filtra en el workflow |
| Tocar un botón no hace nada en un número por código QR | El Trigger escucha **Message Received** | Los toques llegan como `message.reply`: usa **All Events** |
| `$json.data` es `undefined` | El número es oficial, y el cuerpo es el sobre de Meta | Agrega el node **Normalize** |
| `401 Invalid signature` | El **Signing Secret** no coincide con el webhook | Pega el secreto actual, o rótalo y pega el nuevo |
| `403 TENANT_SCOPE_NOT_ALLOWED` | Clave de workspace o de cuenta sin número | Llena el **WhatsApp Number ID** en la credencial |
| `400 WORKSPACE_ID_REQUIRED` | Clave de cuenta (`ps_account_`) sin workspace | Llena el **Workspace ID** en la credencial |
| El registro Automatic falla con `400 NUMBER_REQUIRED` | Clave de workspace o de cuenta sin número | Llena el **WhatsApp Number ID** en la credencial |
| La respuesta sale desde otro número | El webhook y la credencial son de números distintos | Usa el mismo número en los dos |

## Relacionados

* [Eventos de webhook](https://docs.pilotstatus.com.br/es/api/webhooks/events.md)
* [Enviar un mensaje](https://docs.pilotstatus.com.br/es/api/messages/send.md)
* [SDKs](https://docs.pilotstatus.com.br/es/integrations/sdks.md)
* [Servidor MCP](https://docs.pilotstatus.com.br/es/integrations/mcp-server.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.