{
  "name": "MazyOS · WhatsApp Debounce Redis + Whisper + Evolution v2 + Chatwoot",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-evolution-entrada",
        "options": {}
      },
      "id": "node-webhook-evo",
      "name": "Webhook Evolution v2",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [220, 320],
      "webhookId": "whatsapp-evolution-entrada"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-not-from-me",
              "leftValue": "={{ $json.body?.data?.key?.fromMe }}",
              "rightValue": false,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            },
            {
              "id": "cond-not-group",
              "leftValue": "={{ $json.body?.data?.key?.remoteJid ?? '' }}",
              "rightValue": "@g.us",
              "operator": {
                "type": "string",
                "operation": "notEndsWith"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-filtro-entrada",
      "name": "Filtrar fromMe e Grupos",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [440, 320]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.body?.data?.messageType }}",
                    "rightValue": "audioMessage",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "audio"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict"
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.body?.data?.messageType }}",
                    "rightValue": "audioMessage",
                    "operator": {
                      "type": "string",
                      "operation": "notEquals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "texto"
            }
          ]
        },
        "options": {}
      },
      "id": "node-switch-tipo",
      "name": "Switch Audio vs Texto",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [660, 320]
    },
    {
      "parameters": {
        "operation": "toBinary",
        "sourceProperty": "body.data.message.base64",
        "options": {
          "fileName": "audio-whatsapp.ogg",
          "mimeType": "audio/ogg"
        }
      },
      "id": "node-base64-binary",
      "name": "Converter Base64 para OGG",
      "type": "n8n-nodes-base.convertToFile",
      "typeVersion": 1.1,
      "position": [880, 180]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.groq.com/openai/v1/audio/transcriptions",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer ${GROQ_API_KEY}"
            }
          ]
        },
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "parameterType": "formBinaryData",
              "name": "file",
              "inputDataFieldName": "data"
            },
            {
              "name": "model",
              "value": "whisper-large-v3-turbo"
            },
            {
              "name": "language",
              "value": "pt"
            }
          ]
        },
        "options": {}
      },
      "id": "node-groq-whisper",
      "name": "Transcrever Audio Groq Whisper",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1100, 180]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "assign-jid",
              "name": "remoteJid",
              "value": "={{ $('Webhook Evolution v2').item.json.body.data.key.remoteJid }}",
              "type": "string"
            },
            {
              "id": "assign-nome",
              "name": "pushName",
              "value": "={{ $('Webhook Evolution v2').item.json.body.data.pushName ?? 'Cliente' }}",
              "type": "string"
            },
            {
              "id": "assign-msg",
              "name": "mensagemNormalizada",
              "value": "={{ $json.text ?? $json.body?.data?.message?.conversation ?? $json.body?.data?.message?.extendedTextMessage?.text ?? '' }}",
              "type": "string"
            },
            {
              "id": "assign-exec",
              "name": "execId",
              "value": "={{ $execution.id }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "node-normalizar-payload",
      "name": "Normalizar Mensagem",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [1320, 320]
    },
    {
      "parameters": {
        "operation": "push",
        "list": "={{ 'debounce:fila:' + $json.remoteJid }}",
        "messageData": "={{ $json.mensagemNormalizada }}",
        "tail": true
      },
      "id": "node-redis-rpush",
      "name": "Redis RPUSH Fila",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [1540, 320],
      "credentials": {
        "redis": {
          "id": "${N8N_REDIS_CREDENTIAL_ID}",
          "name": "Redis VPS"
        }
      }
    },
    {
      "parameters": {
        "operation": "set",
        "key": "={{ 'debounce:ultimo:' + $('Normalizar Mensagem').item.json.remoteJid }}",
        "value": "={{ $('Normalizar Mensagem').item.json.execId }}",
        "expire": true,
        "ttl": 120
      },
      "id": "node-redis-set-exec",
      "name": "Redis Marcar Ultima Execucao",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [1740, 320],
      "credentials": {
        "redis": {
          "id": "${N8N_REDIS_CREDENTIAL_ID}",
          "name": "Redis VPS"
        }
      }
    },
    {
      "parameters": {
        "amount": 12,
        "unit": "seconds"
      },
      "id": "node-wait-12s",
      "name": "Wait 12s Debounce",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [1940, 320],
      "webhookId": "wait-debounce-12s"
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "ultimoExecId",
        "key": "={{ 'debounce:ultimo:' + $('Normalizar Mensagem').item.json.remoteJid }}",
        "options": {}
      },
      "id": "node-redis-get-exec",
      "name": "Redis Ler Ultima Execucao",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [2140, 320],
      "credentials": {
        "redis": {
          "id": "${N8N_REDIS_CREDENTIAL_ID}",
          "name": "Redis VPS"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-exec-venceu",
              "leftValue": "={{ $json.ultimoExecId }}",
              "rightValue": "={{ $('Normalizar Mensagem').item.json.execId }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "node-if-ultima-exec",
      "name": "Ultima Mensagem da Rajada?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [2340, 320]
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "mensagens",
        "key": "={{ 'debounce:fila:' + $('Normalizar Mensagem').item.json.remoteJid }}",
        "options": {}
      },
      "id": "node-redis-lrange",
      "name": "Redis Ler Fila Completa",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [2560, 220],
      "credentials": {
        "redis": {
          "id": "${N8N_REDIS_CREDENTIAL_ID}",
          "name": "Redis VPS"
        }
      }
    },
    {
      "parameters": {
        "operation": "delete",
        "key": "={{ 'debounce:fila:' + $('Normalizar Mensagem').item.json.remoteJid }}"
      },
      "id": "node-redis-del",
      "name": "Redis Limpar Fila",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [2760, 220],
      "credentials": {
        "redis": {
          "id": "${N8N_REDIS_CREDENTIAL_ID}",
          "name": "Redis VPS"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ Array.isArray($('Redis Ler Fila Completa').item.json.mensagens) ? $('Redis Ler Fila Completa').item.json.mensagens.join('\\n') : $('Normalizar Mensagem').item.json.mensagemNormalizada }}",
        "options": {
          "systemMessage": "Você é a atendente da clínica no WhatsApp. Responda em português do Brasil, de forma curta e cordial, em um único bloco de texto sem quebrar em vários balões. Se o cliente pedir orçamento complexo ou falar com humano, sinalize transbordo."
        }
      },
      "id": "node-ai-agent",
      "name": "AI Agent Atendimento",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [2980, 220]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=${EVOLUTION_BASE_URL}/message/sendText/${EVOLUTION_INSTANCE}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "${EVOLUTION_API_KEY}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"number\": \"{{ $('Normalizar Mensagem').item.json.remoteJid }}\",\n  \"text\": \"{{ $json.output }}\",\n  \"delay\": 2500\n}",
        "options": {}
      },
      "id": "node-evo-send",
      "name": "Enviar Resposta Evolution v2",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [3220, 220]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=${CHATWOOT_BASE_URL}/api/v1/accounts/${CHATWOOT_ACCOUNT_ID}/conversations/${CHATWOOT_CONVERSATION_ID}/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "${CHATWOOT_API_TOKEN}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"[IA respondeu] {{ $('AI Agent Atendimento').item.json.output }}\",\n  \"message_type\": \"outgoing\",\n  \"private\": true\n}",
        "options": {}
      },
      "id": "node-chatwoot-log",
      "name": "Registrar Nota no Chatwoot",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [3440, 220]
    },
    {
      "parameters": {},
      "id": "node-noop-descartar",
      "name": "Encerrar Execucao Antiga",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [2560, 440]
    }
  ],
  "connections": {
    "Webhook Evolution v2": {
      "main": [[{ "node": "Filtrar fromMe e Grupos", "type": "main", "index": 0 }]]
    },
    "Filtrar fromMe e Grupos": {
      "main": [[{ "node": "Switch Audio vs Texto", "type": "main", "index": 0 }]]
    },
    "Switch Audio vs Texto": {
      "main": [
        [{ "node": "Converter Base64 para OGG", "type": "main", "index": 0 }],
        [{ "node": "Normalizar Mensagem", "type": "main", "index": 0 }]
      ]
    },
    "Converter Base64 para OGG": {
      "main": [[{ "node": "Transcrever Audio Groq Whisper", "type": "main", "index": 0 }]]
    },
    "Transcrever Audio Groq Whisper": {
      "main": [[{ "node": "Normalizar Mensagem", "type": "main", "index": 0 }]]
    },
    "Normalizar Mensagem": {
      "main": [[{ "node": "Redis RPUSH Fila", "type": "main", "index": 0 }]]
    },
    "Redis RPUSH Fila": {
      "main": [[{ "node": "Redis Marcar Ultima Execucao", "type": "main", "index": 0 }]]
    },
    "Redis Marcar Ultima Execucao": {
      "main": [[{ "node": "Wait 12s Debounce", "type": "main", "index": 0 }]]
    },
    "Wait 12s Debounce": {
      "main": [[{ "node": "Redis Ler Ultima Execucao", "type": "main", "index": 0 }]]
    },
    "Redis Ler Ultima Execucao": {
      "main": [[{ "node": "Ultima Mensagem da Rajada?", "type": "main", "index": 0 }]]
    },
    "Ultima Mensagem da Rajada?": {
      "main": [
        [{ "node": "Redis Ler Fila Completa", "type": "main", "index": 0 }],
        [{ "node": "Encerrar Execucao Antiga", "type": "main", "index": 0 }]
      ]
    },
    "Redis Ler Fila Completa": {
      "main": [[{ "node": "Redis Limpar Fila", "type": "main", "index": 0 }]]
    },
    "Redis Limpar Fila": {
      "main": [[{ "node": "AI Agent Atendimento", "type": "main", "index": 0 }]]
    },
    "AI Agent Atendimento": {
      "main": [[{ "node": "Enviar Resposta Evolution v2", "type": "main", "index": 0 }]]
    },
    "Enviar Resposta Evolution v2": {
      "main": [[{ "node": "Registrar Nota no Chatwoot", "type": "main", "index": 0 }]]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
