Skip to content

V4 - WhatsAppTrigger

This workflow processes incoming WhatsApp messages for youth entrepreneurs in a coaching program, routing them through appropriate AI agents based on their current stage and message content, while handling daytime message queuing and error scenarios with fallback responses.

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: - Processing WhatsApp messages through specialized AI agents - Managing weekly report submissions - Providing sales tracking and general coaching support - Ensuring 24/7 availability with intelligent message routing

How It Works

  1. Message Reception: Incoming WhatsApp messages trigger the workflow via webhook
  2. User Validation: The system checks if the sender's phone number exists in the youth entrepreneurs database
  3. Activity Tracking: Updates the user's last inbound message timestamp
  4. Daytime Message Handling: Messages sent during daytime hours (4 AM - 7 PM Nairobi time) when evening sessions haven't started are queued for later processing
  5. Message Routing: Based on the user's current stage, messages are routed to either:
    • Weekly Report Handler (for users in weekly report stages)
    • Francis SalesTrackingAgent (for general queries and sales-related content)
  6. Response Processing: Agent responses are processed through a MessageInterceptor for formatting
  7. Message Delivery: Responses are sent back via WhatsApp, supporting both text messages and interactive templates
  8. Error Handling: Failed processing triggers fallback messages and error logging
  9. Chat Logging: All interactions are logged for tracking and analysis

Workflow Diagram

graph TD
    A[DevelopmentWebhook] --> B[getUserRecord]
    B --> C[ifUserNotFound]
    C -->|User Not Found| D[userNotFound]
    C -->|User Found| E[updateLastInboundAt]
    E --> F[isDaytimeMessage]
    F -->|Daytime| G[storeDaytimeMessage]
    F -->|Evening/Night| H[setUserPhoneNumnberAndQuery]
    G --> H
    H --> I[isWeeklyReport]
    I -->|Weekly Report| J[Set WR Input]
    I -->|General Query| K[Call Francis - SalesTrackingAgent]
    J --> L[Call Weekly Report Handler]
    L --> M[hasAgentOutput]
    K --> M
    M -->|Has Output| N[Call V4 - MessageInterceptor]
    M -->|No Output| O[logError]
    N --> P[isInteractive?]
    P -->|Interactive| Q[sendTemplate]
    P -->|Text| R[Send WhatsApp response via Twilio]
    O --> S[setFallbackMessage]
    S --> T[sendFallbackWhatsApp]
    S --> U[logChatFallback]

Trigger

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

Nodes Used

Node Type Node Name Purpose
Webhook DevelopmentWebhook Receives incoming WhatsApp messages
PostgreSQL getUserRecord Retrieves user data from youth entrepreneurs table
If ifUserNotFound Checks if user exists in system
Twilio userNotFound Sends error message for unregistered users
PostgreSQL updateLastInboundAt Updates user's last activity timestamp
If isDaytimeMessage Determines if message is sent during daytime hours
PostgreSQL storeDaytimeMessage Queues daytime messages for later processing
Set setUserPhoneNumnberAndQuery Prepares user data for agent processing
If isWeeklyReport Routes weekly report messages
Set Set WR Input Formats input for weekly report handler
Execute Workflow Call Weekly Report Handler Processes weekly report submissions
Execute Workflow Call Francis - SalesTrackingAgent Handles general queries and sales tracking
If hasAgentOutput Validates agent response
Execute Workflow Call V4 - MessageInterceptor Formats agent responses
If isInteractive? Determines message type (template vs text)
HTTP Request sendTemplate Sends WhatsApp template messages
Twilio Send WhatsApp response via Twilio Sends text responses
PostgreSQL logError Records processing errors
Set setFallbackMessage Creates fallback response
Twilio sendFallbackWhatsApp Sends fallback message
PostgreSQL logChatFallback Logs fallback interactions

External Services & Credentials Required

Twilio WhatsApp API

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

PostgreSQL Database

  • Credential: sifaV4Dev
  • Purpose: Store user data, chat logs, and error logs
  • Required: Database connection string, username, password

HTTP Basic Auth (for Twilio API)

  • Purpose: Direct API calls to Twilio for template messages
  • Required: Twilio Account SID and Auth Token

Environment Variables

No explicit environment variables are defined in this workflow. Configuration is handled through: - Database connection credentials - Twilio API credentials - Webhook endpoint configuration

Data Flow

Input

  • WhatsApp webhook payload containing:
    • WaId: Sender's WhatsApp ID
    • Body: Message content
    • To/From: Phone number routing information
    • InteractiveData: Interactive message responses (optional)

Output

  • WhatsApp response messages (text or template)
  • Database records in:
    • v4_youthEntrepreneurs (activity updates)
    • v4_pendingDaytimeMessages (queued messages)
    • v4_chatLog (conversation history)
    • errorLog (error tracking)

Error Handling

The workflow includes comprehensive error handling:

  1. User Not Found: Sends informational message directing users to contact program coordinator
  2. Agent Processing Errors: Logs errors to database and sends fallback message in Swahili
  3. Fallback Response: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye. 🙏" (Sorry, there's a small problem. Please try again later.)
  4. Error Logging: Captures phone number, workflow name, error message, and raw input
  5. Continue on Error: Most nodes are configured to continue processing even if errors occur

Known Limitations

Based on the workflow structure and sticky notes: - Daytime message queuing logic may not be needed as Sifa V4 is active throughout - No call center integration (noted as "no call center people") - Error notifications to Slack channel are planned but not implemented - Sales-related responses use generic messaging rather than specialized handling

  • V4 - MessageInterceptor (s5k7iyzMK6cYVzAa): Formats and processes agent responses
  • Francis - SalesTrackingAgent (nyk5AWlf0hTWye5D): Handles sales tracking and general queries
  • Weekly Report Handler (liCqzaZwxr01Y1gx): Processes weekly report submissions

Setup Instructions

  1. Import Workflow: Import the JSON into your n8n instance
  2. Configure Database Credential:
    • Create PostgreSQL credential named sifaV4Dev
    • Ensure database contains required tables: v4_youthEntrepreneurs, v4_pendingDaytimeMessages, v4_chatLog, errorLog
  3. Configure Twilio Credential:
    • Create Twilio API credential named Twilio WhatsApp kdp
    • Set up WhatsApp Business API integration
  4. Set Up Webhook:
    • Configure WhatsApp webhook to POST to the webhook URL
    • Ensure webhook endpoint is accessible from Twilio
  5. Deploy Related Workflows:
    • Import and configure the three related workflows
    • Ensure they're active and properly credentialed
  6. Test Integration:
    • Send test WhatsApp message from registered phone number
    • Verify database logging and response delivery
  7. Monitor Error Logs: Regularly check the errorLog table for processing issues