Skip to content

WhatsApp Trigger Workflow

This workflow processes incoming WhatsApp messages from youth entrepreneurs, validates users against a database, handles time-based message routing, and delegates responses to specialized AI agents for business coaching and weekly report collection.

Purpose

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

Based on the workflow structure, this appears to serve youth entrepreneurs in a coaching program by: - Providing 24/7 WhatsApp support with intelligent routing - Collecting and processing weekly business reports - Offering sales tracking and business advice through AI agents - Managing user validation and program enrollment status

How It Works

  1. Message Reception: Receives WhatsApp messages via Twilio webhook
  2. User Validation: Checks if the sender's phone number exists in the youth entrepreneurs database
  3. Time-Based Routing: During daytime hours (4 AM - 7 PM Nairobi time), messages are stored for later processing unless the user has started an evening session
  4. Message Classification: Determines if the message is related to weekly reporting or general business queries
  5. Agent Routing: Routes weekly reports to a specialized handler, other queries to the sales tracking agent
  6. Response Delivery: Sends AI-generated responses back via WhatsApp
  7. Error Handling: Logs errors and sends fallback messages in Swahili when agents fail

Workflow Diagram

graph TD
    A[productionWebhook] --> B[getUserRecord1]
    B --> C[ifUserNotFound1]
    C -->|User Not Found| D[userNotFound1]
    C -->|User Found| E[updateLastInboundAt1]
    E --> F[isDaytimeMessage1]
    F -->|Daytime| G[storeDaytimeMessage1]
    F -->|Evening/Night| H[setUserPhoneNumnberAndQuery1]
    G --> H
    H --> I[isWeeklyReport1]
    I -->|Weekly Report| J[Set WR Input1]
    I -->|General Query| K[Call 'Francis - SalesTrackingAgent'1]
    J --> L[Call Weekly Report Handler1]
    L --> M[hasAgentOutput1]
    K --> M
    M -->|Has Output| N[Send WhatsApp response via Twilio1]
    M -->|No Output| O[logError1]
    O --> P[setFallbackMessage1]
    P --> Q[sendFallbackWhatsApp1]
    P --> R[logChatFallback1]

Trigger

Webhook: POST endpoint at path 23dd4bb2-c037-4603-8483-d52e2faecf48 that receives WhatsApp message data from Twilio.

Expected payload includes: - body.WaId: Sender's WhatsApp ID (phone number) - body.Body: Message content - body.To: Recipient number (your WhatsApp Business number) - body.From: Sender's full WhatsApp identifier

Nodes Used

Node Type Node Name Purpose
Webhook productionWebhook Receives incoming WhatsApp messages
PostgreSQL getUserRecord1 Queries user database by phone number
If ifUserNotFound1 Checks if user exists in system
Twilio userNotFound1 Sends "not found" message to unregistered users
PostgreSQL updateLastInboundAt1 Updates user's last contact timestamp
If isDaytimeMessage1 Checks if message is during business hours
PostgreSQL storeDaytimeMessage1 Stores daytime messages for later processing
Set setUserPhoneNumnberAndQuery1 Prepares user data for agent processing
If isWeeklyReport1 Determines if message is weekly report related
Set Set WR Input1 Formats input for weekly report handler
Execute Workflow Call Weekly Report Handler1 Processes weekly reports
Execute Workflow Call 'Francis - SalesTrackingAgent'1 Handles general business queries
If hasAgentOutput1 Validates agent response exists
Twilio Send WhatsApp response via Twilio1 Sends successful responses
PostgreSQL logError1 Records errors to database
Set setFallbackMessage1 Creates fallback message in Swahili
Twilio sendFallbackWhatsApp1 Sends error fallback (disabled)
PostgreSQL logChatFallback1 Logs fallback interactions

External Services & Credentials Required

Twilio

  • Credential ID: dEOy4AckE29MTkk3
  • Purpose: Send and receive WhatsApp messages
  • Required: Account SID, Auth Token, WhatsApp-enabled phone number

