AutomationFlowsAI & RAG › Whatsapp Bot Flow

Whatsapp Bot Flow

Whatsapp-Bot-Flow. Uses whatsappTrigger, agent, supabase, whatsapp. Event-driven trigger; 60 nodes.

Event trigger★★★★★ complexityAI-powered60 nodesWhatsApp TriggerAgentSupabaseWhatsAppOpenAI ChatMemory Buffer WindowGmailSupabase Tool
AI & RAG Trigger: Event Nodes: 60 Complexity: ★★★★★ AI nodes: yes Added:

This workflow follows the Agent → Gmail recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "nodes": [
    {
      "parameters": {
        "updates": [
          "messages"
        ],
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsappTrigger",
      "typeVersion": 1,
      "position": [
        -768,
        -96
      ],
      "id": "02c555ea-c2af-4e78-bb89-573b13801884",
      "name": "WhatsApp Trigger",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $node[\"WhatsApp Trigger\"].json.message.text }}",
        "options": {
          "systemMessage": "=Est\u00e1s hablando con el cliente: {{ $node['Datos_Usuario'].json.Nombre_cliente }}\n\n=== IDENTIDAD Y SALUDO ===\nEres un asesor log\u00edstico de Omega Cargo Express.\nTono: Profesional, directo y amable. ESTRICTO: Debes incluir al menos 1 o 2 emojis (\ud83d\udce6, \u2708\ufe0f, \ud83d\udea2, \ud83d\udccd, \ud83d\ude9a, \u2705, \u2728) en CADA UNO de tus mensajes para mantener un tono amigable. Responde SOLO sobre env\u00edos.\nREGLA DE SALUDO: Si es el primer mensaje, saluda al cliente por su nombre de forma entusiasta y ve directo al grano. Evita saludos redundantes en mensajes posteriores.\n\n=== CONOCIMIENTO GENERAL (FAQ Y PRODUCTOS) ===\nDestinos: Pickup en Canad\u00e1. A\u00e9reos a todo el mundo. Mar\u00edtimos SOLO para Venezuela, Honduras, Guatemala, El Salvador y Nicaragua.\nTiempos: M\u00e9xico Regular (12-15 d\u00edas h\u00e1b.) / M\u00e9xico Express (2-5 d\u00edas h\u00e1b.), Colombia (7-10 d\u00edas h\u00e1b.), Venezuela A\u00e9reo (10-12 d\u00edas h\u00e1b.) / Mar\u00edtimo (35-45 d\u00edas), Cuba (3-6 semanas).\nTarifas: Mayor entre peso f\u00edsico y volum\u00e9trico. M\u00ednimo: 10 lbs (Ven, Col, Per, Cub), 15 lbs (Mex consolidados), 1 lb (otros).\nImpuestos: Incluidos para Colombia y Venezuela. M\u00e9xico si es menor a $400 CAD. Cuba NO incluidos.\nL\u00edmite: M\u00e1ximo a declarar $2000.\nCasillero: Gratis. Reempaque $10. Bodegaje gratis 15 d\u00edas.\nDerivaci\u00f3n: Carga industrial, mudanzas o m\u00e1s de $2000 -> ###ACCION_TRANSFERIR###\n\n\ud83d\udccd UBICACI\u00d3N Y HORARIOS:\nOficina Principal: 2601 Matheson Blvd E. #6, Puerta Atr\u00e1s, Mississauga, ON, L4W 5A8. Contamos con 22 puntos de recepci\u00f3n en Canad\u00e1.\nHorarios: Lunes a viernes de 9:00 a.m. a 6:00 p.m. S\u00e1bados de 10:00 a.m. a 4:00 p.m. Domingos con cita previa.\n\n\ud83d\udcb3 M\u00c9TODOS DE PAGO:\nTarjeta de cr\u00e9dito, PayPal, App de Omega Cargo Express, Efectivo, Transferencia bancaria o pago directo en oficina.\n\n\ud83d\ude9a REGLAS ESPECIALES CENTROAM\u00c9RICA (Honduras, Guatemala, Nicaragua):\nEnv\u00edo a\u00e9reo m\u00ednimo: 110 lbs. Los familiares deben retirar en el aeropuerto presentando su documento de identidad.\n\n\ud83d\ude97 ENV\u00cdO DE VEH\u00cdCULOS A M\u00c9XICO:\nModelos permitidos: 2017\u20132018. Salidas desde Toronto desde USD $4,500. El VIN debe iniciar obligatoriamente con 1, 2, 3, 4 o 5.\n\n\u2b50 PROMOCI\u00d3N:\nSi el cliente deja un review en Google, recibe un 5% de descuento en su pr\u00f3ximo env\u00edo.\n\n\ud83d\udce6 MEDIDAS Y PESOS CAJAS EST\u00c1NDAR OMEGA:\nSmall: 16x13x13 in, 20 lbs.\nMedium: 18x18x16 in, 30 lbs.\nLarge: 23x15x15 in, 40 lbs.\nExtra Large: 27x15x16 in, 55 lbs.\nJumbo: 20x20x20 in, 60 lbs.\n\n=== MODO RASTREO (EXCEPCI\u00d3N DE ALTA PRIORIDAD Y PRIVACIDAD) ===\nSi el cliente proporciona un n\u00famero de gu\u00eda o pregunta por el estado de su env\u00edo:\n\n1. DET\u00c9N el flujo de cotizaci\u00f3n actual.\n2. Ejecuta obligatoriamente la herramienta \"Rastrear_Paquete\" enviando el n\u00famero de gu\u00eda.\n\nAl recibir la respuesta de la API HTTP (\u00a1ATENCI\u00d3N A ESTAS REGLAS ESTRICTAS!):\n- IGNORA por completo si los campos principales como \"TrackingActive\" o \"TrackingDateTime\" est\u00e1n vac\u00edos. \u00a1El paquete S\u00cd existe aunque esos campos est\u00e9n en blanco! Ve DIRECTAMENTE a buscar el arreglo llamado \"Detail\" para ver el estatus.\n- \ud83d\udea8 REGLA DE PRIVACIDAD CR\u00cdTICA: Por pol\u00edticas de seguridad de Omega Cargo Express, SOLO tienes permitido mostrarle al cliente los siguientes datos del paquete: Estado actual, Fecha de entrega o actualizaci\u00f3n, Contenido, Origen (Solo Ciudad y Pa\u00eds) y Destino (Solo Ciudad y Pa\u00eds).\n- \ud83d\udeab ESTRICTAMENTE PROHIBIDO: NUNCA reveles nombres de remitentes o consignatarios, n\u00fameros de tel\u00e9fono, correos electr\u00f3nicos, ni direcciones exactas (calles, avenidas, c\u00f3digos postales). Si el cliente pregunta por estos datos, dile cort\u00e9smente que por pol\u00edticas de privacidad solo puedes brindar el estatus general del env\u00edo.\n\nTras informar el resultado del rastreo (respetando la privacidad), preg\u00fantale: \"\u00bfDeseas cotizar o realizar un nuevo env\u00edo?\". Si dice que s\u00ed, inicia el Flujo de Recolecci\u00f3n desde el PASO 1.\n\n=== MODO ESCALAMIENTO (ATENCI\u00d3N HUMANA) - PRIORIDAD ABSOLUTA ===\n\ud83d\udea8 ESTA REGLA ANULA CUALQUIER OTRA INSTRUCCI\u00d3N, INCLUIDO EL SALUDO INICIAL. \ud83d\udea8\nSi en CUALQUIER MOMENTO (incluso en el primer mensaje) el cliente solicita expl\u00edcitamente hablar con un humano, asesor, agente, representante, o si manifiesta frustraci\u00f3n:\n1. IGNORA la regla de saludo.\n2. DET\u00c9N por completo el Flujo de Recolecci\u00f3n (no hagas preguntas).\n3. Responde \u00daNICAMENTE indicando que lo transferir\u00e1s. Ejemplo: \"Entiendo. Te transferir\u00e9 en este momento con uno de nuestros asesores. \ud83d\udc68\u200d\ud83d\udcbb\"\n4. Inmediatamente despu\u00e9s de tu respuesta, DEBES imprimir EXACTAMENTE esta etiqueta: ###ACCION_TRANSFERIR###\n\n=== TU MISI\u00d3N (FLUJO DE RECOLECCI\u00d3N) ===\nDebes obtener datos precisos para cotizar.\n\ud83d\udea8 REGLA 1: Haz UNA (1) SOLA PREGUNTA por mensaje para mantener la conversaci\u00f3n din\u00e1mica.\n\ud83d\udea8 REGLA 2: PROHIBIDO IMPRIMIR RES\u00daMENES PARCIALES. Nunca muestres un resumen hasta completar los 6 pasos.\n\ud83d\udea8 REGLA 3: Sigue ESTE ORDEN estricto:\n\n\u25ba PASO 1 - DESTINO: Pregunta pa\u00eds y ciudad. \ud83d\udea8 REGLA: Si el cliente solo indica el pa\u00eds, DEBES preguntarle la ciudad espec\u00edfica antes de avanzar.\n\u25ba PASO 2 - MODALIDAD: Si el destino NO permite mar\u00edtimo, asigna \"A\u00e9reo\" autom\u00e1ticamente, inf\u00f3rmalo y pasa al Paso 3. Si permite mar\u00edtimo, pregunta: \"\u00bfPrefieres env\u00edo A\u00e9reo o Mar\u00edtimo?\".\n\u25ba PASO 3 - CARGA: Pregunta cantidad de cajas y contenido exacto. (OBLIGATORIO usar herramienta \"articulos\"). \ud83d\udea8 REGLA CR\u00cdTICA: Al aceptar el contenido, DEBES incluir obligatoriamente cualquier advertencia que est\u00e9 en \"articulos_restringidos\" o \"notas_especiales\" (ejemplo: \"Recuerda que para Venezuela los celulares deben estar homologados por CONATEL\") ANTES de pasar al Paso 4.\n\u25ba PASO 4 - EMPAQUE Y TAMA\u00d1O (CR\u00cdTICO):\nPrimero pregunta: \"\u00bfDeseas usar tus propias cajas o prefieres usar nuestras Cajas Est\u00e1ndar?\".\nSi el cliente elige \"Cajas Est\u00e1ndar\", DEBES cumplir estas DOS reglas INQUEBRANTABLES:\n1. \ud83d\udeab ESTRICTAMENTE PROHIBIDO: NO debes listar, escribir ni mencionar las medidas o pesos de las cajas en tu respuesta. La imagen lo har\u00e1 por ti.\n2. \ud83d\udea8 ETIQUETA OBLIGATORIA: DEBES imprimir EXACTAMENTE la etiqueta correspondiente al pa\u00eds al FINAL de tu mensaje:\n- Si es M\u00e9xico: ###FOTO_MEXICO###\n- Si es Colombia: ###FOTO_COLOMBIA###\n- Si es Venezuela: ###FOTO_VENEZUELA###\n- Si es Per\u00fa: ###FOTO_PERU###\n- Si es Nicaragua: ###FOTO_NICARAGUA###\n- Si es otro pa\u00eds: ###FOTO_GLOBAL###\n\nEjemplo de c\u00f3mo DEBE ser tu respuesta exacta si el destino es Venezuela:\n\"Excelente elecci\u00f3n. Te acabo de enviar nuestras opciones de Cajas Est\u00e1ndar. \u00bfQu\u00e9 tama\u00f1o de caja prefieres: Small, Medium, Large, Extra Large o Jumbo? ###FOTO_VENEZUELA###\"\nNO AVANCES al Paso 5 hasta que el cliente confirme el tama\u00f1o exacto.\n\u25ba PASO 5 - CONTACTO: Solicita nombre, apellido, correo electr\u00f3nico y n\u00famero de tel\u00e9fono.\n\u25ba PASO 6 - ORIGEN: Pregunta c\u00f3mo entregar\u00e1 la carga (Contamos con nuestra Oficina principal en Mississauga, Puntos de Recepci\u00f3n o servicio de Pickup). \ud83d\udea8 REGLA: Si el cliente elige Punto de Recepci\u00f3n, debes pedirle que confirme el nombre exacto del local de la lista.\n\n=== USO DE HERRAMIENTAS ===\n\u25ba \"articulos\": Ejecutar apenas el cliente declare el contenido.\n\u25ba \"sucursales\": Ejecutar al recibir ciudad/c\u00f3digo postal de origen en Canad\u00e1.\n\u25ba \"Rastrear_Paquete\": Ejecutar SOLO cuando el cliente d\u00e9 un n\u00famero de gu\u00eda o pida rastreo. \n\n=== TRIGGERS (ETIQUETAS DE ACCI\u00d3N) ===\n\u25ba FOTO CAJAS: Si en el Paso 4 el cliente elige \"Cajas Est\u00e1ndar\", agrega al final de tu mensaje la etiqueta del pa\u00eds correspondiente (ej. ###FOTO_MEXICO###, ###FOTO_VENEZUELA###, etc.).\n\u25ba TRANSFERENCIA: Si el cliente pide un asesor, carga industrial, mudanzas o el valor supera los $2000, agrega al final de tu mensaje: ###ACCION_TRANSFERIR###\n\u25ba FINALIZAR: Solo al terminar los 6 pasos y dar el resumen, agrega al final de tu mensaje: ###FINALIZAR_Y_ENVIAR_EMAIL###\n\n=== CIERRE Y COTIZACI\u00d3N ===\nSOLO CUANDO LOS 6 PASOS EST\u00c9N COMPLETOS, genera este resumen EXACTO.\n\ud83d\udea8 REGLA DE EXCEPCI\u00d3N: En este resumen final S\u00cd TIENES PERMITIDO y ES OBLIGATORIO escribir el peso y las medidas exactas. Busca en tu conocimiento general la tabla \"\ud83d\udce6 MEDIDAS Y PESOS CAJAS EST\u00c1NDAR OMEGA\" y rellena los datos seg\u00fan el tama\u00f1o que eligi\u00f3 el cliente. EST\u00c1 PROHIBIDO poner \"Por definir\" si el cliente eligi\u00f3 una Caja Est\u00e1ndar.\n\n\"Excelente. Aqu\u00ed tienes el resumen final de tu cotizaci\u00f3n:\n\n\ud83d\udc64 Nombre completo: [Nombre y Apellido]\n\ud83d\udce7 Correo Electr\u00f3nico: [Correo]\n\ud83d\udcf1 Tel\u00e9fono de contacto: [Tel\u00e9fono]\n\u2708\ufe0f/\ud83d\udea2 Ruta: [A\u00e9reo o Mar\u00edtimo]\n\ud83d\udce6 Tipo de empaque: [Empaque Propio o \"Caja Est\u00e1ndar - Tama\u00f1o elegido\"]\n\u2696\ufe0f Peso total aproximado: [Peso exacto del tama\u00f1o elegido]\n\ud83d\udccf Medidas de cada caja: [Medidas exactas del tama\u00f1o elegido]\n\ud83d\udce6 Contenido detallado: [Contenido]\n\ud83d\udccd Origen: [Ciudad Exacta y Nombre del Punto de Recepci\u00f3n, Oficina Principal, o Direcci\u00f3n de Pickup. ESTRICTAMENTE PROHIBIDO poner solo la provincia o pa\u00eds]\n\ud83d\udccd Destino: [Ciudad Exacta, Pa\u00eds. ESTRICTAMENTE PROHIBIDO poner solo el pa\u00eds]\n\nTus datos ya est\u00e1n siendo procesados. \u2705 En breve un asesor te contactar\u00e1.\"\n\n\ud83d\udea8 REGLA DE SISTEMA CR\u00cdTICA: \nInmediatamente despu\u00e9s del texto de arriba, debes imprimir EXACTAMENTE esta etiqueta: ###FINALIZAR_Y_ENVIAR_EMAIL###\nEST\u00c1 ESTRICTAMENTE PROHIBIDO agregar despedidas (como \"\u00a1Gracias por elegirnos!\"), texto extra o emojis despu\u00e9s de esa etiqueta. Tu mensaje DEBE terminar con esa etiqueta para que el sistema interno funcione.",
          "maxIterations": 8
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        784,
        -368
      ],
      "id": "2a6a77ea-ad77-489f-9ca2-310a47793695",
      "name": "AI Agent"
    },
    {
      "parameters": {
        "tableId": "Clientes",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "id_whatsapp",
              "fieldValue": "={{ $node[\"WhatsApp Trigger\"].json.message.from.id.toString() }}"
            },
            {
              "fieldId": "Nombre",
              "fieldValue": "={{ $node[\"WhatsApp Trigger\"].json.message.from.first_name }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        656,
        0
      ],
      "id": "2e8c31d6-dde1-4740-8614-d6357c7de037",
      "name": "Create a row",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $node[\"WhatsApp Trigger\"].json.message.from.id }}",
        "text": "={{ $('AI Agent').item.json.output.replace('###FINALIZAR_Y_ENVIAR_EMAIL###','').replace(/###FOTO_[A-Z]+###/g, '').trim() }}"
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        2704,
        464
      ],
      "id": "d1790acc-011f-478a-9aca-c7252c994859",
      "name": "Send a text message",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "5d77a537-9cb6-41c1-b350-3d016106682f",
              "name": "Nombre_cliente",
              "value": "={{ $json.contact_name }}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        112,
        -160
      ],
      "id": "d1324935-a0e4-4f4e-9a07-9c73a4d05b07",
      "name": "Datos_Usuario"
    },
    {
      "parameters": {
        "operation": "get",
        "tableId": "Clientes",
        "filters": {
          "conditions": [
            {
              "keyName": "=id_whatsapp",
              "keyValue": "={{ $('WhatsApp Trigger').item.json.message.from.id }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        288,
        -112
      ],
      "id": "e1784573-a813-4552-a03c-68e429e22835",
      "name": "Get a row",
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "b715c043-bcbb-4b7a-84f2-640acd923992",
              "leftValue": "={{ $json.content }}",
              "rightValue": "/responder",
              "operator": {
                "type": "string",
                "operation": "startsWith"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -112,
        -112
      ],
      "id": "b25f7915-7580-4202-890d-bb0677e371d0",
      "name": "If3"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $json.content.split(' ')[1] }}",
        "text": "={{ $json.content.split(' ').slice(2).join(' ') }}"
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        96,
        32
      ],
      "id": "7515b08b-bb66-4e88-9312-0442e4dd6f3d",
      "name": "Send a text message2",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "4294d494-e671-4043-950a-c2f3132f171d",
              "leftValue": "={{ $json.output }}",
              "rightValue": "###ACCION_TRANSFERIR###",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1200,
        -272
      ],
      "id": "104301de-244b-4eef-8c1d-73c53a01f505",
      "name": "If_Transferencia"
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "Clientes",
        "filters": {
          "conditions": [
            {
              "keyName": "id_whatsapp",
              "condition": "eq",
              "keyValue": "={{ $('WhatsApp Trigger').item.json.message.from.id }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "modo_atencion",
              "fieldValue": "humano"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        2144,
        -256
      ],
      "id": "27a0cdd0-b57d-4838-8734-6d5327e4d798",
      "name": "Update a row",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('WhatsApp Trigger').item.json.message.from.id }}",
        "text": "Entendido. Te estoy transfiriendo con un agente de atenci\u00f3n al cliente de Omega Cargo Express. En breve un asesor se pondr\u00e1 en contacto contigo para ayudarte de forma personalizada."
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        1504,
        -288
      ],
      "id": "d21e4bf3-3f00-4cd4-a9b8-8ba6c76c00fd",
      "name": "Send a text message3",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "a1550836-b329-4315-8b76-7a0f060c1f90",
              "leftValue": "={{ $json.content }}",
              "rightValue": "/cerrar",
              "operator": {
                "type": "string",
                "operation": "startsWith"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -384,
        -112
      ],
      "id": "b9a93a0c-7444-41b6-afd4-e5fe92a922ae",
      "name": "If_Comando_Asesor"
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "Clientes",
        "filters": {
          "conditions": [
            {
              "keyName": "id_whatsapp",
              "condition": "eq",
              "keyValue": "={{ $json.content.replace('/cerrar ', '') }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "modo_atencion",
              "fieldValue": "bot"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        -208,
        -256
      ],
      "id": "18a7be37-9b7a-4095-83ee-d35b9917273b",
      "name": "Update a row1",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('WhatsApp Trigger').item.json.message.text.replace('/cerrar ', '') }}",
        "text": "El asesor ha cerrado tu caso. Vuelvo a ser tu asistente virtual, \u00bfen qu\u00e9 m\u00e1s te puedo ayudar"
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        16,
        -416
      ],
      "id": "d7529083-6317-43f6-9e47-c5dcb9e0c949",
      "name": "Aviso Retorno a Bot",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('WhatsApp Trigger').item.json.message.from.id }}",
        "text": "\u2705 Ticket cerrado exitosamente. El cliente ha regresado al modo bot."
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        224,
        -416
      ],
      "id": "fb20ac05-2c7b-49cf-a982-38a3a62c8181",
      "name": "Confirmar a Asesor",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "openai/gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "openai/gpt-4o-mini"
        },
        "builtInTools": {},
        "options": {
          "maxTokens": 1000,
          "temperature": 0.8
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        816,
        80
      ],
      "id": "4f2bdcc8-577e-4e4e-ae79-90f09da34b35",
      "name": "OpenAI Chat Model",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('WhatsApp Trigger').first().json.message.from.id }}_013",
        "contextWindowLength": 8
      },
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        1072,
        176
      ],
      "id": "a60424c1-f72c-4dd3-9a5a-009ded7fda9f",
      "name": "Simple Memory"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "af9e0683-1e9e-43ac-b5c4-8820170a8c31",
              "leftValue": "={{ $json.output }}",
              "rightValue": "###FINALIZAR_Y_ENVIAR_EMAIL###",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        2368,
        400
      ],
      "id": "c8af0592-624d-4d6e-83a8-098c7712f3f1",
      "name": "if_email"
    },
    {
      "parameters": {
        "sendTo": "TU_CORREO@gmail.com",
        "subject": "=Nueva Cotizaci\u00f3n solicitada por: {{ $('Datos_Usuario').item.json.Nombre_cliente }}",
        "message": "=<div style=\"font-family: Arial, sans-serif; border: 1px solid #003366; padding: 20px; border-radius: 10px;\">\n  <h2 style=\"color: #003366;\">\ud83d\ude80 Nueva Cotizaci\u00f3n Omega Cargo</h2>\n  <hr>\n  <p><b>\ud83d\udc64 Cliente:</b> {{ $('Extraer_Datos').item.json[\"Nombre\"] }}</p>\n  <p><b>\ud83d\udce7 Email:</b> {{ $('Extraer_Datos').item.json[\"Email\"] }}</p>\n  <p><b>\ud83d\udcf1 Tel\u00e9fono:</b> {{ $('Extraer_Datos').item.json[\"Telefono\"] }}</p>\n  <p><b>\u2708\ufe0f Ruta:</b> {{ $('Extraer_Datos').item.json[\"Ruta\"] }}</p>\n  <p><b>\ud83d\udce6 Tipo de empaque:</b> {{ $('Extraer_Datos').item.json[\"Empaque\"] }}</p>\n  <p><b>\u2696\ufe0f Peso:</b> {{ $('Extraer_Datos').item.json[\"Peso\"] }}</p>\n  <p><b>\ud83d\udccf Medidas:</b> {{ $('Extraer_Datos').item.json[\"Medidas\"] }}</p>\n  <p><b>\ud83d\udce6 Carga:</b> {{ $('Extraer_Datos').item.json[\"Carga\"] }}</p>\n  <p><b>\ud83d\udccd Origen:</b> {{ $('Extraer_Datos').item.json[\"Origen\"] }}</p>\n  <p><b>\ud83d\udccd Destino:</b> {{ $('Extraer_Datos').item.json[\"Destino\"] }}</p>\n</div>",
        "options": {
          "appendAttribution": false
        }
      },
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.2,
      "position": [
        2336,
        -96
      ],
      "id": "d2b929ee-21d0-42b0-b4b5-45608d8ec90d",
      "name": "Send a message",
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('WhatsApp Trigger').item.json.message.from.id }}",
        "text": "={{ $('AI Agent').item.json.output.replace('###FINALIZAR_Y_ENVIAR_EMAIL###', '') }}"
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        2560,
        -80
      ],
      "id": "a12e38a8-4c60-4fad-b9a6-cc754a176b7a",
      "name": "Confirmacion_Cliente_Cotizacion",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "HERRAMIENTA OBLIGATORIA PARA SUCURSALES. \u00dasala para buscar sucursales cuando el cliente te d\u00e9 una ciudad, direcci\u00f3n o c\u00f3digo postal. \n\ud83d\udea8 REGLA ESTRICTA DE FORMATO: \n1. TIENES TOTALMENTE PROHIBIDO ENVIAR COMAS (,). Si el cliente menciona una ciudad y un estado (ejemplo: \"Courtice, ON\" o \"Courtice, Ontario\"), env\u00eda \u00daNICAMENTE el nombre de la ciudad (\"Courtice\"). \n2. Si el cliente te da un c\u00f3digo postal (ejemplo: \"J2B 2N1\"), debes enviarlo EXACTO y COMPLETO respetando el espacio, pero SIN comas. \nSi la base de datos devuelve resultados, mu\u00e9stralos completos. Devuelve la lista exacta de sucursales. Si hay varias, devu\u00e9lvelas TODAS. PROHIBIDO inventar datos. Si no devuelve nada, ofrece Pickup.",
        "operation": "getAll",
        "tableId": "=sucursales_canada",
        "filters": {
          "conditions": [
            {
              "keyName": "ciudad",
              "condition": "ilike",
              "keyValue": "={{ $fromAI('ciudad_busqueda') }}"
            },
            {
              "keyName": "provincia",
              "condition": "ilike",
              "keyValue": "={{ $fromAI('ciudad_busqueda') }}"
            },
            {
              "keyName": "codigo_postal",
              "condition": "ilike",
              "keyValue": "={{ $fromAI('ciudad_busqueda') }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabaseTool",
      "typeVersion": 1,
      "position": [
        1152,
        -16
      ],
      "id": "e304f2fa-a800-48d5-bcec-9013a0a8b2b5",
      "name": "sucursales",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "try {\n   const texto = $json.output || \"\";\n\n   if (!texto || texto.trim() === \"\") {\n       return {\n           \"Nombre\": \"Esperando datos\", \"Email\": \"Esperando\", \"Telefono\": \"Esperando\",\n           \"Ruta\": \"Esperando\", \"Carga\": \"Esperando\", \"Peso\": \"Esperando\",\n           \"Origen\": \"Esperando\", \"Destino\": \"Esperando\", \"Empaque\": \"Esperando\", \"Medidas\": \"Esperando\"\n       };\n   }\n\n   // Busca la l\u00ednea que contiene la palabra clave y extrae todo despu\u00e9s de los \":\"\n   function extraerDato(palabraClave) {\n       // Buscamos la l\u00ednea exacta ignorando may\u00fasculas/min\u00fasculas\n       const regex = new RegExp(palabraClave + \"[^:]*:\\\\s*(.*)\", \"i\");\n       const match = texto.match(regex);\n       \n       if (match && match[1]) {\n           // Limpiamos saltos de l\u00ednea y el punto final si la IA lo pone\n           return match[1].replace(/\\n/g, '').replace(/\\.$/, '').trim();\n       }\n       return \"No especificado\";\n   }\n\n  return {\n   \"Nombre\": extraerDato(\"Nombre completo\"),\n   \"Email\": extraerDato(\"Correo Electr\u00f3nico\"),\n   \"Telefono\": extraerDato(\"Tel\u00e9fono de contacto\"),\n   \"Ruta\": extraerDato(\"Ruta\"),\n   \"Empaque\": extraerDato(\"Tipo de empaque\"),\n   \"Peso\": extraerDato(\"Peso total aproximado\"), \n   \"Medidas\": extraerDato(\"Medidas de cada caja\"),\n   \"Carga\": extraerDato(\"Contenido detallado\"),\n   \"Origen\": extraerDato(\"Origen\"),\n   \"Destino\": extraerDato(\"Destino\")\n};\n} catch (error) {\n   return { \"Error_Detectado\": error.message };\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2336,
        112
      ],
      "id": "74685244-de21-4664-9e3a-429c47a72971",
      "name": "Extraer_Datos"
    },
    {
      "parameters": {
        "toolDescription": "Herramienta obligatoria para rastrear el estatus de un paquete. Extrae el n\u00famero de gu\u00eda que te dio el cliente y env\u00edalo en el par\u00e1metro TrackingNumber completamente limpio y sin espacios.",
        "method": "POST",
        "url": "URL_API_OCULTA",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"TrackingDetailsRequest\": {\n    \"SecretId\": \"SECRET_ID_OCULTO\",\n    \"TrackingNumber\": \"{{ $fromAI('TrackingNumber') }}\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequestTool",
      "typeVersion": 4.4,
      "position": [
        1008,
        368
      ],
      "id": "f402a447-daba-4154-b22b-b8b29ec5ef46",
      "name": "Rastrear_Paquete"
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $json.result.chat.id }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "ai"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $('AI Agent').item.json.output.replace('###FINALIZAR_Y_ENVIAR_EMAIL###','').replace(/###FOTO_[A-Z]+###/g, '').trim() }}"
            },
            {
              "fieldId": "contact_name",
              "fieldValue": "={{ $json.result.chat.first_name }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "text"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        2960,
        432
      ],
      "id": "39383aeb-1d9f-43e9-a1e3-1bade7e32657",
      "name": "Log_IA_Texto",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $('WhatsApp Trigger').item.json.message.from.id.toString() }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "ai"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $('AI Agent').item.json.output.replace(/###FOTO_[A-Z]+###/g, '').trim() }}"
            },
            {
              "fieldId": "contact_name",
              "fieldValue": "={{ $('Datos_Usuario').item.json.Nombre_cliente }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "image"
            },
            {
              "fieldId": "media_url",
              "fieldValue": "https://ibb.co/wFzH7kBx"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        3024,
        208
      ],
      "id": "b3803a7e-5320-43a4-bd80-6b0f19ca4ded",
      "name": "Log_IA_Foto",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $json.message.text.split(' ')[1] }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "agent"
            },
            {
              "fieldId": "sender_name",
              "fieldValue": "={{ $json.message.from.first_name }}"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $json.message.text.split(' ').slice(2).join(' ') }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "text"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        336,
        240
      ],
      "id": "51150452-5f65-4d95-91d5-9c89eb3b5790",
      "name": "Log_Agente_Humano",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $json.message.from.id.toString() }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "user"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $json.message.text }}"
            },
            {
              "fieldId": "contact_name",
              "fieldValue": "={{ $json.message.from.first_name }} {{ $json.message.from.last_name }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "text"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        -576,
        -96
      ],
      "id": "20d8d174-b84d-4e13-84a2-9f7298691053",
      "name": "Log_Entrante",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $('WhatsApp Trigger').item.json.message.from.id.toString() }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "ai"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $('AI Agent').item.json.output.replace('###FINALIZAR_Y_ENVIAR_EMAIL###','').replace('###MOSTRAR_FOTO_CAJAS###','').trim() }}"
            },
            {
              "fieldId": "contact_name",
              "fieldValue": "={{ $('Datos_Usuario').item.json.Nombre_cliente }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "text"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        3568,
        -160
      ],
      "id": "cb91d98d-f380-4420-be93-a093c43b1554",
      "name": "Log_IA_Texto1",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.asesor_id }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "id": "16cf4a52-d827-4efc-9a6b-7cadd41eeae1",
      "name": "\u00bfYa tiene asesor?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        624,
        736
      ]
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $json.asesor_id }}",
        "text": "=\ud83d\udea8 CONTINUACI\u00d3N DE TICKET - OMEGA CARGO\n\ud83d\udc64 Cliente: {{ $node[\"Get a row\"].json.Nombre }} {{ $node[\"Get a row\"].json.Apellido }}\n\ud83d\udcac Dice: {{ $node[\"WhatsApp Trigger\"].json.message.text }}\n\n\ud83d\udee0\ufe0f PARA RESPONDER:\nCopia el siguiente comando, escribe tu respuesta al final y env\u00edalo aqu\u00ed mismo:\n\n/responder {{ $node[\"Get a row\"].json.id_whatsapp }}"
      },
      "id": "f73c5ae8-c428-4abd-b189-93aa640d11bc",
      "name": "Notificar Asesor Actual",
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        880,
        592
      ],
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "tableId": "livechat_messages",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chat_id",
              "fieldValue": "={{ $node[\"Webhook Livechat\"].json.body.chat_id }}"
            },
            {
              "fieldId": "role",
              "fieldValue": "agent"
            },
            {
              "fieldId": "sender_name",
              "fieldValue": "={{ $('Webhook Livechat').item.json.body.sender_name }}"
            },
            {
              "fieldId": "content",
              "fieldValue": "={{ $node[\"Webhook Livechat\"].json.body.text }}"
            },
            {
              "fieldId": "message_type",
              "fieldValue": "text"
            },
            {
              "fieldId": "contact_name",
              "fieldValue": "={{ $('\u00bfA d\u00f3nde env\u00edo?').item.json.Nombre }} {{ $('\u00bfA d\u00f3nde env\u00edo?').item.json.Apellido }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1104,
        -864
      ],
      "id": "4e617f5e-096a-423d-9cdf-abc17e90718b",
      "name": "Log_Agente_Panel_Recuperado",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $node[\"Webhook Livechat\"].json.body.chat_id }}",
        "text": "={{ $node[\"Webhook Livechat\"].json.body.text }}"
      },
      "id": "f15fb807-83cf-42a3-b5b6-6f34437f75e2",
      "name": "Enviar a Cliente",
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        720,
        -864
      ],
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "getAll",
        "tableId": "Clientes",
        "limit": 1,
        "filters": {
          "conditions": [
            {
              "keyName": "id_whatsapp",
              "condition": "eq",
              "keyValue": "={{ $json.body.chat_id }}"
            }
          ]
        }
      },
      "id": "ad3e89ed-a831-4ce7-b97b-c773e24199e0",
      "name": "\u00bfA d\u00f3nde env\u00edo?",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        400,
        -880
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "livechat-send",
        "responseMode": "responseNode",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "id": "41bd656e-4a62-4ad3-b44e-ed49a31c6bc8",
      "name": "Webhook Livechat",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        48,
        -880
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "tableId": "asesores",
        "returnAll": true,
        "filters": {
          "conditions": [
            {
              "keyName": "estado",
              "condition": "eq",
              "keyValue": "disponible"
            }
          ]
        }
      },
      "id": "9bb1f3f4-5fc4-4683-b392-78116a98baf8",
      "name": "Buscar Asesor Disponible1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        992,
        848
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "asesores",
        "filters": {
          "conditions": [
            {
              "keyName": "telefono",
              "condition": "eq",
              "keyValue": "={{ $json.telefono }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chats_activos",
              "fieldValue": "={{ Number($json.chats_activos) + 1 }}"
            }
          ]
        }
      },
      "id": "bd49638e-8624-4c57-8d72-e981ec884528",
      "name": "Sumar +1 Carga1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1568,
        832
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('code1').item.json.telefono }}",
        "text": "=\ud83d\udea8 NUEVO TICKET DE SOPORTE - OMEGA CARGO\n\ud83d\udc64 Cliente: {{ $node[\"Get a row\"].json.Nombre }} {{ $node[\"Get a row\"].json.Apellido }}\n\ud83d\udcac Dice: {{ $node[\"WhatsApp Trigger\"].json.message.text }}\n\n\ud83d\udee0\ufe0f PARA RESPONDER:\nCopia el siguiente comando, escribe tu respuesta al final y env\u00edalo aqu\u00ed mismo:\n\n/responder {{ $node[\"Get a row\"].json.id_whatsapp }}"
      },
      "id": "e82564fc-aba1-4b4f-9646-b1f649a82058",
      "name": "Notificar Nuevo Asesor1",
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        2016,
        832
      ],
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// 1. Obtenemos a todos los asesores disponibles\nlet asesores = $input.all();\n\n// 2. FILTRO CLAVE: Descartar a los que ya llegaron a su l\u00edmite (3)\nasesores = asesores.filter(a => (a.json.chats_activos || 0) < (a.json.limite_chats || 3));\n\n// 3. Los ordenamos de menor a mayor para darle el chat al m\u00e1s desocupado\nasesores.sort((a, b) => (a.json.chats_activos || 0) - (b.json.chats_activos || 0));\n\n// 4. Devolvemos \u00daNICAMENTE al primero\nif (asesores.length > 0) {\n  return [asesores[0]];\n} else {\n  // Si TODOS est\u00e1n a tope (3/3), no devuelve nada y frena esta rama\n  return []; \n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1264,
        832
      ],
      "id": "644e60e7-2289-4bf1-b1b9-a1ea80ae9d40",
      "name": "code1"
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "asignaciones_chat",
        "filters": {
          "conditions": [
            {
              "keyName": "chat_id",
              "condition": "eq",
              "keyValue": "={{ $('WhatsApp Trigger').item.json.message.from.id.toString() }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "asesor_id",
              "fieldValue": "={{ $('code1').item.json.telefono }}"
            },
            {
              "fieldId": "estado",
              "fieldValue": "abierta"
            }
          ]
        }
      },
      "id": "5919ec5c-9edb-4b01-9ae3-043649594efd",
      "name": "Registrar Asignaci\u00f3n1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1792,
        832
      ],
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"success\": true,\n  \"message\": \"Mensaje recibido\"\n}",
        "options": {}
      },
      "id": "a4574f5f-12a7-4969-a78d-0bc83386035c",
      "name": "Responder a Vercel",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        368,
        -1040
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "tableId": "asignaciones_chat",
        "limit": 1,
        "filters": {
          "conditions": [
            {
              "keyName": "chat_id",
              "condition": "eq",
              "keyValue": "={{ $json.body.chat_id }}"
            },
            {
              "keyName": "estado",
              "condition": "eq",
              "keyValue": "abierta"
            }
          ]
        }
      },
      "id": "616552ed-78ce-4c78-a375-d3b0dca0bcc6",
      "name": "Buscar Asesor",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1200,
        1152
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "getAll",
        "tableId": "asesores",
        "limit": 1,
        "filters": {
          "conditions": [
            {
              "keyName": "telefono",
              "condition": "eq",
              "keyValue": "={{ $json.asesor_id }}"
            }
          ]
        }
      },
      "id": "c8dea74a-f9f9-4d2e-8a7d-d8f143f41301",
      "name": "Obtener Carga",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1424,
        1152
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "asesores",
        "filters": {
          "conditions": [
            {
              "keyName": "telefono",
              "condition": "eq",
              "keyValue": "={{ $json.telefono }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chats_activos",
              "fieldValue": "={{ Math.max(0, Number($json.chats_activos) - 1) }}"
            }
          ]
        }
      },
      "id": "adf050b1-a016-4a9c-9840-e436898f10d8",
      "name": "Restar -1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1648,
        1152
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "livechat-resolved",
        "options": {
          "allowedOrigins": "*"
        }
      },
      "id": "3ceada3c-77e0-42cb-9e9a-20b3000cdae8",
      "name": "Webhook Resolved1",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        976,
        1152
      ]
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "asignaciones_chat",
        "filters": {
          "conditions": [
            {
              "keyName": "chat_id",
              "condition": "eq",
              "keyValue": "={{ $('Webhook Resolved1').item.json.body.chat_id }}"
            }
          ]
        }
      },
      "id": "65aecdb1-e0d5-4613-a7d9-e77c623a121b",
      "name": "Cerrar Ticket1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        1904,
        1152
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "getAll",
        "tableId": "asignaciones_chat",
        "limit": 1,
        "matchType": "allFilters",
        "filters": {
          "conditions": [
            {
              "keyName": "chat_id",
              "condition": "eq",
              "keyValue": "={{ $node[\"Get a row\"].json.id_whatsapp }}"
            },
            {
              "keyName": "estado",
              "condition": "eq",
              "keyValue": "abierta"
            }
          ]
        }
      },
      "id": "ef4c879d-f63f-4688-a159-0069e8153238",
      "name": "Revisar Memoria1",
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        560,
        304
      ],
      "alwaysOutputData": true,
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "modo_humano",
              "leftValue": "={{ $json.modo_atencion }}",
              "rightValue": "humano",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Modo Humano?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        48,
        352
      ],
      "id": "0317a42a-e95b-40de-af87-7c4bd23dcf4f"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "condicion_segura_100",
              "leftValue": "={{ $json.id_whatsapp ? true : false }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Usuario Existe?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -336,
        288
      ],
      "id": "956d111e-afa4-4c87-b838-96fdcdfd8909"
    },
    {
      "parameters": {
        "operation": "update",
        "tableId": "Clientes",
        "filters": {
          "conditions": [
            {
              "keyName": "id_whatsapp",
              "condition": "eq",
              "keyValue": "={{ $('Webhook Resolved1').item.json.body.chat_id }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "modo_atencion",
              "fieldValue": "bot"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        2112,
        1152
      ],
      "id": "fb924bd3-c576-48ec-862c-ef0d29d65e60",
      "name": "Update a row2",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumber": "={{ $('Webhook Resolved1').item.json.body.chat_id }}",
        "text": "El asesor ha cerrado tu caso. Vuelvo a ser tu asistente virtual de Omega Cargo Express, \u00bfen qu\u00e9 m\u00e1s te puedo ayudar?"
      },
      "type": "n8n-nodes-base.whatsapp",
      "typeVersion": 1,
      "position": [
        2320,
        1152
      ],
      "id": "d770f87d-2928-4074-9083-d0546e5f45dc",
      "name": "Send a text message1",
      "credentials": {
        "whatsappCloudApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "c941cc09-f097-4c58-8aff-893eaa6d2631",
              "leftValue": "={{ $json.banned }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -160,
        144
      ],
      "id": "11e66d7b-0e97-4a28-a1f0-ca3e9fce5895",
      "name": "\u00bfUsuario Baneado?"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "56ee331d-fbae-4dc7-b283-9f23769af660",
              "leftValue": "={{ ($('WhatsApp Trigger').item.json.message.text || '').length }}",
              "rightValue": 1000,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        448,
        -304
      ],
      "id": "58b3da2f-c4db-4556-8de1-547688037d6e",
      "name": "Filtro Anti-Testamentos"
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "HERRAMIENTA DE USO OBLIGATORIO. Se activa CUANDO MENCIONAN ART\u00cdCULOS O PREGUNTAN REGLAS de env\u00edo. Tienes ESTRICTAMENTE PROHIBIDO aceptar los art\u00edculos sin pasarlos primero por esta herramienta. \n\nINSTRUCCIONES CR\u00cdTICAS PARA LA IA:\n1. Revisa detenidamente la columna 'articulos_restringidos'. All\u00ed hay l\u00edmites matem\u00e1ticos (ej: m\u00e1ximo 1 celular a Colombia, m\u00e1ximo 3 celulares a Venezuela, m\u00e1ximo 4 unidades de uso personal a Per\u00fa). Si el cliente supera esos l\u00edmites, DEBES NEGAR O CORREGIR EL ENV\u00cdO.\n2. Si el cliente pregunta qu\u00e9 se puede enviar pero NO ha dicho el pa\u00eds de destino, asigna el valor 'GLOBAL' al par\u00e1metro pais_destino para darle las reglas generales.\n3. ADVERTENCIAS OBLIGATORIAS: Si la cantidad de art\u00edculos es v\u00e1lida, pero existen condiciones en 'articulos_restringidos' o 'notas_especiales' (como la homologaci\u00f3n de CONATEL para Venezuela, informar sobre bater\u00edas de litio, o reglas de impuestos aduaneros), DEBES mencion\u00e1rselo obligatoriamente al cliente como una advertencia breve en tu respuesta antes de hacer la siguiente pregunta del flujo.",
        "operation": "getAll",
        "tableId": "regulaciones_envio",
        "filters": {
          "conditions": [
            {
              "keyName": "pais",
              "condition": "like",
              "keyValue": "={{ $fromAI('pais_destino') }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabaseTool",
      "typeVersion": 1,
      "position": [
        928,
        96
      ],
      "id": "be588ecb-1de4-4122-b782-42142201d510",
      "name": "articulos1",
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_MEXICO###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    },
                    "id": "283c9862-fb76-48bd-82de-1e9d103522e3"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "M\u00e9xico"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "225d306d-c2c8-43f3-81b8-0891435a2a10",
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_COLOMBIA###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Colombia"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "af6efbfa-d14d-4fc8-aca4-9b3177e2f386",
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_VENEZUELA###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Venezuela"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "667a9b21-bc16-4153-875c-80e65d14b3f4",
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_PERU###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Peru"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "84cea7f3-e114-48e4-9704-cc120258bd89",
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_NICARAGUA###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Nicaragua"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "a5b26eb1-ffd6-4eeb-9dc7-87391f429630",
                    "leftValue": "={{ $('AI Agent').item.json.output }}",
                    "rightValue": "###FOTO_GLOBAL###",
                    "operator": {
                      "type": "string",
                      "operation": "contains"
                    }
                  }
            

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

Whatsapp-Bot-Flow. Uses whatsappTrigger, agent, supabase, whatsapp. Event-driven trigger; 60 nodes.

Source: https://github.com/Diego-Roman/omega-ai-logistics-assistant/blob/25aadcb4c01b469a1fa07494a2f30a8dd996c497/flows/whatsapp-bot-flow.json — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

Automated Book Generation System. Uses googleSheetsTrigger, gmail, lmChatOpenAi, outputParserStructured. Event-driven trigger; 43 nodes.

Google Sheets Trigger, Gmail, OpenAI Chat +6
AI & RAG

This workflow provides a comprehensive weather reporting system with two main functionalities: a scheduled daily summary and an interactive AI agent for dynamic queries.

HTTP Request, Gmail, Slack +5
AI & RAG

This workflow is perfect for content creators, newsletter publishers, digital marketers, and virtual assistants who need a quick way to generate professional newsletters from trending news without man

Memory Buffer Window, HTTP Request Tool, Telegram Trigger +6
AI & RAG

Arvifund - Supabase (Fixed v2). Uses httpRequest, telegram, googleSheets, telegramTrigger. Event-driven trigger; 90 nodes.

HTTP Request, Telegram, Google Sheets +9
AI & RAG

Arvifund - Supabase (Fixed v4). Uses httpRequest, telegram, googleSheets, telegramTrigger. Event-driven trigger; 90 nodes.

HTTP Request, Telegram, Google Sheets +9