Skip to content

WhatsApp Trigger - Francis

This workflow serves as the main entry point for WhatsApp messages in a youth entrepreneur coaching system. It receives incoming WhatsApp messages via Twilio webhook, validates users against a database, implements time-based message handling, 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.

Based on the workflow structure, this appears to be part of a youth entrepreneur support system that: - Provides WhatsApp-based coaching and support to registered youth entrepreneurs - Implements business hours logic to queue messages received during daytime - Uses AI agents to provide intelligent responses to user queries - Maintains user engagement tracking and error logging

How It Works

  1. Message Reception: Receives incoming WhatsApp messages through a Twilio webhook
  2. User Validation: Looks up the sender's phone number in the youth entrepreneurs database
  3. Access Control: Rejects messages from unregistered users with an error message
  4. Activity Tracking: Updates the user's last inbound message timestamp
  5. Time-Based Routing: Checks if it's daytime (before 7 PM) and if the user hasn't started an evening session
  6. Message Queuing: Stores daytime messages in a pending queue for later processing
  7. AI Processing: Routes evening messages or active session messages to the Francis Sales Tracking Agent
  8. Response Delivery: Sends the AI agent's response back via WhatsApp
  9. Error Handling: Logs errors and sends fallback messages in Swahili when the AI agent fails

Workflow Diagram

graph TD
    A[Webhook] --> B[getUserRecord]
    B --> C[ifUserNotFound]
    C -->|User Not Found| D[userNotFound]
    C -->|User Found| E[updateLastInboundAt]
    E --> F[isDaytimeMessage]
    F -->|Daytime & No Evening Session| G[storeDaytimeMessage]
    F -->|Evening or Active Session| H[setUserPhoneNumnberAndQuery]
    H --> I[Call Francis - SalesTrackingAgent]
    I --> J[hasAgentOutput]
    J -->|Has Output| K[Send WhatsApp response via Twilio]
    J -->|No Output| L[logError]
    I -->|Error| L
    L --> M[setFallbackMessage]
    M --> N[sendFallbackWhatsApp]

Trigger

Webhook: Listens for POST requests from Twilio WhatsApp webhook at endpoint 98ed6d7d-5af1-4500-878f-56b7f22cad75

The webhook receives Twilio WhatsApp message data including sender phone number, message content, and metadata.

Nodes Used

Node Type Node Name Purpose
Webhook Webhook Receives incoming WhatsApp messages from Twilio
PostgreSQL getUserRecord Queries user database to validate sender
If ifUserNotFound Checks if user exists in system
Twilio userNotFound Sends rejection message to unregistered users
PostgreSQL updateLastInboundAt Updates user's last activity timestamp
If isDaytimeMessage Determines if message should be queued or processed
PostgreSQL storeDaytimeMessage Stores daytime messages for later processing
Set setUserPhoneNumnberAndQuery Prepares data for AI agent
Execute Workflow Call 'Francis - SalesTrackingAgent' Routes to AI processing workflow
If hasAgentOutput Validates AI agent response
Twilio Send WhatsApp response via Twilio Sends AI response to user
PostgreSQL logError Records errors for debugging
Set setFallbackMessage Creates fallback message in Swahili
Twilio sendFallbackWhatsApp Sends fallback message on errors

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 validation, activity tracking, message queuing, error logging
  • Required: Database connection string, username, password

Required Database Tables

  • youthEntrepreneursReal: User records with phone numbers and session status
  • pendingDaytimeMessages: Queue for messages received during business hours
  • errorLog: Error tracking and debugging

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 WhatsApp webhook payload containing:
    • WaId: Sender's phone number
    • Body: Message content
    • To/From: WhatsApp number routing information

Output

  • WhatsApp response message sent back to user
  • Database updates for user activity tracking
  • Error logs for failed processing attempts
  • Queued messages for daytime processing

Internal Data

  • User validation results from database
  • Time-based routing decisions
  • AI agent responses
  • Error states and fallback messages

Error Handling

The workflow implements comprehensive error handling:

  1. User Not Found: Sends polite rejection message asking user to contact program coordinator
  2. AI Agent Failures: Catches errors from the sales tracking agent and logs them
  3. Empty Responses: Detects when AI agent returns no output and treats as error
  4. Database Errors: Continues execution even if database operations fail
  5. Fallback Messaging: Sends Swahili apology message when primary processing fails
  6. Error Logging: Records all errors with context for debugging

Known Limitations

Based on the sticky notes in the workflow: - Error notifications are not sent to Slack channels (planned feature) - Call center integration is mentioned but not implemented - Sales vs. advice message classification needs improvement

  • 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 Twilio Credentials:

    • Create Twilio account with WhatsApp Business API access
    • Add credential "Twilio WhatsApp kdp" with Account SID and Auth Token
    • Configure webhook URL in Twilio console
  3. Setup PostgreSQL Database:

    • Create Supabase account or setup PostgreSQL instance
    • Add credential "PostgresOnSupabase" with connection details
    • Create required tables:
       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
      -- Users table
      CREATE TABLE "youthEntrepreneursReal" (
        id SERIAL PRIMARY KEY,
        "phoneNumber" VARCHAR(20),
        "eveningSessionStarted" BOOLEAN DEFAULT FALSE,
        "todayDataCollected" BOOLEAN DEFAULT FALSE,
        "lastInboundAt" TIMESTAMP,
        "onboardingStatus" VARCHAR(50)
      );
      
      -- Message queue table
      CREATE TABLE "pendingDaytimeMessages" (
        id SERIAL PRIMARY KEY,
        "createdAt" TIMESTAMP DEFAULT NOW(),
        "phoneNumber" VARCHAR(20),
        content TEXT,
        channel VARCHAR(20)
      );
      
      -- Error logging table
      CREATE TABLE "errorLog" (
        id SERIAL PRIMARY KEY,
        "createdAt" TIMESTAMP DEFAULT NOW(),
        "phoneNumber" VARCHAR(20),
        workflow VARCHAR(100),
        "errorMessage" TEXT,
        "rawInput" TEXT
      );
      
  4. Deploy Francis - SalesTrackingAgent: Ensure the referenced workflow is available and properly configured

  5. Test Integration: Send a test WhatsApp message to verify the complete flow

  6. Monitor Logs: Check the errorLog table for any issues during initial deployment