{
  "name": "Atendimento WhatsApp com IA (Evolution API)",
  "nodes": [
    {
      "id": "n_webhook",
      "name": "Webhook WhatsApp",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -220,
        300
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-evolution",
        "responseMode": "onReceived",
        "options": {}
      }
    },
    {
      "id": "n_config",
      "name": "CONFIG",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        0,
        300
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "evolutionUrl",
              "type": "string",
              "value": "https://SEU-EVOLUTION-AQUI"
            },
            {
              "id": "c2",
              "name": "instance",
              "type": "string",
              "value": "SUA-INSTANCIA"
            },
            {
              "id": "c3",
              "name": "sheetId",
              "type": "string",
              "value": "COLE-O-ID-DA-PLANILHA"
            },
            {
              "id": "c4",
              "name": "persona",
              "type": "string",
              "value": "Você é o atendente virtual da [NOME DA EMPRESA], que vende [PRODUTO/SERVIÇO] para [PÚBLICO]. Fale em português do Brasil, de forma simpática, breve e humana (no máximo 3 frases por resposta), como num WhatsApp. NUNCA invente preço, prazo ou informação que você não tem: se não souber, diga que vai confirmar com a equipe. Dados do negócio: horário [HORÁRIOS]; formas de pagamento [PAGAMENTOS]; prazo de entrega [PRAZO]; endereço [ENDEREÇO]. Seu objetivo é entender o que o cliente precisa, responder com clareza e conduzir para o próximo passo (orçamento, agendamento ou compra). Se o cliente pedir para falar com humano, ou for uma reclamação séria, responda que vai chamar a equipe."
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      }
    },
    {
      "id": "n_if",
      "name": "Filtro: mensagem válida?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        220,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "f1",
              "leftValue": "={{ $json.body.data.key.fromMe }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "false",
                "singleValue": true
              }
            },
            {
              "id": "f2",
              "leftValue": "={{ $json.body.data.key.remoteJid }}",
              "rightValue": "@g.us",
              "operator": {
                "type": "string",
                "operation": "notContains"
              }
            },
            {
              "id": "f3",
              "leftValue": "={{ $json.body.data.message.conversation || $json.body.data.message.extendedTextMessage?.text }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              }
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "n_extract",
      "name": "Extrair dados",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        440,
        220
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "e1",
              "name": "numero",
              "type": "string",
              "value": "={{ $json.body.data.key.remoteJid }}"
            },
            {
              "id": "e2",
              "name": "nome",
              "type": "string",
              "value": "={{ $json.body.data.pushName || 'cliente' }}"
            },
            {
              "id": "e3",
              "name": "mensagem",
              "type": "string",
              "value": "={{ $json.body.data.message.conversation || $json.body.data.message.extendedTextMessage?.text }}"
            }
          ]
        },
        "includeOtherFields": false,
        "options": {}
      }
    },
    {
      "id": "n_ia",
      "name": "IA - OpenAI",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        220
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "openAiApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ model: \"gpt-4o-mini\", messages: [{ role: \"system\", content: $('CONFIG').first().json.persona }, { role: \"user\", content: $json.mensagem } ], temperature: 0.5, max_tokens: 400 }) }}",
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "id": "",
          "name": "OpenAI (sua conta)"
        }
      }
    },
    {
      "id": "n_send",
      "name": "Responder no WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        880,
        220
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ $('CONFIG').first().json.evolutionUrl }}/message/sendText/{{ $('CONFIG').first().json.instance }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ number: $('Extrair dados').first().json.numero, text: $json.choices[0].message.content }) }}",
        "options": {}
      },
      "credentials": {
        "httpHeaderAuth": {
          "id": "",
          "name": "Evolution API (apikey)"
        }
      }
    },
    {
      "id": "n_sheet",
      "name": "Registrar na planilha",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        220
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "={{ $('CONFIG').first().json.sheetId }}",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Leads",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Data": "={{ $now.toFormat('dd/LL/yyyy HH:mm') }}",
            "Numero": "={{ $('Extrair dados').first().json.numero }}",
            "Nome": "={{ $('Extrair dados').first().json.nome }}",
            "Mensagem": "={{ $('Extrair dados').first().json.mensagem }}",
            "Resposta": "={{ $('IA - OpenAI').first().json.choices[0].message.content }}"
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "",
          "name": "Google Sheets (sua conta)"
        }
      }
    },
    {
      "id": "n_skip",
      "name": "Ignorar (grupo/eco)",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        440,
        540
      ],
      "parameters": {}
    },
    {
      "id": "ov",
      "name": "Nota ov",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -260,
        -260
      ],
      "parameters": {
        "content": "## 🤖 Atendente de WhatsApp com IA (Evolution API)\n\n**Fluxo:** o cliente manda msg → a Evolution joga aqui → a IA responde no seu tom → volta pelo WhatsApp → registra na planilha.\n\n### ✏️ Você edita só o nó **CONFIG**\nURL da Evolution, nome da instância, ID da planilha e a **persona** do seu negócio.\n\n### 🔑 3 credenciais\n1) OpenAI (nó IA)  2) Header Auth `apikey` (nó Responder)  3) Google Sheets (nó Registrar).\n\nGuia completo: diogocaspary.pages.dev/p/n8n",
        "height": 360,
        "width": 540,
        "color": 4
      }
    },
    {
      "id": "k1",
      "name": "Nota k1",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -300,
        120
      ],
      "parameters": {
        "content": "### 1. Webhook\nPonto de entrada. A Evolution manda cada mensagem recebida aqui.\nCopie a **Production URL** e cadastre no `webhook/set` da Evolution (evento **MESSAGES_UPSERT**).",
        "height": 200,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k2",
      "name": "Nota k2",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        120
      ],
      "parameters": {
        "content": "### 2. CONFIG ⚙️\n**O único nó que você edita.**\nevolutionUrl · instance · sheetId · persona.",
        "height": 200,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k3",
      "name": "Nota k3",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        220,
        120
      ],
      "parameters": {
        "content": "### 3. Filtro\nDescarta o **eco** (suas próprias msgs) e **grupos** (@g.us). Só passa texto de cliente.",
        "height": 200,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k4",
      "name": "Nota k4",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        480,
        120
      ],
      "parameters": {
        "content": "### 4. Extrair\nPega **número, nome e texto** da mensagem pros próximos nós.",
        "height": 200,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k5",
      "name": "Nota k5",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        740,
        60
      ],
      "parameters": {
        "content": "### 5. IA (OpenAI)\nEscreve a resposta usando a **persona** do CONFIG.\nCredencial: OpenAI. (Dá pra trocar por Claude.)",
        "height": 130,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k6",
      "name": "Nota k6",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        60
      ],
      "parameters": {
        "content": "### 6. Responder\nEnvia a resposta pelo WhatsApp (Evolution `sendText`).\nCredencial **Header Auth**: `apikey` = sua chave.",
        "height": 130,
        "width": 230,
        "color": 7
      }
    },
    {
      "id": "k7",
      "name": "Nota k7",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1000,
        380
      ],
      "parameters": {
        "content": "### 7. Registrar\nGrava a conversa na aba **Leads** da planilha.\nCredencial: Google Sheets (OAuth2).",
        "height": 140,
        "width": 230,
        "color": 7
      }
    }
  ],
  "connections": {
    "Webhook WhatsApp": {
      "main": [
        [
          {
            "node": "CONFIG",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "CONFIG": {
      "main": [
        [
          {
            "node": "Filtro: mensagem válida?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filtro: mensagem válida?": {
      "main": [
        [
          {
            "node": "Extrair dados",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Ignorar (grupo/eco)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrair dados": {
      "main": [
        [
          {
            "node": "IA - OpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IA - OpenAI": {
      "main": [
        [
          {
            "node": "Responder no WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Responder no WhatsApp": {
      "main": [
        [
          {
            "node": "Registrar na planilha",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templatecredsSetupCompleted": false
  },
  "tags": []
}