Skip to content

WhatsApp Trigger - Francis

This workflow serves as the main entry point for WhatsApp messages, handling incoming messages from users, validating their registration status, managing daytime message queuing, and routing queries to an AI sales tracking agent for intelligent responses.

Purpose

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

This workflow appears to be designed for a youth entrepreneurship program that provides WhatsApp-based support and coaching. It handles incoming WhatsApp messages from registered participants, validates their enrollment status, manages time-based message routing (storing daytime messages for later processing), and provides AI-powered responses through a sales tracking agent.

How It Works

  1. Message Reception: The workflow receives incoming WhatsApp messages through Twilio webhooks (both development and production endpoints)
  2. User Validation: Looks up the sender's phone number in the youthEntrepreneursReal database table to verify they're a registered participant
  3. Registration Check: If the user isn't found, sends an error message directing them to contact their program coordinator
  4. Activity Tracking: Updates the user's lastInboundAt timestamp to track engagement
  5. Time-Based Routing: Checks if it's daytime (4 AM - 7 PM) and if the user hasn't started an evening session
  6. Message Storage: For daytime messages, stores them in pendingDaytimeMessages table for later processing
  7. AI Processing: For evening messages or immediate processing, forwards the query to the "Francis - SalesTrackingAgent" workflow
  8. Response Handling: Validates the AI agent's response and sends it back via WhatsApp
  9. Error Management: Logs errors to the database and sends fallback messages in Swahili when the AI agent fails

Mermaid Diagram

graph TD
    A[DevelopmentWebhook] --> B[getUserRecord]
    A2[productionWebhook] --> B2[getUserRecord1]

    B --> C[ifUserNotFound]
    B2 --> C2[ifUserNotFound1]

    C -->|User Not Found| D[userNotFound]
    C -->|User Found| E[updateLastInboundAt]
    C2 -->|User Not Found| D2[userNotFound1]
    C2 -->|User Found| E2[updateLastInboundAt1]

    E --> F[isDaytimeMessage]
    E2 --> F2[isDaytimeMessage1]

    F -->|Daytime| G[storeDaytimeMessage]
    F -->|Evening/Night| H[setUserPhoneNumnberAndQuery]
    F2 -->|Daytime| G2[storeDaytimeMessage1]
    F2 -->|Evening/Night| H2[setUserPhoneNumnberAndQuery1]

    G --> H
    G2 --> H2

    H --> I[Call 'Francis - SalesTrackingAgent']
    H2 --> I2[Call 'Francis - SalesTrackingAgent'1]

    I --> J[hasAgentOutput]
    I2 --> J2[hasAgentOutput1]

    J -->|Has Output| K[Send WhatsApp response via Twilio]
    J -->|No Output| L[logError]
    J2 -->|Has Output| K2[Send WhatsApp response via Twilio1]
    J2 -->|No Output| L2[logError1]

    L --> M[setFallbackMessage]
    L2 --> M2[setFallbackMessage1]

    M --> N[sendFallbackWhatsApp]
    M2 --> N2[sendFallbackWhatsApp1]

Trigger

The workflow is triggered by incoming HTTP POST requests to two webhook endpoints: - Development: /webhook/98ed6d7d-5af1-4500-878f-56b7f22cad75 - Production: /webhook/kdpwaba

These webhooks receive WhatsApp message data from Twilio when users send messages to the configured WhatsApp business number.

Nodes Used

Node Type Purpose
Webhook Receives incoming WhatsApp messages from Twilio
PostgreSQL Queries user records, updates activity timestamps, stores daytime messages, logs errors
If Conditional logic for user validation, time-based routing, and response validation
Set Prepares user data for the AI agent workflow
Execute Workflow Calls the Francis - SalesTrackingAgent workflow for AI-powered responses
Twilio Sends WhatsApp responses and error messages back to users
Sticky Note Documentation and development notes

External Services & Credentials Required

Twilio

  • Credential Name: "Twilio WhatsApp kdp"
  • Purpose: Sending WhatsApp messages
  • Required: Account SID, Auth Token, WhatsApp-enabled phone number

