{
  "name": "Lunexo – AI Lead Qualifier (n8n + OpenClaw)",
  "nodes": [
    {
      "parameters": {
        "content": "## AI Lead Qualifier (OpenClaw)\n\n**What it does:** Receives lead data via webhook, sends it to OpenClaw AI for qualification scoring, then notifies via Telegram and email with the result.\n\n**Setup (~15 min):**\n1. Ensure OpenClaw is running on localhost:18789\n2. Add your SMTP credentials\n3. Add your Telegram Bot API credentials\n4. Add your OpenClaw HTTP Header Auth token\n5. Replace `YOUR_TELEGRAM_CHAT_ID` with your chat ID\n6. Replace `YOUR_ADMIN_EMAIL` with your inbox\n7. Activate the workflow\n\n**Variables to change:**\n- `YOUR_TELEGRAM_CHAT_ID` — Telegram chat ID\n- `YOUR_ADMIN_EMAIL` — admin notification inbox",
        "height": 350,
        "width": 350,
        "color": 5
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000001",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [40, 80]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "qualify-lead",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000002",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [240, 300],
      "webhookId": "f8c40001-e5f6-7a8b-d9c0-800000000020"
    },
    {
      "parameters": {
        "jsCode": "try {\n  const input = $input.first().json;\n  const body = input.body || input;\n  const name = body.name || body.fullName || 'Unknown';\n  const email = (body.email || '').trim().toLowerCase();\n  const company = body.company || 'Not provided';\n  const role = body.role || body.jobTitle || 'Not provided';\n  const budget = body.budget || 'Not provided';\n  const message = body.message || body.inquiry || '';\n  const source = body.source || 'webhook';\n  const phone = body.phone || '';\n\n  return [{ json: { name, email, company, role, budget, message, source, phone } }];\n} catch (err) {\n  return [{ json: { name: 'Unknown', email: '', company: '', role: '', budget: '', message: '', source: 'error', phone: '', error: err.message } }];\n}"
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000003",
      "name": "Extract Lead Data",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [460, 300]
    },
    {
      "parameters": {
        "jsCode": "const lead = $input.first().json;\n\nconst prompt = `You are an expert B2B lead qualification assistant. Analyze this lead and provide a qualification score.\n\nLead Information:\n- Name: ${lead.name}\n- Email: ${lead.email}\n- Company: ${lead.company}\n- Role: ${lead.role}\n- Budget: ${lead.budget}\n- Message: ${lead.message}\n- Source: ${lead.source}\n\nRespond in this exact JSON format:\n{\n  \"score\": <number 1-10>,\n  \"tier\": \"<hot|warm|cold>\",\n  \"reasoning\": \"<brief explanation>\",\n  \"suggestedAction\": \"<next step recommendation>\",\n  \"estimatedValue\": \"<low|medium|high>\"\n}`;\n\nreturn [{ json: { ...lead, prompt } }];"
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000004",
      "name": "Build AI Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [680, 300]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "http://localhost:18789/v1/chat/completions",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"model\": \"openclaw:main\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": {{ JSON.stringify($json.prompt) }}\n    }\n  ],\n  \"temperature\": 0.3\n}",
        "options": {
          "timeout": 30000
        }
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000005",
      "name": "OpenClaw API",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [900, 300],
      "credentials": {
        "httpHeaderAuth": {
          "id": "CHANGE_ME",
          "name": "OpenClaw Gateway Token"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "f8c40001-cond-0001",
              "leftValue": "={{ $json.choices }}",
              "rightValue": "",
              "operator": {
                "type": "array",
                "operation": "notEmpty"
              }
            }
          ],
          "combinator": "and"
        }
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000006",
      "name": "IF AI Response Valid",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1120, 300]
    },
    {
      "parameters": {
        "jsCode": "try {\n  const input = $input.first().json;\n  const aiText = input.choices[0].message.content;\n  let parsed;\n  try {\n    const jsonMatch = aiText.match(/\\{[\\s\\S]*\\}/);\n    parsed = JSON.parse(jsonMatch ? jsonMatch[0] : aiText);\n  } catch (e) {\n    parsed = { score: 5, tier: 'warm', reasoning: aiText, suggestedAction: 'Manual review recommended', estimatedValue: 'medium' };\n  }\n\n  const score = parsed.score || 5;\n  const tier = parsed.tier || 'warm';\n  const reasoning = parsed.reasoning || 'No reasoning provided';\n  const suggestedAction = parsed.suggestedAction || 'Follow up manually';\n  const estimatedValue = parsed.estimatedValue || 'medium';\n\n  const tierEmoji = tier === 'hot' ? '🔥' : tier === 'warm' ? '🌤️' : '❄️';\n  const scoreBar = '█'.repeat(score) + '░'.repeat(10 - score);\n\n  const name = input.name || 'Unknown';\n  const email = input.email || '';\n  const company = input.company || '';\n\n  const telegramMessage = `${tierEmoji} Lead Qualified: ${name}\\n\\n🏢 ${company}\\n📧 ${email}\\n📊 Score: ${score}/10 [${scoreBar}]\\n🏷️ Tier: ${tier.toUpperCase()}\\n💡 ${suggestedAction}`;\n\n  const emailHtml = `<div style=\"font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px;\">`\n    + `<h2 style=\"color:#6C2BD9;\">${tierEmoji} Lead Qualification Report</h2>`\n    + `<table style=\"width:100%;border-collapse:collapse;margin:16px 0;\">`\n    + `<tr style=\"background:#f4f0ff;\"><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Name</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${name}</td></tr>`\n    + `<tr><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Email</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${email}</td></tr>`\n    + `<tr style=\"background:#f4f0ff;\"><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Company</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${company}</td></tr>`\n    + `<tr><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Score</td><td style=\"padding:10px;border:1px solid #e0d4f5;font-size:18px;\">${score}/10 — ${tier.toUpperCase()}</td></tr>`\n    + `<tr style=\"background:#f4f0ff;\"><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Value</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${estimatedValue}</td></tr>`\n    + `<tr><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Reasoning</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${reasoning}</td></tr>`\n    + `<tr style=\"background:#f4f0ff;\"><td style=\"padding:10px;border:1px solid #e0d4f5;font-weight:bold;\">Next Step</td><td style=\"padding:10px;border:1px solid #e0d4f5;\">${suggestedAction}</td></tr>`\n    + `</table>`\n    + `<p style=\"color:#888;font-size:12px;\">— Lunexo AI Lead Qualifier</p></div>`;\n\n  return [{ json: { name, email, company, score, tier, reasoning, suggestedAction, estimatedValue, telegramMessage, emailHtml, tierEmoji } }];\n} catch (err) {\n  return [{ json: { error: err.message, telegramMessage: '⚠️ Error formatting AI result: ' + err.message, emailHtml: '<p>Error formatting result</p>', score: 0, tier: 'unknown', name: 'Error', email: '' } }];\n}"
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000007",
      "name": "Format AI Result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1340, 200]
    },
    {
      "parameters": {
        "chatId": "YOUR_TELEGRAM_CHAT_ID",
        "text": "={{ $json.telegramMessage }}",
        "additionalFields": {}
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000008",
      "name": "Send Telegram Result",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [1560, 200],
      "credentials": {
        "telegramApi": {
          "id": "CHANGE_ME",
          "name": "Your Telegram Bot"
        }
      }
    },
    {
      "parameters": {
        "fromEmail": "noreply@yourdomain.com",
        "toEmail": "YOUR_ADMIN_EMAIL",
        "subject": "={{ $json.tierEmoji }} Lead: {{ $json.name }} ({{ $json.tier }}) — Score {{ $json.score }}/10",
        "emailType": "html",
        "html": "={{ $json.emailHtml }}",
        "options": {}
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000009",
      "name": "Send Email Report",
      "type": "n8n-nodes-base.emailSend",
      "typeVersion": 2.1,
      "position": [1780, 200],
      "credentials": {
        "smtp": {
          "id": "CHANGE_ME",
          "name": "Your SMTP Account"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ success: true, score: $json.score, tier: $json.tier, reasoning: $json.reasoning, suggestedAction: $json.suggestedAction, estimatedValue: $json.estimatedValue }) }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000010",
      "name": "Respond OK",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [2000, 200]
    },
    {
      "parameters": {
        "jsCode": "const input = $input.first().json;\nconst name = input.name || 'Unknown';\nconst email = input.email || '';\n\nconst telegramAlert = `⚠️ AI Lead Qualification Failed\\n\\n👤 ${name}\\n📧 ${email}\\n❌ OpenClaw did not return a valid response.\\n🔧 Please check that OpenClaw is running and the model is loaded.`;\n\nconst fallbackMessage = 'AI analysis unavailable. This lead requires manual review.';\n\nreturn [{ json: { name, email, telegramAlert, fallbackMessage, status: 'manual_review_needed' } }];"
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000011",
      "name": "Format Fallback",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1340, 440]
    },
    {
      "parameters": {
        "chatId": "YOUR_TELEGRAM_CHAT_ID",
        "text": "={{ $json.telegramAlert }}",
        "additionalFields": {}
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000012",
      "name": "Send Telegram Error",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [1560, 440],
      "credentials": {
        "telegramApi": {
          "id": "CHANGE_ME",
          "name": "Your Telegram Bot"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ success: false, status: 'manual_review_needed', message: $json.fallbackMessage, lead: { name: $json.name, email: $json.email } }) }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "f8c40001-e5f6-7a8b-d9c0-800000000013",
      "name": "Respond Manual Review",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1780, 440]
    }
  ],
  "connections": {
    "Webhook": {
      "main": [
        [
          {
            "node": "Extract Lead Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Lead Data": {
      "main": [
        [
          {
            "node": "Build AI Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build AI Prompt": {
      "main": [
        [
          {
            "node": "OpenClaw API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenClaw API": {
      "main": [
        [
          {
            "node": "IF AI Response Valid",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IF AI Response Valid": {
      "main": [
        [
          {
            "node": "Format AI Result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Format Fallback",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format AI Result": {
      "main": [
        [
          {
            "node": "Send Telegram Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Telegram Result": {
      "main": [
        [
          {
            "node": "Send Email Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Email Report": {
      "main": [
        [
          {
            "node": "Respond OK",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Fallback": {
      "main": [
        [
          {
            "node": "Send Telegram Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Telegram Error": {
      "main": [
        [
          {
            "node": "Respond Manual Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "f8c40001-e5f6-7a8b-d9c0-800000000099",
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "lunexo"
  },
  "pinData": {},
  "staticData": null,
  "tags": [
    { "name": "Lunexo" },
    { "name": "AI" },
    { "name": "OpenClaw" },
    { "name": "Lead Qualifier" }
  ]
}