{
  "name": "Chatbot de Respuestas Automáticas por WhatsApp con IA",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-chatbot-webhook",
        "options": {}
      },
      "id": "c9d0e1f2-0009-4a01-b001-ef1234567001",
      "name": "Webhook - Mensaje WhatsApp",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "functionCode": "const entry = items[0].json.entry;\nif (!entry || !entry[0] || !entry[0].changes || !entry[0].changes[0].value.messages) {\n  return [];\n}\n\nconst messageData = entry[0].changes[0].value.messages[0];\nconst contactData = entry[0].changes[0].value.contacts[0];\n\nreturn [{\n  json: {\n    phoneNumber: messageData.from,\n    messageText: messageData.text ? messageData.text.body : '',\n    contactName: contactData.profile.name,\n    messageId: messageData.id,\n    timestamp: messageData.timestamp\n  }\n}];"
      },
      "id": "c9d0e1f2-0009-4a02-b002-ef1234567002",
      "name": "Function - Extraer Datos Mensaje",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [500, 300]
    },
    {
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": ""
        },
        "sheetName": {
          "__rl": true,
          "mode": "byName",
          "value": "Historial Conversaciones"
        },
        "filters": {
          "column": "telefono",
          "value": "={{ $json.phoneNumber }}"
        },
        "options": {}
      },
      "id": "c9d0e1f2-0009-4a03-b003-ef1234567003",
      "name": "Google Sheets - Buscar Historial",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4,
      "position": [750, 300],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "resource": "chat",
        "operation": "message",
        "model": "gpt-3.5-turbo",
        "messages": {
          "values": [
            {
              "role": "system",
              "content": "Eres un asistente virtual amable y profesional de un negocio ecuatoriano. Responde en español de forma concisa y útil. Información del negocio:\n- Horario: Lunes a viernes 8:00-18:00, Sábado 9:00-13:00\n- Ubicación: [DIRECCIÓN DEL NEGOCIO]\n- Teléfono: [TELÉFONO]\n- Productos/Servicios: [DESCRIBIR PRODUCTOS O SERVICIOS]\n- Formas de pago: Efectivo, transferencia bancaria, tarjeta de crédito\n- Envíos: Todo Ecuador, 24-48h en Quito y Guayaquil\n\nSi el cliente tiene un reclamo grave, dice 'gerente', 'problema grave' o está muy insatisfecho, responde amablemente y di que un agente humano lo contactará pronto. Marca estas conversaciones para escalamiento."
            },
            {
              "content": "={{ $json.messageText }}"
            }
          ]
        },
        "options": {
          "temperature": 0.7,
          "maxTokens": 300
        }
      },
      "id": "c9d0e1f2-0009-4a04-b004-ef1234567004",
      "name": "OpenAI - Generar Respuesta",
      "type": "n8n-nodes-base.openAi",
      "typeVersion": 1,
      "position": [1000, 300],
      "credentials": {
        "openAiApi": {
          "id": "",
          "name": "OpenAI account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.messageText.toLowerCase() }}",
              "operation": "contains",
              "value2": "reclamo"
            }
          ]
        }
      },
      "id": "c9d0e1f2-0009-4a05-b005-ef1234567005",
      "name": "IF - Requiere Humano",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [1250, 300]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v17.0/FROM_PHONE_NUMBER_ID/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"messaging_product\": \"whatsapp\",\n  \"to\": \"{{ $json.phoneNumber }}\",\n  \"type\": \"text\",\n  \"text\": {\n    \"body\": \"{{ $json.message.content }}\"\n  }\n}",
        "options": {}
      },
      "id": "c9d0e1f2-0009-4a06-b006-ef1234567006",
      "name": "HTTP Request - Responder WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4,
      "position": [1500, 200]
    },
    {
      "parameters": {
        "chatId": "",
        "text": "=🚨 *ESCALACIÓN - Cliente requiere agente humano*\n\n📱 Teléfono: {{ $json.phoneNumber }}\n👤 Nombre: {{ $json.contactName }}\n💬 Mensaje: {{ $json.messageText }}\n\n_Responder lo antes posible._",
        "additionalFields": {
          "parse_mode": "Markdown"
        }
      },
      "id": "c9d0e1f2-0009-4a07-b007-ef1234567007",
      "name": "Telegram - Escalar a Agente",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1,
      "position": [1500, 400],
      "credentials": {
        "telegramApi": {
          "id": "",
          "name": "Telegram account"
        }
      }
    }
  ],
  "connections": {
    "Webhook - Mensaje WhatsApp": {
      "main": [
        [
          {
            "node": "Function - Extraer Datos Mensaje",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function - Extraer Datos Mensaje": {
      "main": [
        [
          {
            "node": "Google Sheets - Buscar Historial",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Sheets - Buscar Historial": {
      "main": [
        [
          {
            "node": "OpenAI - Generar Respuesta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI - Generar Respuesta": {
      "main": [
        [
          {
            "node": "IF - Requiere Humano",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF - Requiere Humano": {
      "main": [
        [
          {
            "node": "Telegram - Escalar a Agente",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "HTTP Request - Responder WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [
    {
      "name": "customer-service"
    },
    {
      "name": "chatbot"
    },
    {
      "name": "whatsapp"
    },
    {
      "name": "ia"
    }
  ]
}
