WhatsApp Trigger Workflow¶
This workflow processes incoming WhatsApp messages for a youth entrepreneurship program, routing messages to appropriate handlers based on user status and message timing, while maintaining comprehensive logging and error handling.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
Based on the workflow structure, this appears to serve participants in a youth entrepreneurship program by: - Processing WhatsApp messages during business hours (4 AM - 7 PM Nairobi time) - Validating users against a program database - Routing weekly report submissions to specialized handlers - Providing AI-powered responses through integrated agents - Maintaining audit trails of all interactions
How It Works¶
- Message Reception: Receives WhatsApp messages via Twilio webhook
- User Validation: Checks if the sender's phone number exists in the youth entrepreneurs database
- Access Control: Rejects messages from unregistered users with an error message
- Activity Tracking: Updates the user's last inbound message timestamp
- Time-Based Routing: During business hours (4 AM - 7 PM Nairobi time), stores messages for later processing if evening sessions haven't started
- Message Classification: Determines if the message is a weekly report submission based on user's current stage
- Specialized Routing: Routes weekly reports to a dedicated handler workflow
- AI Processing: Sends other messages to the Francis SalesTrackingAgent for intelligent responses
- Response Delivery: Sends AI-generated responses back via WhatsApp
- Error Handling: Logs errors and sends fallback messages in Swahili when processing fails
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 & No Evening Session| G[storeDaytimeMessage1]
F -->|Process Now| H[setUserPhoneNumnberAndQuery1]
G --> H
H --> I[isWeeklyReport1]
I -->|Weekly Report| J[Set WR Input1]
I -->|Regular Message| K[Call Francis SalesTrackingAgent1]
J --> L[Call Weekly Report Handler1]
L --> M[hasAgentOutput1]
K --> M
K -->|Error| N[logError1]
M -->|Has Output| O[Send WhatsApp response via Twilio1]
M -->|No Output| N
N --> P[setFallbackMessage1]
P --> Q[sendFallbackWhatsApp1]
P --> R[logChatFallback1]
Trigger¶
Webhook: POST endpoint at path 23dd4bb2-c037-4603-8483-d52e2faecf48
- Receives WhatsApp message data from Twilio
- Expects JSON payload with message content, sender phone number, and recipient information
Nodes Used¶
| Node Type | Node Name | Purpose |
|---|---|---|
| Webhook | productionWebhook | Receives incoming WhatsApp messages from Twilio |
| Postgres | getUserRecord1 | Queries user database to validate sender |
| If | ifUserNotFound1 | Checks if user exists in system |
| Twilio | userNotFound1 | Sends rejection message to unregistered users |
| Postgres | updateLastInboundAt1 | Updates user's last message timestamp |
| If | isDaytimeMessage1 | Determines if message should be processed immediately |
| Postgres | storeDaytimeMessage1 | Stores daytime messages for later processing |
| Set | setUserPhoneNumnberAndQuery1 | Prepares user data for processing |
| If | isWeeklyReport1 | Identifies weekly report submissions |
| Set | Set WR Input1 | Formats data for weekly report handler |
| Execute Workflow | Call Weekly Report Handler1 | Processes weekly report submissions |
| Execute Workflow | Call Francis SalesTrackingAgent1 | Processes regular messages with AI |
| If | hasAgentOutput1 | Validates AI response exists |
| Twilio | Send WhatsApp response via Twilio1 | Sends AI response to user |
| Postgres | logError1 | Records processing errors |
| Set | setFallbackMessage1 | Creates fallback message in Swahili |
| Twilio | sendFallbackWhatsApp1 | Sends fallback message (disabled) |
| Postgres | 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 validation, message storage, error logging
- Required: Database connection string, username, password
- Tables Used:
youthEntrepreneursReal- User records and statuspendingDaytimeMessages- Queued messageserrorLog- Error trackingchatLog- Conversation history
Environment Variables¶
The workflow uses Africa/Nairobi timezone for time-based operations. No explicit environment variables are referenced, but the following may be configured at the n8n instance level: - Database connection parameters - Twilio API credentials - Webhook security settings
Data Flow¶
Input¶
- WhatsApp Message Data (via webhook):
body.WaId: Sender's WhatsApp ID (phone number)body.Body: Message contentbody.To: Recipient WhatsApp numberbody.From: Sender WhatsApp number
Processing¶
- User validation against database
- Time-based message queuing
- Message classification (weekly report vs. general)
- AI processing for responses
Output¶
- WhatsApp Response: AI-generated or fallback message sent to user
- Database Records: Updated user activity, stored messages, error logs
- Audit Trail: Complete conversation history in chat log
Error Handling¶
The workflow implements comprehensive error handling:
- User Validation Errors: Unregistered users receive a polite rejection message
- AI Processing Failures: Captured and logged with fallback message in Swahili
- Database Errors: Retry logic with 2 attempts and 3-second delays
- Empty Responses: Detected and treated as errors with appropriate logging
- Fallback Message: "Samahani, kuna tatizo kidogo kwa sasa..." (Swahili apology with support contact)
All errors are logged to the errorLog table with:
- Phone number
- Workflow name
- Error message
- Raw input content
Known Limitations¶
Based on the sticky notes in the workflow: - Call center integration is planned but not implemented ("no call center people") - Slack error notifications are planned but not yet implemented - Sales-related message detection and generic responses are planned features - The fallback WhatsApp sender is currently disabled
Related Workflows¶
- Francis - SalesTrackingAgent (
aygyT37fIK22WZ9a): Processes general user queries with AI - Weekly Report Handler (
SlShcSkVHkkJ54wK): Handles weekly report submissions - Error Workflow (
cuHEGQjAfvuGwIOD): Global error handling workflow
Setup Instructions¶
-
Import Workflow: Import the JSON into your n8n instance
-
Configure Credentials:
- Set up PostgreSQL connection with access to required tables
- Configure Twilio API credentials with WhatsApp capabilities
-
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 31 32 33 34 35 36 37 38
-- User records table CREATE TABLE "youthEntrepreneursReal" ( id SERIAL PRIMARY KEY, "phoneNumber" VARCHAR(20), "eveningSessionStarted" BOOLEAN, "currentStage" VARCHAR(100), "lastInboundAt" TIMESTAMP ); -- Message queue table CREATE TABLE "pendingDaytimeMessages" ( id SERIAL PRIMARY KEY, "phoneNumber" VARCHAR(20), content TEXT, channel VARCHAR(20), "nairobiTime" TIMESTAMP, date DATE ); -- Error logging table CREATE TABLE "errorLog" ( id SERIAL PRIMARY KEY, "phoneNumber" VARCHAR(20), workflow VARCHAR(100), "errorMessage" TEXT, "rawInput" TEXT, "createdAt" TIMESTAMP DEFAULT NOW() ); -- Chat history table CREATE TABLE "chatLog" ( id SERIAL PRIMARY KEY, "userPhone" VARCHAR(20), "userQuery" TEXT, "agentResponse" TEXT, channel VARCHAR(20), created_at TIMESTAMP DEFAULT NOW() ); -
Webhook Configuration:
- Configure Twilio webhook to point to the n8n webhook URL
- Ensure webhook path matches:
23dd4bb2-c037-4603-8483-d52e2faecf48
-
Related Workflows: Import and configure the dependent workflows:
- Francis - SalesTrackingAgent
- Weekly Report Handler
-
Activate Workflow: Enable the workflow to start processing WhatsApp messages
-
Test: Send a test WhatsApp message from a registered user to verify the complete flow