{
  "name": "Recepcionista de WhatsApp (ep01, Blackcircuit Labs)",
  "nodes": [
    {
      "parameters": {
        "content": "## Recepcionista de WhatsApp (ep01)\n1. Asigna credenciales: WhatsApp (Cloud API), OpenAI, Google Calendar y Gmail. Las notas de voz las transcribe OpenAI en «Transcribir nota de voz».\n2. Cambia el correo de Marta en «Avisar a Marta».\n3. Prueba con las tres conversaciones de la plantilla 3.\nDatos de ejemplo ficticios. Blackcircuit Labs.",
        "height": 260,
        "width": 380
      },
      "name": "Léeme",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -500,
        -300
      ]
    },
    {
      "parameters": {
        "updates": [
          "messages"
        ]
      },
      "name": "WhatsApp: mensaje recibido",
      "type": "n8n-nodes-base.whatsAppTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Ignora avisos de entregado/leído y otros eventos: solo pasan mensajes de clientas.\nreturn $input.all().filter(i => i.json.messages?.length);"
      },
      "name": "Solo mensajes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "dedupeValue": "={{ $json.messages[0].id }}",
        "options": {}
      },
      "name": "Sin repetidos",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        440,
        0
      ],
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v25.0/{{ $('WhatsApp: mensaje recibido').first().json.metadata.phone_number_id }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', status: 'read', message_id: $('WhatsApp: mensaje recibido').first().json.messages[0].id, typing_indicator: { type: 'text' } }) }}",
        "options": {}
      },
      "name": "Escribiendo…",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        660,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "resource": "table",
        "operation": "create",
        "tableName": "buffer_recepcionista",
        "columns": {
          "column": [
            {
              "name": "cliente",
              "type": "string"
            },
            {
              "name": "texto",
              "type": "string"
            },
            {
              "name": "ts",
              "type": "number"
            },
            {
              "name": "msg_id",
              "type": "string"
            }
          ]
        },
        "options": {
          "createIfNotExists": true
        }
      },
      "name": "Preparar tabla",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        880,
        0
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].type }}",
              "rightValue": "audio",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ]
        }
      },
      "name": "¿Es nota de voz?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1100,
        0
      ]
    },
    {
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].audio.id }}"
      },
      "name": "Obtener audio",
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        1320,
        -200
      ]
    },
    {
      "parameters": {
        "url": "={{ $json.url }}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "name": "Descargar audio",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        1540,
        -200
      ]
    },
    {
      "parameters": {
        "resource": "audio",
        "operation": "transcribe",
        "binaryPropertyName": "data",
        "options": {
          "language": "es"
        }
      },
      "name": "Transcribir nota de voz",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.3,
      "position": [
        1760,
        -200
      ],
      "retryOnFail": true,
      "maxTries": 5,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "name": "texto",
              "type": "string",
              "value": "={{ $json.text }}"
            },
            {
              "name": "telefono",
              "type": "string",
              "value": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].from || $('WhatsApp: mensaje recibido').item.json.messages[0].from_user_id }}"
            },
            {
              "name": "ts",
              "type": "number",
              "value": "={{ Number($('WhatsApp: mensaje recibido').item.json.messages[0].timestamp) }}"
            },
            {
              "name": "msg_id",
              "type": "string",
              "value": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].id }}"
            }
          ]
        }
      },
      "name": "Texto de la nota",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1980,
        -200
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "name": "texto",
              "type": "string",
              "value": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].text.body }}"
            },
            {
              "name": "telefono",
              "type": "string",
              "value": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].from || $('WhatsApp: mensaje recibido').item.json.messages[0].from_user_id }}"
            },
            {
              "name": "ts",
              "type": "number",
              "value": "={{ Number($('WhatsApp: mensaje recibido').item.json.messages[0].timestamp) }}"
            },
            {
              "name": "msg_id",
              "type": "string",
              "value": "={{ $('WhatsApp: mensaje recibido').item.json.messages[0].id }}"
            }
          ]
        }
      },
      "name": "Texto del mensaje",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1980,
        0
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "buffer_recepcionista"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "cliente": "={{ $json.telefono }}",
            "texto": "={{ $json.texto }}",
            "ts": "={{ $json.ts }}",
            "msg_id": "={{ $json.msg_id }}"
          },
          "schema": [
            {
              "id": "cliente",
              "displayName": "cliente",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "texto",
              "displayName": "texto",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "ts",
              "displayName": "ts",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true
            },
            {
              "id": "msg_id",
              "displayName": "msg_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        }
      },
      "name": "Guardar en buffer",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        2200,
        0
      ]
    },
    {
      "parameters": {
        "resume": "timeInterval",
        "amount": 8,
        "unit": "seconds"
      },
      "name": "Esperar unos segundos",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        2420,
        0
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "buffer_recepcionista"
        },
        "returnAll": true,
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "cliente",
              "condition": "eq",
              "keyValue": "={{ $json.telefono ?? $json.cliente }}"
            }
          ]
        }
      },
      "name": "Leer buffer",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        2640,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Buffer: si llegó otro mensaje de la misma clienta mientras esperábamos, ese se encarga y este termina.\n// Si este es el último, junta todos los pendientes en orden y sigue una sola vez.\nconst mio = $('Guardar en buffer').first().json;\nconst filas = $input.all().map(i => i.json).filter(r => r.id);\nfilas.sort((a, b) => (a.ts - b.ts) || (a.id - b.id));\n// Meta a veces entrega el mismo mensaje dos veces: cada ID de mensaje cuenta una sola vez.\nconst vistos = new Set();\nconst unicas = filas.filter(r => !r.msg_id || (!vistos.has(r.msg_id) && vistos.add(r.msg_id)));\nreturn [{ json: {\n  ultimo: filas.every(r => r.id <= mio.id),\n  telefono: mio.cliente,\n  texto: unicas.map(r => r.texto).join('\\n'),\n  hasta_id: Math.max(...filas.map(r => r.id)),\n} }];"
      },
      "name": "Juntar mensajes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2860,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "combinator": "and",
          "conditions": [
            {
              "leftValue": "={{ $json.ultimo }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ]
        }
      },
      "name": "¿Es el último mensaje?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        3080,
        0
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "deleteRows",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "buffer_recepcionista"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "cliente",
              "condition": "eq",
              "keyValue": "={{ $json.telefono ?? $json.cliente }}"
            },
            {
              "keyName": "id",
              "condition": "lte",
              "keyValue": "={{ $json.hasta_id }}"
            }
          ]
        }
      },
      "name": "Vaciar buffer",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        3300,
        -260
      ]
    },
    {
      "parameters": {
        "inputText": "={{ $json.texto }}",
        "categories": {
          "categories": [
            {
              "category": "pasar_a_marta",
              "description": "Queja, cliente molesta, pregunta de salud (alergias, embarazo, reacción a un tinte), pedido de descuento o reembolso, o pide hablar con una persona."
            },
            {
              "category": "atender",
              "description": "Precios, horarios, dirección, servicios, agendar, cambiar o cancelar una cita, saludos."
            }
          ]
        },
        "options": {
          "fallback": "other"
        }
      },
      "name": "Guardrail: ¿pasar a Marta?",
      "type": "@n8n/n8n-nodes-langchain.textClassifier",
      "typeVersion": 1.1,
      "position": [
        3300,
        0
      ],
      "retryOnFail": true,
      "maxTries": 5,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-5-mini"
        },
        "options": {}
      },
      "name": "Modelo (clasificador)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        3300,
        240
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v25.0/{{ $('WhatsApp: mensaje recibido').first().json.metadata.phone_number_id }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify(Object.assign({ messaging_product: 'whatsapp', recipient_type: 'individual', type: 'text', text: { body: 'Te paso con Marta para que lo vea ella. Te escribe en cuanto pueda.' } }, /^[0-9]+$/.test($('Juntar mensajes').first().json.telefono) ? { to: $('Juntar mensajes').first().json.telefono } : { recipient: $('Juntar mensajes').first().json.telefono })) }}",
        "options": {}
      },
      "name": "Responder: te paso con Marta",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        3640,
        -160
      ]
    },
    {
      "parameters": {
        "sendTo": "marta@ejemplo.com",
        "subject": "Lía te pasó una conversación",
        "emailType": "text",
        "message": "=Número: {{ $('Juntar mensajes').first().json.telefono }}\nMensaje: {{ $('Juntar mensajes').first().json.texto }}\n\nContéstale tú por WhatsApp."
      },
      "name": "Avisar a Marta",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2,
      "position": [
        3880,
        -160
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.texto }}",
        "options": {
          "systemMessage": "=Hoy es {{ $now.setZone('America/Bogota').setLocale('es').toFormat(\"cccc d 'de' LLLL 'de' yyyy, h:mm a\") }} (hora de Colombia). Usa esta fecha para entender \"hoy\", \"mañana\" o \"el jueves\".\n\nEres Lía, la asistente virtual de Peluquería Marta, en Barrio Centro.\nAtiendes el WhatsApp del negocio: contestas mensajes y notas de voz (te llegan transcritas).\n\nCÓMO HABLAS\n- Saludas así la primera vez: \"Hola, soy Lía, la asistente virtual de Peluquería Marta. ¿En qué te ayudo?\"\n- Tuteas en español neutro (\"¿quieres?\", \"recuerda\"), nunca de vos (\"¿querés?\", \"recordá\"). Frases cortas y amables. Un emoji como máximo por mensaje.\n- Si la clienta escribe de usted, le contestas de usted.\n\nQUÉ SABES\n- Solo lo que está en LISTA DE PRECIOS Y HORARIOS, abajo. Si te preguntan algo que no está ahí,\n  dices que no lo sabes y que Marta le confirma. Nunca inventes un precio, un horario ni un servicio.\n- Los precios pueden cambiar según el largo del cabello: si la lista dice \"desde\", lo dices.\n\nQUÉ HACES\n- Respondes precios, horarios, dirección y servicios.\n- Agendas citas con la herramienta de calendario: primero revisas qué horas hay libres, ofreces\n  dos opciones, y creas la cita solo cuando la clienta elige una. Confirmas día, hora y servicio.\n- Si la clienta quiere cancelar o cambiar una cita, la ayudas igual.\n\nCUÁNDO PASAS LA CONVERSACIÓN A MARTA (no la sigues tú)\n- Una queja o una clienta molesta.\n- Una pregunta de salud: alergias, embarazo, reacciones a un tinte.\n- Un pedido de descuento, reembolso o algo fuera de la lista.\n- Cuando la clienta pide hablar con una persona.\nEn esos casos respondes: \"Te paso con Marta para que lo vea ella. Te escribe en cuanto pueda.\"\ny no ofreces soluciones.\n\nLO QUE NUNCA HACES\n- Pedir o repetir números de tarjeta, de cuenta o documentos de identidad.\n- Prometer resultados (\"te va a quedar perfecto\") ni hablar mal de otros negocios.\n- Escribirle primero a alguien: solo respondes a quien te escribe.\n- Ofrecer o prometer algo que no esté en LISTA DE PRECIOS Y HORARIOS, como avisos o \"te escribo después\": tú no puedes mandar mensajes más tarde. Si te piden un recordatorio y la lista no dice que hay, dices que no puedes enviarlo y que la cita queda en la agenda del negocio.\n\nLISTA DE PRECIOS Y HORARIOS\nNEGOCIO: Peluquería Marta · Calle Ejemplo 123, Barrio Centro · WhatsApp del negocio\n\nHORARIO\n- Lunes a viernes: 9:00 a. m. a 7:00 p. m.\n- Sábados: 9:00 a. m. a 2:00 p. m.\n- Domingos y festivos: cerrado\n- Última cita del día: una hora antes de cerrar\n\nSERVICIOS Y PRECIOS (duración aproximada)\n- Corte de dama: $25 (45 min)\n- Corte de caballero: $15 (30 min)\n- Corte infantil, hasta 10 años: $12 (30 min)\n- Tinte completo: desde $80, según el largo (2 h)\n- Retoque de raíz: $45 (1 h 30 min)\n- Mechas o rayitos: desde $95, según el largo (2 h 30 min)\n- Peinado: $20 (40 min)\n- Tratamiento de hidratación: $30 (45 min)\n\nPAGO\n- Efectivo, tarjeta y transferencia. No se toman pagos por WhatsApp.\n\nREGLAS DE CITAS\n- Para tintes y mechas se pide llegar con el cabello sin lavar ese día.\n- Si alguien llega más de 15 minutos tarde, se reagenda.\n- Para cancelar, avisar con al menos 3 horas.\n- Recordatorio: la tarde anterior a la cita llega un recordatorio por WhatsApp. (Borra esta línea si no activas el flujo de recordatorios.)\n\nÚLTIMA ACTUALIZACIÓN: fecha\n\nRECUERDA SIEMPRE: escribe de tú, en español latino neutro (\"confirma\", \"recuerda\", \"llegas\", \"quieres\"), nunca de vos (\"confirmá\", \"recordá\", \"llegás\", \"querés\"), aunque la clienta escriba de vos."
        }
      },
      "name": "Recepcionista",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        3640,
        120
      ],
      "retryOnFail": true,
      "maxTries": 5,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "gpt-5-mini"
        },
        "options": {}
      },
      "name": "Modelo (recepcionista)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        3480,
        360
      ]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $json.telefono }}",
        "contextWindowLength": 12
      },
      "name": "Memoria por clienta",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1,
      "position": [
        3640,
        360
      ]
    },
    {
      "parameters": {
        "operation": "getAll",
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "tu-calendario@gmail.com"
        },
        "returnAll": true,
        "timeMin": "={{ $fromAI('desde', 'Inicio del rango a revisar, ISO 8601') }}",
        "timeMax": "={{ $fromAI('hasta', 'Fin del rango a revisar, ISO 8601') }}",
        "descriptionType": "manual",
        "toolDescription": "Lista las citas ya ocupadas entre dos fechas para encontrar horas libres."
      },
      "name": "Calendario: horas ocupadas",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        3800,
        360
      ]
    },
    {
      "parameters": {
        "calendar": {
          "__rl": true,
          "mode": "id",
          "value": "tu-calendario@gmail.com"
        },
        "start": "={{ $fromAI('inicio', 'Inicio de la cita, ISO 8601') }}",
        "end": "={{ $fromAI('fin', 'Fin de la cita según la duración del servicio, ISO 8601') }}",
        "additionalFields": {
          "summary": "={{ $fromAI('titulo', 'Servicio y nombre de la clienta, por ejemplo: Corte de dama - Ana') }}",
          "description": "=WhatsApp: {{ $json.telefono }}\nNombre: {{ $fromAI('nombre', 'Nombre de la clienta') }}\nServicio: {{ $fromAI('servicio', 'Servicio en minúsculas, por ejemplo: corte de dama') }}"
        },
        "descriptionType": "manual",
        "toolDescription": "Crea la cita solo después de que la clienta eligió la hora."
      },
      "name": "Calendario: crear cita",
      "type": "n8n-nodes-base.googleCalendarTool",
      "typeVersion": 1.3,
      "position": [
        3960,
        360
      ]
    },
    {
      "parameters": {
        "jsCode": "// Respuestas largas: se mandan en máximo 3 mensajes, cortando entre párrafos (o entre frases si es un solo párrafo).\n// `pausa` = segundos de \"escribiendo…\" antes de cada parte, según su largo, para que se sienta escrito a mano.\nconst MAX_PARTES = 3, LARGO = 320;\n// Tuteo: algunos modelos se pasan al voseo aunque las instrucciones lo prohíban. Se corrigen las formas más comunes.\nconst VOS = { querés: 'quieres', podés: 'puedes', tenés: 'tienes', preferís: 'prefieres', sabés: 'sabes', necesitás: 'necesitas',\n  llegás: 'llegas', venís: 'vienes', recordá: 'recuerda', confirmá: 'confirma', avisá: 'avisa', escribí: 'escribe', mirá: 'mira',\n  decime: 'dime', contame: 'cuéntame', fijate: 'fíjate', elegí: 'elige', mandá: 'manda', pasá: 'pasa', vení: 'ven', hacé: 'haz' };\nconst tuteo = (t) => t.replace(/\\p{L}+/gu, (w) => {  // palabras completas, con tildes\n  const r = VOS[w.toLowerCase()];\n  return !r ? w : w[0] === w[0].toUpperCase() ? r[0].toUpperCase() + r.slice(1) : r;\n});\nconst texto = tuteo(($input.first().json.output || '').trim());\nif (texto.length <= LARGO) return [{ json: { parte: texto, pausa: 1 } }];\nlet bloques = texto.split(/\\n\\s*\\n/).map(b => b.trim()).filter(Boolean), sep = '\\n\\n';\n// Un solo párrafo: corta entre frases (después de . ! ? y antes de mayúscula), sin romper \"$80.000\" ni \"a. m.\".\nif (bloques.length < 2) { bloques = texto.split(/(?<=[.!?…])\\s+(?=[¿¡\"«A-ZÁÉÍÓÚÑ0-9])/).map(b => b.trim()).filter(Boolean); sep = ' '; }\nconst n = Math.max(1, Math.min(MAX_PARTES, Math.ceil(texto.length / LARGO), bloques.length));\nconst meta = texto.length / n, partes = [];\nlet actual = '';\nfor (const b of bloques) {\n  if (actual && actual.length + b.length > meta && partes.length < n - 1) { partes.push(actual); actual = b; }\n  else actual = actual ? actual + sep + b : b;\n}\nif (actual) partes.push(actual);\nreturn partes.map((parte, i) => ({ json: { parte, pausa: i === 0 ? 1 : Math.min(5, Math.max(1.5, parte.length / 30)) } }));"
      },
      "name": "Dividir respuesta",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4000,
        120
      ]
    },
    {
      "parameters": {
        "batchSize": 1,
        "options": {}
      },
      "name": "Una parte a la vez",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        4220,
        120
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v25.0/{{ $('WhatsApp: mensaje recibido').first().json.metadata.phone_number_id }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ messaging_product: 'whatsapp', status: 'read', message_id: $('WhatsApp: mensaje recibido').first().json.messages[0].id, typing_indicator: { type: 'text' } }) }}",
        "options": {}
      },
      "name": "Escribiendo (respuesta)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        4440,
        300
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "resume": "timeInterval",
        "amount": "={{ $('Una parte a la vez').first().json.pausa }}",
        "unit": "seconds"
      },
      "name": "Pausa de escritura",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        4660,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://graph.facebook.com/v25.0/{{ $('WhatsApp: mensaje recibido').first().json.metadata.phone_number_id }}/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify(Object.assign({ messaging_product: 'whatsapp', recipient_type: 'individual', type: 'text', text: { body: $('Una parte a la vez').first().json.parte } }, /^[0-9]+$/.test($('Juntar mensajes').first().json.telefono) ? { to: $('Juntar mensajes').first().json.telefono } : { recipient: $('Juntar mensajes').first().json.telefono })) }}",
        "options": {}
      },
      "name": "Enviar respuesta",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [
        4880,
        300
      ]
    }
  ],
  "connections": {
    "WhatsApp: mensaje recibido": {
      "main": [
        [
          {
            "node": "Solo mensajes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Solo mensajes": {
      "main": [
        [
          {
            "node": "Sin repetidos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sin repetidos": {
      "main": [
        [
          {
            "node": "Escribiendo…",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Escribiendo…",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Escribiendo…": {
      "main": [
        [
          {
            "node": "Preparar tabla",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Preparar tabla": {
      "main": [
        [
          {
            "node": "¿Es nota de voz?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Es nota de voz?": {
      "main": [
        [
          {
            "node": "Obtener audio",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Texto del mensaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Obtener audio": {
      "main": [
        [
          {
            "node": "Descargar audio",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Descargar audio": {
      "main": [
        [
          {
            "node": "Transcribir nota de voz",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transcribir nota de voz": {
      "main": [
        [
          {
            "node": "Texto de la nota",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Texto de la nota": {
      "main": [
        [
          {
            "node": "Guardar en buffer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Texto del mensaje": {
      "main": [
        [
          {
            "node": "Guardar en buffer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Guardar en buffer": {
      "main": [
        [
          {
            "node": "Esperar unos segundos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Esperar unos segundos": {
      "main": [
        [
          {
            "node": "Leer buffer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Leer buffer": {
      "main": [
        [
          {
            "node": "Juntar mensajes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Juntar mensajes": {
      "main": [
        [
          {
            "node": "¿Es el último mensaje?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "¿Es el último mensaje?": {
      "main": [
        [
          {
            "node": "Vaciar buffer",
            "type": "main",
            "index": 0
          },
          {
            "node": "Guardrail: ¿pasar a Marta?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Guardrail: ¿pasar a Marta?": {
      "main": [
        [
          {
            "node": "Responder: te paso con Marta",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Recepcionista",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Recepcionista",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Responder: te paso con Marta": {
      "main": [
        [
          {
            "node": "Avisar a Marta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Recepcionista": {
      "main": [
        [
          {
            "node": "Dividir respuesta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dividir respuesta": {
      "main": [
        [
          {
            "node": "Una parte a la vez",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Una parte a la vez": {
      "main": [
        [],
        [
          {
            "node": "Escribiendo (respuesta)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Escribiendo (respuesta)": {
      "main": [
        [
          {
            "node": "Pausa de escritura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pausa de escritura": {
      "main": [
        [
          {
            "node": "Enviar respuesta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar respuesta": {
      "main": [
        [
          {
            "node": "Una parte a la vez",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Modelo (clasificador)": {
      "ai_languageModel": [
        [
          {
            "node": "Guardrail: ¿pasar a Marta?",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Modelo (recepcionista)": {
      "ai_languageModel": [
        [
          {
            "node": "Recepcionista",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Memoria por clienta": {
      "ai_memory": [
        [
          {
            "node": "Recepcionista",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Calendario: horas ocupadas": {
      "ai_tool": [
        [
          {
            "node": "Recepcionista",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Calendario: crear cita": {
      "ai_tool": [
        [
          {
            "node": "Recepcionista",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false,
    "generatedBy": "tools/material_flujo_recepcionista.py"
  }
}
