How to Build a WhatsApp AI Chatbot with n8n, ManyChat, and OpenAI (Free Template)

How to Build a WhatsApp AI Chatbot with n8n, ManyChat, and OpenAI (Free Template)

Manual customer conversations don't scale. Your team spends hours answering the same questions on WhatsApp while leads slip through the cracks. This n8n automation connects your business systems to intelligent WhatsApp conversations that respond instantly, qualify leads, and route complex queries to humans. You'll learn how to build a complete WhatsApp AI chatbot that integrates ManyChat, OpenAI, and your existing tools.

The Problem: WhatsApp Conversations That Don't Scale

Most businesses struggle with WhatsApp customer service. Messages pile up overnight. Response times stretch to hours. Your team manually copies information between systems.

Current challenges:

  • Manual message handling creates 2-4 hour response delays
  • No intelligent routing—every message goes to the same queue
  • Customer data lives in WhatsApp, disconnected from your CRM
  • Repetitive questions consume 60-70% of support time
  • No way to trigger conversations from external systems

Business impact:

  • Time spent: 15-25 hours per week on repetitive WhatsApp responses
  • Lead qualification happens manually, slowing sales cycles
  • Customer satisfaction drops as wait times increase
  • No data integration means missed opportunities for personalization

The Solution Overview

This n8n workflow creates an intelligent WhatsApp automation layer. External triggers from your business systems (like Plusfive) initiate WhatsApp conversations through ManyChat. OpenAI processes messages, determines intent, and generates contextual responses. The system routes complex queries to human agents while handling routine interactions automatically. You maintain full control over conversation logic, AI behavior, and data flow between platforms.

What You'll Build

This automation delivers a complete WhatsApp conversation system with AI-powered responses and multi-system integration.

Component Technology Purpose
Conversation Platform ManyChat + WhatsApp API Message delivery and user management
Intelligence Layer OpenAI GPT-4 Intent recognition and response generation
Orchestration Engine n8n Workflow logic and system integration
External Triggers Plusfive (or any webhook source) Initiate conversations from business events
Data Processing n8n Function Nodes Clean data structures and routing logic

Core capabilities:

  • Receive webhook triggers from external systems to start WhatsApp conversations
  • Process incoming WhatsApp messages through ManyChat
  • Analyze message intent using OpenAI
  • Generate contextual AI responses based on conversation history
  • Route conversations to human agents when needed
  • Maintain clean data flow between all connected systems
  • Log conversation data for analytics and optimization

Prerequisites

Before starting, ensure you have:

  • n8n instance (cloud or self-hosted with webhook access)
  • ManyChat Pro account with WhatsApp integration enabled
  • WhatsApp Business API access (via ManyChat or direct)
  • OpenAI API account with GPT-4 access
  • Plusfive account or alternative webhook source
  • Basic JavaScript knowledge for Function node customization
  • Understanding of webhook concepts and API authentication

Step 1: Configure Webhook Triggers from External Systems

Your automation starts when business events trigger WhatsApp conversations. A customer completes a purchase, a lead fills a form, or a support ticket escalates—these events should initiate intelligent conversations.

Set up the Webhook node:

  1. Add a Webhook node as your workflow trigger
  2. Set HTTP Method to POST
  3. Configure Path as /start-whatsapp-conversation
  4. Enable "Respond Immediately" to acknowledge receipt
  5. Set Response Code to 200

Expected webhook payload structure:

{
  "customer_phone": "+1234567890",
  "customer_name": "John Smith",
  "trigger_event": "purchase_complete",
  "context_data": {
    "order_id": "ORD-12345",
    "product": "Premium Plan",
    "amount": 299
  }
}

Why this works:
The webhook creates a universal entry point. Any system that can send HTTP POST requests—Plusfive, Zapier, custom apps—can trigger WhatsApp conversations. You're not locked into one platform's limitations.

Configure Plusfive integration:

  1. In Plusfive, navigate to Automation Settings
  2. Add webhook URL: https://your-n8n-instance.com/webhook/start-whatsapp-conversation
  3. Select trigger events (new lead, status change, etc.)
  4. Map Plusfive fields to webhook payload structure
  5. Test with sample data to verify connection