PostgreSQL Database

  • Credential Name: "PostgresOnSupabase"
  • Purpose: User data storage and message management
  • Required: Database connection string, username, password
  • Tables Used:
    • youthEntrepreneursReal: User registration and status data
    • pendingDaytimeMessages: Temporary storage for daytime messages
    • errorLog: Error tracking and debugging

Environment Variables

No explicit environment variables are configured in this workflow. All configuration is handled through n8n credentials and direct node parameters.

Data Flow

Input

  • WhatsApp Message Data (from Twilio webhook):
    • WaId: Sender's phone number
    • Body: Message content
    • To/From: WhatsApp number routing information
    • Various Twilio metadata fields

Output

  • WhatsApp Response Messages: AI-generated responses or error messages sent back to users
  • Database Records:
    • Updated user activity timestamps
    • Stored daytime messages for later processing
    • Error logs for troubleshooting

Internal Data Processing

  • User phone numbers are formatted with '+' prefix for database queries
  • Message content and metadata are passed to the AI agent workflow
  • Timestamps are converted to local Nairobi time for storage

Error Handling

The workflow includes comprehensive error handling:

  1. User Not Found: Sends a message directing users to contact their program coordinator
  2. AI Agent Failures: Catches errors from the SalesTrackingAgent workflow and logs them to the database
  3. Empty AI Responses: Validates that the AI agent returns meaningful output
  4. Fallback Messaging: Sends a Swahili apology message when the AI agent fails: "Samahani, kuna tatizo kidogo. Tafadhali jaribu tena baadaye. 🙏"
  5. Database Error Logging: Records error details including phone number, workflow name, error message, and raw input
  6. Graceful Degradation: Uses onError: "continueErrorOutput" to ensure the workflow continues even when individual nodes fail

Known Limitations

Based on the sticky notes in the workflow, there are several known limitations and planned improvements:

  • Error notifications are not currently sent to Slack channels for team awareness
  • The workflow treats all users as WhatsApp users (no call center integration planned)
  • Sales-related data handling may need refinement for different types of queries
  • The daytime message storage system requires a separate workflow to process stored messages
  • Francis - SalesTrackingAgent (z3uutKAWYHk3qbQE): The AI agent workflow that processes user queries and generates responses

Setup Instructions

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

  2. Configure Twilio Credentials:

    • Create a new Twilio credential named "Twilio WhatsApp kdp"
    • Add your Twilio Account SID and Auth Token
    • Ensure your Twilio account has WhatsApp messaging enabled
  3. Configure Database Credentials:

    • Create a PostgreSQL credential named "PostgresOnSupabase"
    • Configure connection to your database with the 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
      -- 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)
      );
      
      -- Daytime messages storage
      CREATE TABLE "pendingDaytimeMessages" (
        id SERIAL PRIMARY KEY,
        "createdAt" TIMESTAMP DEFAULT NOW(),
        "phoneNumber" VARCHAR(20),
        content TEXT,
        channel VARCHAR(20),
        "nairobiTime" TIMESTAMP,
        date DATE
      );
      
      -- Error logging
      CREATE TABLE "errorLog" (
        id SERIAL PRIMARY KEY,
        "createdAt" TIMESTAMP DEFAULT NOW(),
        "phoneNumber" VARCHAR(20),
        workflow VARCHAR(100),
        "errorMessage" TEXT,
        "rawInput" TEXT
      );
      
  4. Set Up Webhook URLs:

    • Configure your Twilio WhatsApp webhook to point to the production webhook URL
    • Use the development webhook for testing
  5. Deploy Related Workflows:

    • Ensure the "Francis - SalesTrackingAgent" workflow is imported and configured
    • Verify the workflow ID matches the one referenced in the Execute Workflow nodes
  6. Test the Integration:

    • Send a test message to your WhatsApp business number
    • Verify user lookup, message processing, and response delivery work correctly
    • Check error logging functionality with invalid inputs