V4 - WhatsAppTrigger¶
This workflow serves as the main entry point for WhatsApp messages in a youth entrepreneurship program, handling user authentication, message routing, and intelligent response generation through AI agents while managing daytime message queuing and error handling.
Purpose¶
No business context provided yet — add a context.md to enrich this documentation.
How It Works¶
- Message Reception: Receives WhatsApp messages via webhook from Twilio
- User Validation: Looks up the sender's phone number in the youth entrepreneurs database
- Authentication Check: If user not found, sends an error message and stops processing
- Activity Tracking: Updates the user's last inbound message timestamp
- Time-Based Routing: Checks if it's daytime (4 AM - 7 PM Nairobi time) and user hasn't started evening session
- Message Storage: If daytime, stores message for later processing instead of immediate response
- Message Processing: For evening messages or active sessions, extracts user query and phone number
- Workflow Routing: Determines if message is for weekly reporting or general sales tracking
- AI Agent Processing: Routes to appropriate agent workflow (Weekly Report Handler or Sales Tracking Agent)
- Response Formatting: Processes agent output through Message Interceptor for proper formatting
- Message Delivery: Sends response via WhatsApp, supporting both regular messages and interactive templates
- Error Handling: Logs errors and sends fallback messages in Swahili when processing fails
- Chat Logging: Records all conversations for audit and analysis purposes
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/Active| 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 -->|Regular| R[Send WhatsApp response via Twilio]
O --> S[setFallbackMessage]
S --> T[sendFallbackWhatsApp]
S --> U[logChatFallback]
Trigger¶
Webhook Trigger: Listens for POST requests at path 98ed6d7d-5af1-4500-878f-56b7f22cad75 from Twilio WhatsApp webhook notifications.
Nodes Used¶
| Node Type | Node Name | Purpose |
|---|---|---|
| Webhook | DevelopmentWebhook | Receives WhatsApp messages from Twilio |
| Postgres | getUserRecord | Looks up user by phone number |
| If | ifUserNotFound | Checks if user exists in database |
| Twilio | userNotFound | Sends error message for unknown users |
| Postgres | updateLastInboundAt | Updates user's last message timestamp |
| If | isDaytimeMessage | Checks time and session status |
| Postgres | storeDaytimeMessage | Stores daytime messages for later |
| Set | setUserPhoneNumnberAndQuery | Prepares user data for processing |
| If | isWeeklyReport | Routes weekly report messages |
| Set | Set WR Input | Formats weekly report input |
| Execute Workflow | Call Weekly Report Handler | Processes weekly reports |
| Execute Workflow | Call Francis - SalesTrackingAgent | Handles general queries |
| If | hasAgentOutput | Validates agent response |
| Execute Workflow | Call V4 - MessageInterceptor | Formats responses |
| If | isInteractive? | Checks for template responses |
| HTTP Request | sendTemplate | Sends WhatsApp templates |
| Twilio | Send WhatsApp response via Twilio | Sends regular messages |
| Postgres | logError | Records processing errors |
| Set | setFallbackMessage | Creates fallback response |
| Twilio | sendFallbackWhatsApp | Sends error messages |
| Postgres | logChatFallback | Logs fallback conversations |
External Services & Credentials Required¶
Twilio¶
- Purpose: WhatsApp message sending and receiving
- Credentials:
- Twilio API credentials (Account SID, Auth Token)
- Twilio Basic Auth for template messages
- Configuration: WhatsApp Business Account with approved templates
PostgreSQL Database¶
- Purpose: User data, message storage, error logging, chat history
- Credentials: Database connection (host, username, password, database name)
- Required Tables:
v4_youthEntrepreneurs- User profiles and statusv4_pendingDaytimeMessages- Queued daytime messageserrorLog- Error trackingv4_chatLog- Conversation history
Environment Variables¶
No explicit environment variables are defined in this workflow. Configuration is handled through: - n8n credential system for database and API access - Hardcoded webhook paths and Twilio account references - Timezone settings (Africa/Nairobi) for time-based logic
Data Flow¶
Input¶
- WhatsApp Message Data: Phone number, message content, interactive data, Twilio metadata
- Expected Format: Twilio webhook payload with
WaId,Body,To,Fromfields
Output¶
- WhatsApp Responses: Text messages or interactive templates sent back to users
- Database Records: Updated user activity, stored messages, error logs, chat history
- Error Notifications: Fallback messages in Swahili when processing fails
Data Transformations¶
- Phone number formatting (adding/removing country codes)
- Message content extraction (text or interactive data)
- Timezone conversion for Nairobi time
- Agent response formatting through Message Interceptor
Error Handling¶
The workflow includes comprehensive error handling:
- User Not Found: Sends polite error message asking to contact program coordinator
- Agent Processing Errors: Catches failures in AI agent workflows and logs details
- Empty Agent Responses: Detects when agents return no output and triggers fallback
- Database Error Resilience: Continues execution even if error logging fails
- Fallback Messages: Provides Swahili error message when all else fails
- Error Logging: Records phone number, workflow name, error details, and raw input 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 - Some features are marked as work-in-progress or incomplete
Related Workflows¶
This workflow integrates with several other workflows:
- V4 - WIP - Francis - SalesTrackingAgent (xtOmBg6ht3gq931x): Handles general user queries
- Weekly Report Handler (SlShcSkVHkkJ54wK): Processes weekly business reports
- V4 - MessageInterceptor (KREp86iqWq4YMW6k): Formats and validates responses
Setup Instructions¶
- Import Workflow: Import the JSON into your n8n instance
- Configure Database Credentials:
- Set up PostgreSQL connection named "Postgres account"
- Ensure required tables exist with proper schema
- Configure Twilio Credentials:
- Add "Twilio account" API credentials
- Add "Twilio Basic Auth" for template messages
- Update Account SID in HTTP request node if different
- Set Up Webhook:
- Note the webhook URL from the DevelopmentWebhook node
- Configure Twilio WhatsApp webhook to POST to this URL
- Verify Related Workflows:
- Ensure referenced workflows are imported and active
- Update workflow IDs if they differ in your instance
- Test Integration:
- Send test WhatsApp message to verify end-to-end flow
- Check database tables for proper data recording
- Verify error handling with invalid inputs
- Monitor and Adjust:
- Review error logs regularly
- Adjust time-based logic for your timezone if needed
- Customize fallback messages for your program language