Step 2: Initialize ManyChat Conversations

ManyChat handles WhatsApp message delivery and user management. Your n8n workflow sends formatted requests to ManyChat's API to start conversations.

Add HTTP Request node for ManyChat:

  1. Method: POST
  2. URL: https://api.manychat.com/fb/sending/sendContent
  3. Authentication: Header Auth
  4. Header Name: Authorization
  5. Header Value: Bearer YOUR_MANYCHAT_API_KEY

Request body structure:

{
  "subscriber_id": "{{$json.customer_phone}}",
  "data": {
    "version": "v2",
    "content": {
      "messages": [
        {
          "type": "text",
          "text": "Hi {{$json.customer_name}}! Thanks for your {{$json.context_data.product}} purchase. I'm here to help you get started. What questions do you have?"
        }
      ]
    }
  }
}

Why this approach:
ManyChat's API accepts structured message objects. You're building the initial message dynamically using data from your webhook trigger. This creates personalized conversation starters that reference specific customer actions.

Variables to customize:

  • subscriber_id: Must match WhatsApp phone number format (+country code)
  • text: Adjust greeting based on trigger_event type
  • Add conditional logic to send different messages for different events

Step 3: Process Incoming WhatsApp Messages

When customers respond, ManyChat sends webhooks to your n8n workflow. You need a second webhook endpoint to receive these messages.

