Skip to content

WhatsApp Trigger Workflow

This workflow processes incoming WhatsApp messages from youth entrepreneurs, routing them to appropriate handlers based on user status and message timing. It includes both development and production environments, handles daytime message queuing, and provides fallback responses when the AI agent fails.

Purpose

No business context provided yet — add a context.md to enrich this documentation.

How It Works

  1. Message Reception: Receives WhatsApp messages via Twilio webhook (separate endpoints for development and production)
  2. User Validation: Looks up the sender's phone number in the youthEntrepreneursReal database table
  3. User Not Found: If the phone number isn't registered, sends an error message directing them to contact their program coordinator
  4. Activity Tracking: Updates the user's lastInboundAt timestamp to track engagement
  5. Daytime Filtering: Checks if it's daytime (4 AM - 7 PM Nairobi time) and the user hasn't started an evening session
  6. Message Queuing: If it's daytime, stores the message in pendingDaytimeMessages table for later processing
  7. Weekly Report Routing: Checks if the user is in a weekly report stage and routes to the Weekly Report Handler workflow
  8. AI Agent Processing: For other messages, calls the Francis SalesTrackingAgent workflow to generate responses
  9. Response Validation: Checks if the AI agent returned a valid response
  10. Message Delivery: Sends the AI response back via WhatsApp using Twilio
  11. Error Handling: If the AI fails, logs the error and sends a fallback message in Swahili
  12. Chat Logging: Records all conversations in the chatLog table for analysis

Workflow Diagram

graph TD
    A[WhatsApp Webhook] --> B[Get User Record]
    B --> C{User Found?}
    C -->|No| D[Send Error Message]
    C -->|Yes| E[Update Last Inbound]
    E --> F{Daytime Message?}
    F -->|Yes| G[Store in Pending Messages]
    F -->|No| H[Set User Data]
    G --> H
    H --> I{Weekly Report Stage?}
    I -->|Yes| J[Call Weekly Report Handler]
    I -->|No| K[Call Sales Tracking Agent]
    J --> L{Has Response?}
    K --> L
    L -->|Yes| M[Send WhatsApp Response]
    L -->|No| N[Log Error]
    N --> O[Set Fallback Message]
    O --> P[Send Fallback WhatsApp]
    O --> Q[Log Chat Fallback]

Trigger

Webhook Trigger: Two webhook endpoints receive POST requests from Twilio when WhatsApp messages are received: - Development: /webhook/98ed6d7d-5af1-4500-878f-56b7f22cad75 - Production: /webhook/23dd4bb2-c037-4603-8483-d52e2faecf48

Nodes Used

Node Type Purpose
Webhook Receives incoming WhatsApp messages from Twilio
PostgreSQL Queries user records, stores messages, logs errors and chats
If Conditional routing based on user status, time, and response validation
Set Prepares data for downstream nodes
Execute Workflow Calls Weekly Report Handler and Sales Tracking Agent workflows
Twilio Sends WhatsApp responses and error messages

External Services & Credentials Required

Twilio

  • Purpose: WhatsApp messaging service
  • Credentials: Twilio API credentials (Account SID, Auth Token)
  • Configuration: WhatsApp sandbox or approved WhatsApp Business number

PostgreSQL Database

  • Purpose: User management, message queuing, error logging, chat history
  • Credentials: Database connection (host, port, database name, username, password)
  • Required Tables:
    • youthEntrepreneursReal: User profiles and status
    • pendingDaytimeMessages: Queued messages during business hours
    • errorLog: Error tracking and debugging
    • chatLog: Conversation history

Environment Variables

No explicit environment variables are configured in this workflow. All configuration is handled through n8n credentials and node parameters.

Data Flow

Input (Twilio Webhook)

1
2
3
4
5
6
7
8
{
  "body": {
    "WaId": "254728309545",
    "Body": "User message content",
    "To": "whatsapp:+254203892316",
    "From": "whatsapp:+254728309545"
  }
}

Output (WhatsApp Response)

  • AI-generated response from Sales Tracking Agent
  • Weekly Report Handler response (for users in reporting stage)
  • Fallback message in Swahili if AI fails
  • Error message for unregistered users

Error Handling

  1. User Not Found: Sends message directing user to contact program coordinator
  2. AI Agent Failure:
    • Logs error details to errorLog table
    • Sends fallback message in Swahili with contact information
    • Records fallback interaction in chat log
  3. Database Errors: Nodes configured with "Continue on Error" to prevent workflow crashes
  4. Retry Logic: Execute Workflow nodes have retry enabled for transient failures

Known Limitations

Based on the sticky notes in the workflow: - No Slack integration for error notifications (marked as TODO) - Call center integration not implemented (noted as "no call center people") - Sales-related message handling needs improvement (marked as TODO)

  • Francis - SalesTrackingAgent (aygyT37fIK22WZ9a): Main AI agent for handling user queries
  • Weekly Report Handler (SlShcSkVHkkJ54wK): Specialized handler for users in weekly reporting stages

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance

  2. Configure Credentials:

    • Set up Twilio API credentials with WhatsApp access
    • Configure PostgreSQL database connection
  3. Database Setup: Ensure these tables exist with proper schema:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    -- Users table
    youthEntrepreneursReal (id, phoneNumber, eveningSessionStarted, todayDataCollected, lastInboundAt, onboardingStatus, currentStage)
    
    -- Message queue
    pendingDaytimeMessages (id, phoneNumber, content, channel, nairobiTime, date, createdAt)
    
    -- Error tracking
    errorLog (id, phoneNumber, workflow, errorMessage, rawInput, createdAt)
    
    -- Chat history
    chatLog (id, userPhone, userQuery, agentResponse, channel, created_at)
    

  4. Webhook Configuration:

    • Copy webhook URLs from the workflow
    • Configure Twilio to send WhatsApp messages to these endpoints
    • Set up separate webhooks for development and production
  5. Dependent Workflows: Ensure the Sales Tracking Agent and Weekly Report Handler workflows are imported and active

  6. Test: Send a test WhatsApp message to verify the complete flow works

  7. Activate: Enable the workflow for your chosen environment (development or production)