Skip to content

WhatsApp Trigger - Francis

This workflow processes incoming WhatsApp messages from youth entrepreneurs, validates users against a database, handles daytime message queuing, and routes messages to an AI sales tracking agent for intelligent responses.

Purpose

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

How It Works

The workflow operates in two identical parallel branches (development and production) with the following flow:

  1. Message Reception: Receives incoming WhatsApp messages via Twilio webhook
  2. User Validation: Looks up the sender's phone number in the youth entrepreneurs database
  3. User Authentication: If user not found, sends an error message and stops processing
  4. Activity Tracking: Updates the user's last inbound message timestamp
  5. Time-Based Routing: Checks if it's daytime (4 AM - 7 PM) and user hasn't started evening session
  6. Message Queuing: For daytime messages, stores them in a pending messages table for later processing
  7. Agent Processing: For evening messages or after queuing, calls the Francis SalesTrackingAgent workflow
  8. Response Validation: Checks if the agent returned a valid response
  9. Message Delivery: Sends the agent's response back via WhatsApp
  10. Error Handling: Logs errors and sends fallback messages in Swahili when processing fails

Mermaid Diagram

graph TD
    A[DevelopmentWebhook] --> B[getUserRecord]
    A2[productionWebhook] --> B2[getUserRecord1]

    B --> C[ifUserNotFound]
    B2 --> C2[ifUserNotFound1]

    C -->|User Not Found| D[userNotFound]
    C -->|User Found| E[updateLastInboundAt]
    C2 -->|User Not Found| D2[userNotFound1]
    C2 -->|User Found| E2[updateLastInboundAt1]

    E --> F[isDaytimeMessage]
    E2 --> F2[isDaytimeMessage1]

    F -->|Daytime| G[storeDaytimeMessage]
    F -->|Evening| H[setUserPhoneNumnberAndQuery]
    F2 -->|Daytime| G2[storeDaytimeMessage1]
    F2 -->|Evening| H2[setUserPhoneNumnberAndQuery1]

    G --> H
    G2 --> H2

    H --> I[Call 'Francis - SalesTrackingAgent']
    H2 --> I2[Call 'Francis - SalesTrackingAgent'1]

    I --> J[hasAgentOutput]
    I2 --> J2[hasAgentOutput1]

    J -->|Has Output| K[Send WhatsApp response via Twilio]
    J -->|No Output| L[logError]
    J2 -->|Has Output| K2[Send WhatsApp response via Twilio1]
    J2 -->|No Output| L2[logError1]

    L --> M[setFallbackMessage]
    L2 --> M2[setFallbackMessage1]

    M --> N[sendFallbackWhatsApp]
    M2 --> N2[sendFallbackWhatsApp1]

Trigger

  • Type: Webhook (HTTP POST)
  • Development Path: /98ed6d7d-5af1-4500-878f-56b7f22cad75
  • Production Path: /kdpwaba
  • Source: Twilio WhatsApp webhook notifications

Nodes Used

Node Type Count Purpose
Webhook 2 Receive incoming WhatsApp messages from Twilio
PostgreSQL 8 Database operations (user lookup, logging, message storage)
If 6 Conditional logic for user validation and message routing
Twilio 6 Send WhatsApp responses and error messages
Set 4 Prepare data for agent processing and fallback messages
Execute Workflow 2 Call the Francis SalesTrackingAgent workflow
Sticky Note 3 Documentation and workflow organization

External Services & Credentials Required

Twilio

  • Credential Name: "Twilio WhatsApp kdp"
  • Purpose: Send and receive WhatsApp messages
  • Required: Account SID, Auth Token, WhatsApp phone number

PostgreSQL Database

  • Credential Name: "PostgresOnSupabase"
  • Purpose: User management and message logging
  • Required: Host, database name, username, password
  • Tables Used:
    • youthEntrepreneursReal - User profiles and status
    • pendingDaytimeMessages - Queued daytime messages
    • errorLog - Error tracking and debugging

Environment Variables

No explicit environment variables are configured in this workflow. All configuration is handled through: - Webhook paths (hardcoded) - Database credentials (stored in n8n credential system) - Twilio credentials (stored in n8n credential system)

Data Flow

Input

  • Source: Twilio WhatsApp webhook
  • Format: Form-encoded HTTP POST
  • Key Fields:
    • WaId: Sender's WhatsApp ID (phone number)
    • Body: Message content
    • To/From: WhatsApp phone numbers

Output

  • Primary: WhatsApp message response via Twilio
  • Secondary: Database records (user activity, pending messages, error logs)

Data Transformations

  1. Phone number formatting (adding/removing country codes)
  2. Timestamp conversion to Nairobi timezone
  3. Message content preparation for AI agent
  4. Error message localization (Swahili fallback)

Error Handling

The workflow implements comprehensive error handling:

  1. User Not Found: Sends informative message directing users to contact program coordinator
  2. Agent Failures: Catches errors from the SalesTrackingAgent workflow
  3. Empty Responses: Detects when agent returns no output
  4. Error Logging: Records all errors with context in database
  5. Fallback Messages: Sends polite Swahili message when processing fails
  6. Graceful Degradation: Continues execution even when error logging fails

Known Limitations

Based on the sticky notes in the workflow: - No integration with Slack for error notifications - Call center integration is explicitly noted as not implemented - Sales-related message handling may need refinement

  • Francis - SalesTrackingAgent (z3uutKAWYHk3qbQE): AI agent that processes user queries and generates responses

Setup Instructions

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

  2. Configure Credentials:

    • Create Twilio credential with WhatsApp-enabled phone number
    • Set up PostgreSQL connection to Supabase or similar database
  3. Database Setup: Ensure these tables exist:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    -- User profiles table
    CREATE TABLE "youthEntrepreneursReal" (
      id SERIAL PRIMARY KEY,
      "phoneNumber" VARCHAR(20),
      "eveningSessionStarted" BOOLEAN DEFAULT FALSE,
      "todayDataCollected" BOOLEAN DEFAULT FALSE,
      "lastInboundAt" TIMESTAMP,
      "onboardingStatus" VARCHAR(50)
    );
    
    -- Pending messages queue
    CREATE TABLE "pendingDaytimeMessages" (
      id SERIAL PRIMARY KEY,
      "createdAt" TIMESTAMP DEFAULT NOW(),
      "phoneNumber" VARCHAR(20),
      content TEXT,
      channel VARCHAR(20),
      "nairobiTime" TIMESTAMP,
      date DATE
    );
    
    -- Error logging
    CREATE TABLE "errorLog" (
      id SERIAL PRIMARY KEY,
      "createdAt" TIMESTAMP DEFAULT NOW(),
      "phoneNumber" VARCHAR(20),
      workflow VARCHAR(100),
      "errorMessage" TEXT,
      "rawInput" TEXT
    );
    

  4. Webhook Configuration:

    • Configure Twilio webhook to point to your n8n webhook URLs
    • Use development webhook for testing
    • Switch to production webhook for live deployment
  5. Dependent Workflow: Ensure the "Francis - SalesTrackingAgent" workflow is imported and active

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

  7. Monitoring: Check the errorLog table regularly for any processing issues