PostgreSQL Database

  • Credential ID: EJPqF6MDH1ZwAzyv
  • Purpose: User management, message logging, error tracking
  • Required Tables:
    • youthEntrepreneursReal: User profiles and program status
    • pendingDaytimeMessages: Queued messages during business hours
    • errorLog: Error tracking and debugging
    • chatLog: Conversation history

Environment Variables

The workflow uses timezone-aware processing: - Timezone: Africa/Nairobi - Business Hours: 4 AM - 7 PM (19:00) Nairobi time - Error Workflow: cuHEGQjAfvuGwIOD (handles workflow-level failures)

Data Flow

Input (Webhook)

1
2
3
4
5
6
7
8
{
  "body": {
    "WaId": "+254712345678",
    "Body": "I need help with my sales report",
    "To": "whatsapp:+254700000000",
    "From": "whatsapp:+254712345678"
  }
}

Output (WhatsApp Response)

  • AI-generated business advice or weekly report guidance
  • Fallback message in Swahili if agents fail: "Samahani, kuna tatizo kidogo kwa sasa..."

Database Updates

  • User's lastInboundAt timestamp
  • Message logs in chatLog table
  • Error logs in errorLog table
  • Daytime message queue in pendingDaytimeMessages

Error Handling

The workflow includes comprehensive error handling:

  1. User Validation: Unregistered users receive a polite rejection message
  2. Agent Failures: When AI agents fail or return empty responses:
    • Errors are logged to the database with phone number, workflow name, and error details
    • Users receive a fallback message in Swahili with contact information
    • Interactions are logged for follow-up
  3. Database Retries: PostgreSQL operations retry up to 2 times with 3-second delays
  4. Workflow-Level Errors: Routed to error workflow cuHEGQjAfvuGwIOD

Known Limitations

Based on the sticky notes in the workflow: - Call center integration is not implemented ("no call center people") - Slack error notifications are planned but not yet implemented - Sales-related message filtering needs enhancement - The fallback WhatsApp sender is currently disabled

  • Francis - SalesTrackingAgent (aygyT37fIK22WZ9a): Handles general business queries and sales advice
  • Weekly Report Handler (SlShcSkVHkkJ54wK): Processes weekly business reports from entrepreneurs
  • Error Handler (cuHEGQjAfvuGwIOD): Manages workflow-level failures

Setup Instructions

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

  2. Configure Credentials:

    • Set up Twilio credentials with WhatsApp Business API access
    • Configure PostgreSQL connection to your database
  3. Database Setup: 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
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    -- User profiles table
    CREATE TABLE "youthEntrepreneursReal" (
      id SERIAL PRIMARY KEY,
      "phoneNumber" VARCHAR(20) UNIQUE,
      "eveningSessionStarted" BOOLEAN DEFAULT FALSE,
      "currentStage" VARCHAR(100),
      "lastInboundAt" TIMESTAMP,
      -- other user fields...
    );
    
    -- Message queue for daytime messages
    CREATE TABLE "pendingDaytimeMessages" (
      id SERIAL PRIMARY KEY,
      "phoneNumber" VARCHAR(20),
      content TEXT,
      channel VARCHAR(20),
      "nairobiTime" TIMESTAMP,
      date DATE,
      "createdAt" TIMESTAMP DEFAULT NOW()
    );
    
    -- Error logging
    CREATE TABLE "errorLog" (
      id SERIAL PRIMARY KEY,
      "phoneNumber" VARCHAR(20),
      workflow VARCHAR(100),
      "errorMessage" TEXT,
      "rawInput" TEXT,
      "createdAt" TIMESTAMP DEFAULT NOW()
    );
    
    -- Chat history
    CREATE TABLE "chatLog" (
      id SERIAL PRIMARY KEY,
      "userPhone" VARCHAR(20),
      "userQuery" TEXT,
      "agentResponse" TEXT,
      channel VARCHAR(20),
      created_at TIMESTAMP DEFAULT NOW()
    );
    

  4. Webhook Configuration:

    • Copy the webhook URL from the productionWebhook node
    • Configure it in your Twilio WhatsApp settings as the message webhook
  5. Deploy Related Workflows: Ensure the Francis SalesTrackingAgent and Weekly Report Handler workflows are deployed and active

  6. Test: Send a test WhatsApp message from a registered phone number to verify the complete flow