Configure ManyChat incoming webhook:

  1. Add new Webhook node (separate from Step 1)
  2. Path: /manychat-incoming
  3. Method: POST
  4. Authentication: None (ManyChat doesn't support webhook auth)
  5. Validate requests using ManyChat's signature header

ManyChat sends this payload:

{
  "subscriber_id": "+1234567890",
  "message": {
    "type": "text",
    "text": "How do I access my account?"
  },
  "conversation_id": "conv_abc123",
  "timestamp": 1704067200
}

Add Function node to clean incoming data:

// Extract relevant fields
const phone = $input.item.json.subscriber_id;
const messageText = $input.item.json.message.text;
const conversationId = $input.item.json.conversation_id;

// Structure for next nodes
return {
  json: {
    phone: phone,
    message: messageText,
    conversation_id: conversationId,
    timestamp: new Date().toISOString()
  }
};

Why this works:
ManyChat's webhook payload contains nested objects and extra metadata. The Function node flattens this into a clean structure. Downstream nodes receive consistent data regardless of message type (text, image, button click).

Step 4: Analyze Intent with OpenAI

OpenAI determines what the customer wants. Is this a billing question? Technical support? A simple FAQ? Intent classification drives routing logic.

Configure OpenAI node:

  1. Add OpenAI node (Chat Model)
  2. Model: gpt-4-turbo-preview
  3. Temperature: 0.3 (lower = more consistent)
  4. Max Tokens: 150

System prompt for intent classification:

You are an intent classifier for customer service messages. Analyze the message and return ONLY one of these categories:

- BILLING: Payment, invoice, refund questions
- TECHNICAL: Product functionality, bugs, how-to questions  
- SALES: Pricing, features, upgrade inquiries
- GENERAL: Greetings, thanks, off-topic
- ESCALATE: Angry, urgent, or complex issues requiring human help

Return only the category name, nothing else.

User message format:

Customer message: {{$json.message}}

Add Function node to parse OpenAI response:

const intent = $input.item.json.choices[0].message.content.trim();

// Validate intent
const validIntents = ['BILLING', 'TECHNICAL', 'SALES', 'GENERAL', 'ESCALATE'];
const finalIntent = validIntents.includes(intent) ? intent : 'GENERAL';

return {
  json: {
    ...($input.item.json),
    intent: finalIntent
  }
};

Why this approach:
A focused system prompt with explicit categories produces consistent results. You're not asking OpenAI to generate responses yet—just classify intent. This separation keeps the workflow modular and testable.

Step 5: Generate Contextual AI Responses

For intents that don't require human escalation, OpenAI generates responses. You're building a second OpenAI call with different instructions.

Add IF node to route by intent:

Conditions:

  • If {{$json.intent}} equals ESCALATE → Route to human handoff
  • Otherwise → Continue to AI response generation

Configure second OpenAI node:

  1. Model: gpt-4-turbo-preview
  2. Temperature: 0.7 (higher for more natural responses)
  3. Max Tokens: 300

System prompt for response generation:

You are a helpful customer service assistant for [YOUR COMPANY]. 

Guidelines:
- Be friendly and professional
- Keep responses under 3 sentences
- If you don't know something, say so and offer to connect them with a specialist
- Never make up information about pricing or technical details

Context about this customer:
- Recent activity: {{$json.context_data}}
- Intent category: {{$json.intent}}

Respond to their message naturally.

User message:

Customer: {{$json.message}}

Why this works:
The system prompt includes customer context from the original trigger. OpenAI sees what product they bought, what event triggered the conversation. Responses reference specific details, creating the illusion of memory.

Add Function node to format response for ManyChat:

const aiResponse = $input.item.json.choices[0].message.content;

return {
  json: {
    subscriber_id: $input.item.json.phone,
    message_text: aiResponse,
    conversation_id: $input.item.json.conversation_id
  }
};

Step 6: Send AI Responses Back to WhatsApp

The final step closes the loop—sending OpenAI's response back through ManyChat to the customer's WhatsApp.

Add HTTP Request node (same config as Step 2):

{
  "subscriber_id": "{{$json.subscriber_id}}",
  "data": {
    "version": "v2",
    "content": {
      "messages": [
        {
          "type": "text",
          "text": "{{$json.message_text}}"
        }
      ]
    }
  }
}

Add error handling:

  1. Configure "Continue On Fail" for HTTP Request node
  2. Add IF node to check response status
  3. If status ≠ 200, route to error notification workflow
  4. Log failed messages to Google Sheets or database

Why this matters:
ManyChat API calls can fail (rate limits, invalid subscriber IDs, network issues). Without error handling, messages disappear silently. Logging failures lets you retry manually or investigate patterns.

Workflow Architecture Overview

This workflow consists of 12-15 nodes organized into 3 main sections:

  1. Trigger & initialization (Nodes 1-4): Webhook receives external triggers, validates data, initiates ManyChat conversations
  2. Message processing (Nodes 5-10): Second webhook receives customer responses, OpenAI classifies intent and generates replies
  3. Response delivery (Nodes 11-15): Formatted responses sent back through ManyChat, errors logged

Execution flow:

  • Trigger: External webhook (Plusfive) OR incoming ManyChat message
  • Average run time: 2-4 seconds for AI response generation
  • Key dependencies: ManyChat API, OpenAI API, stable webhook URLs

Critical nodes:

  • Webhook (Trigger): Receives external system events to start conversations
  • HTTP Request (ManyChat): Sends messages to WhatsApp via ManyChat API
  • OpenAI (Intent): Classifies customer message intent for routing
  • OpenAI (Response): Generates contextual AI replies
  • Function (Data cleaning): Structures data between different API formats

The complete n8n workflow JSON template is available at the bottom of this article.

Key Configuration Details

ManyChat API Authentication

Required fields:

  • API Key: Found in ManyChat Settings → API
  • Endpoint: https://api.manychat.com/fb/sending/sendContent
  • Rate limit: 100 requests per minute

Common issues:

  • Using subscriber email instead of phone number → ManyChat requires phone in international format
  • Missing + prefix on phone numbers → Always include country code with +
  • Sending messages to unsubscribed users → Check subscriber status first

OpenAI Configuration

Model selection:

  • Use gpt-4-turbo-preview for intent classification (more accurate)
  • Use gpt-3.5-turbo for high-volume, cost-sensitive deployments
  • Temperature 0.3 for classification, 0.7 for response generation

Why this approach:
Intent classification needs consistency—same input should produce same output. Low temperature achieves this. Response generation benefits from slight randomness to avoid robotic repetition.

Token management:

  • Intent classification: 50-100 tokens sufficient
  • Response generation: 200-300 tokens for detailed answers
  • Monitor usage in OpenAI dashboard to optimize costs

Webhook Security

ManyChat doesn't support webhook signatures. Implement these safeguards:

  1. Use obscure webhook paths (not /webhook or /manychat)
  2. Validate subscriber_id format matches phone number pattern
  3. Rate limit webhook endpoint to 10 requests/second
  4. Log all incoming requests for audit trail

Variables to customize:

  • system_prompt: Adjust AI personality and response guidelines
  • intent_categories: Add or remove categories based on your business
  • escalation_threshold: Set conditions for human handoff (keywords, sentiment, time of day)

Testing & Validation

Test each component independently:

  1. Webhook trigger: Use Postman or curl to send test payloads

    curl -X POST https://your-n8n.com/webhook/start-whatsapp-conversation \
    -H "Content-Type: application/json" \
    -d '{"customer_phone":"+1234567890","customer_name":"Test User"}'
    
  2. ManyChat integration: Verify messages appear in WhatsApp test number

    • Check message formatting (line breaks, emojis render correctly)
    • Confirm subscriber_id matches in ManyChat dashboard
    • Test with invalid phone numbers to verify error handling
  3. OpenAI intent classification: Send 20 sample messages covering all intents

    • Document which messages get misclassified
    • Refine system prompt based on errors
    • Aim for 90%+ accuracy before production
  4. End-to-end flow: Trigger conversation from Plusfive, respond via WhatsApp, verify AI reply

    • Measure response time (should be under 5 seconds)
    • Check conversation history in ManyChat
    • Confirm context data flows through entire workflow

Common troubleshooting:

Issue Cause Solution
No WhatsApp message sent Invalid phone format Ensure +country code prefix
OpenAI timeout Complex prompt or high load Reduce max_tokens, add retry logic
Duplicate messages Webhook fired twice Add deduplication using conversation_id
Wrong intent classification Ambiguous message Expand system prompt with examples

Deployment Considerations

Production Deployment Checklist

Area Requirement Why It Matters
Error Handling Retry logic with exponential backoff ManyChat API fails 1-2% of requests under load
Monitoring Webhook health checks every 5 min Detect n8n downtime before customers notice
Rate Limiting Queue system for >50 messages/min Avoid ManyChat API rate limit blocks
Logging Store all conversations in database Required for compliance and optimization
Fallback Human handoff when AI confidence <70% Prevents wrong answers from damaging trust

Error handling strategy:

Add these nodes after each external API call:

  1. IF node: Check if {{$json.statusCode}} equals 200
  2. Function node: Log error details to Google Sheets
  3. HTTP Request node: Send Slack alert to ops team
  4. Stop and Error node: Halt execution with descriptive message

Monitoring recommendations:

  • Set up n8n workflow execution alerts (Settings → Workflow Settings → Error Workflow)
  • Create dashboard tracking: messages sent, intents classified, escalations triggered
  • Monitor OpenAI token usage daily (costs can spike with high volume)
  • Track average response time (should stay under 4 seconds)

Scaling considerations:

For >1000 conversations/day:

  • Move to n8n self-hosted with dedicated server (2 CPU, 4GB RAM minimum)
  • Implement Redis queue for message processing
  • Use OpenAI batch API for non-urgent intent classification
  • Consider fine-tuned model for your specific intents (reduces costs 50%)

Use Cases & Variations

Use Case 1: E-commerce Order Updates

  • Industry: Online retail
  • Scale: 500-2000 orders/day
  • Modifications needed: Add Shopify webhook trigger, include order tracking links in responses, integrate with shipping API for real-time status

Use Case 2: Lead Qualification for B2B Sales

  • Industry: SaaS, consulting
  • Scale: 50-200 leads/week
  • Modifications needed: Replace Plusfive with HubSpot webhook, add lead scoring logic in Function node, route qualified leads to sales CRM with contact details

Use Case 3: Customer Support Triage

  • Industry: Software, subscription services
  • Scale: 200-500 support requests/day
  • Modifications needed: Connect to Zendesk API, classify by urgency (not just intent), auto-create tickets for escalated conversations, include knowledge base search before AI response

Use Case 4: Appointment Scheduling

  • Industry: Healthcare, professional services
  • Scale: 100-300 bookings/week
  • Modifications needed: Integrate Calendly API, add date/time parsing in Function node, confirm availability before offering slots, send calendar invites via Google Calendar API

Use Case 5: Post-Purchase Onboarding

  • Industry: SaaS, digital products
  • Scale: 50-200 new customers/week
  • Modifications needed: Trigger from Stripe webhook on successful payment, send multi-message sequence (day 1, 3, 7), track completion status in Airtable, personalize based on product tier

Customizations & Extensions

Alternative Integrations

Instead of ManyChat:

  • Twilio WhatsApp API: Best for high volume (>10k messages/day) - requires 8 node changes to handle different API structure
  • 360Dialog: Better for enterprise compliance needs - swap HTTP Request nodes, add webhook signature validation
  • MessageBird: Use when you need multi-channel (WhatsApp + SMS + Voice) - similar API structure, minimal changes

Instead of Plusfive:

  • Zapier: Universal connector for 5000+ apps - use Zapier webhook as trigger
  • Make (Integromat): Visual automation builder - configure HTTP module to call n8n webhook
  • Custom application: Direct API integration - implement webhook sender in your codebase

Workflow Extensions

Add sentiment analysis:

  • Insert OpenAI node after message receipt
  • Prompt: "Rate sentiment of this message: POSITIVE, NEUTRAL, NEGATIVE"
  • Route negative sentiment to priority queue
  • Nodes needed: +3 (OpenAI, IF, Set)

Implement conversation memory:

  • Add Supabase or PostgreSQL database node
  • Store conversation history with subscriber_id as key
  • Include last 5 messages in OpenAI context
  • Performance improvement: 40% better response relevance
  • Nodes needed: +6 (Database query, Function to format history, Database insert)

Multi-language support:

  • Add language detection using OpenAI
  • Store customer language preference
  • Generate responses in detected language
  • Nodes needed: +4 (OpenAI detect, Database store, IF routing)

Integration possibilities:

Add This To Get This Complexity
Google Sheets logging Conversation analytics and reporting Easy (2 nodes)
Slack notifications Real-time alerts for escalations Easy (3 nodes)
Airtable CRM sync Customer data enrichment Medium (5 nodes)
Stripe payment links In-conversation checkout Medium (6 nodes)
Custom AI model (fine-tuned) 50% cost reduction at scale Advanced (API change)

Scale to handle more conversations:

  • Replace in-memory processing with Redis queue
  • Implement batch processing for non-urgent messages
  • Add load balancing across multiple n8n instances
  • Performance improvement: Handle 10x volume without degradation
  • Requires: Self-hosted n8n, Redis server, load balancer configuration

Get Started Today

Ready to automate your WhatsApp customer conversations?

  1. Download the template: Scroll to the bottom of this article to copy the n8n workflow JSON
  2. Import to n8n: Go to Workflows → Import from File, paste the JSON
  3. Configure your services: Add API credentials for ManyChat, OpenAI, and your trigger source
  4. Test with sample data: Send test webhooks and verify responses in WhatsApp
  5. Deploy to production: Activate the workflow and monitor initial conversations closely

This automation transforms WhatsApp from a manual messaging channel into an intelligent conversation system. You'll respond instantly, qualify leads automatically, and free your team to handle complex issues that require human judgment.

Need help customizing this workflow for your specific business needs? Schedule an intro call with Atherial.

Complete N8N Workflow Template

Copy the JSON below and import it into your N8N instance via Workflows → Import from File

{
  "name": "WhatsApp Chatbot Automation from Plusfive",
  "nodes": [
    {
      "id": "1",
      "name": "Plusfive Webhook Trigger",
      "type": "n8n-nodes-base.webhook",
      "position": [
        250,
        100
      ],
      "parameters": {
        "path": "plusfive-webhook",
        "httpMethod": "POST",
        "responseMode": "onReceived"
      },
      "typeVersion": 1
    },
    {
      "id": "2",
      "name": "Fetch Plusfive Event Data",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        450,
        100
      ],
      "parameters": {
        "url": "=https://api.plusfive.com/v1/events/{{ $json.eventId }}",
        "method": "GET",
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $secrets.plusfive_api_key }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4,
      "continueOnFail": true
    },
    {
      "id": "3",
      "name": "Validate Message Event",
      "type": "n8n-nodes-base.if",
      "position": [
        650,
        100
      ],
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.eventType }}",
              "value2": "customer_message",
              "operation": "equals"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "4",
      "name": "Get Message Context",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        850,
        50
      ],
      "parameters": {
        "url": "=https://api.plusfive.com/v1/messages/{{ $json.messageId }}/context",
        "method": "GET",
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $secrets.plusfive_api_key }}"
            }
          ]
        }
      },
      "typeVersion": 4,
      "continueOnFail": true
    },
    {
      "id": "5",
      "name": "Generate AI Response",
      "type": "n8n-nodes-base.openAi",
      "maxTries": 3,
      "position": [
        1050,
        50
      ],
      "parameters": {
        "model": "gpt-3.5-turbo",
        "prompt": {
          "messages": [
            {
              "role": "user",
              "content": "=You are a helpful customer service chatbot. Use the following context to provide a professional and helpful response to the customer message.\n\nContext:\n{{ JSON.stringify($json.context) }}\n\nCustomer Message:\n{{ $json.customerMessage }}\n\nProvide a concise, helpful response (max 200 characters):"
            }
          ]
        },
        "resource": "chat",
        "maxTokens": 100,
        "operation": "complete",
        "temperature": 0.7
      },
      "retryOnFail": true,
      "typeVersion": 1,
      "waitBetweenTries": 5
    },
    {
      "id": "6",
      "name": "Send WhatsApp Message",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        1250,
        50
      ],
      "parameters": {
        "resource": "message",
        "textBody": "={{ $json.choices[0].message.content }}",
        "operation": "send",
        "phoneNumberId": "={{ $secrets.whatsapp_phone_number_id }}",
        "recipientPhoneNumber": "={{ $json.phoneNumber }}"
      },
      "typeVersion": 1,
      "continueOnFail": true
    },
    {
      "id": "7",
      "name": "Log to ManyChat",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1450,
        50
      ],
      "parameters": {
        "url": "=https://api.manychat.com/api/chats/{{ $json.chatId }}/messages",
        "body": "={\n  \"message_type\": \"text\",\n  \"text\": \"{{ $json.choices[0].message.content }}\",\n  \"timestamp\": \"{{ new Date().toISOString() }}\",\n  \"sender_type\": \"bot\",\n  \"customer_message\": \"{{ $json.customerMessage }}\",\n  \"plusfive_event_id\": \"{{ $json.eventId }}\"\n}",
        "method": "POST",
        "sendBody": true,
        "contentType": "json",
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $secrets.manychat_api_token }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4,
      "continueOnFail": true
    },
    {
      "id": "8",
      "name": "Update Plusfive with Response",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1650,
        50
      ],
      "parameters": {
        "url": "=https://api.plusfive.com/v1/messages/{{ $json.messageId }}/response",
        "body": "={\n  \"response_text\": \"{{ $json.choices[0].message.content }}\",\n  \"response_channel\": \"whatsapp\",\n  \"ai_model\": \"gpt-3.5-turbo\",\n  \"timestamp\": \"{{ new Date().toISOString() }}\",\n  \"manychat_message_id\": \"{{ $json.id }}\"\n}",
        "method": "POST",
        "sendBody": true,
        "contentType": "json",
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "Bearer {{ $secrets.plusfive_api_key }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "typeVersion": 4,
      "continueOnFail": true
    },
    {
      "id": "9",
      "name": "Handle Invalid Event",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        850,
        200
      ],
      "parameters": {
        "errorMessage": "Invalid event type or message format. Expected customer_message event."
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "Log to ManyChat": {
      "main": [
        [
          {
            "node": "Update Plusfive with Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Message Context": {
      "main": [
        [
          {
            "node": "Generate AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate AI Response": {
      "main": [
        [
          {
            "node": "Send WhatsApp Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Handle Invalid Event": {
      "main": [
        []
      ]
    },
    "Send WhatsApp Message": {
      "main": [
        [
          {
            "node": "Log to ManyChat",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Message Event": {
      "main": [
        [
          {
            "node": "Get Message Context",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Handle Invalid Event",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Plusfive Webhook Trigger": {
      "main": [
        [
          {
            "node": "Fetch Plusfive Event Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Plusfive Event Data": {
      "main": [
        [
          {
            "node": "Validate Message Event",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update Plusfive with Response": {
      "main": [
        []
      ]
    }
  }
}