Back to Templates

Smart Facebook Messenger Chatbot with Gemini AI, Message Batching and History

Last update

Last update 4 days ago

Share


🤖 Facebook Messenger Smart Chatbot – Batch, Format & Notify with n8n Data Table

by Nguyen Thieu Toan

Advanced AI-powered chatbot with intelligent message batching, session-aware conversation tracking, and natural Messenger integration


🌟 What Is This Workflow?

This is a production-ready, enterprise-grade chatbot solution built entirely in n8n, designed for seamless Facebook Messenger integration. It intelligently batches incoming messages, maintains deep conversation context across sessions, formats replies for Messenger's requirements, and delivers natural AI responses with human-like interactions.

Perfect for:

  • 💼 Business customer support automation
  • 🛒 E-commerce product inquiries and recommendations
  • 📅 Appointment scheduling and consultation booking
  • 🎓 Educational chatbots and training assistants
  • 🤝 Lead qualification and sales automation

Requires: n8n v1.113.0+ (for Data Table feature)


⚙️ Key Features

Core Capabilities

Feature Description
🔄 Smart Message Batching Groups consecutive user messages within 3 seconds into a single processing unit, preventing fragmented replies and reducing API costs
🧠 Session-Aware Context Distinguishes between old sessions (previous days) and current session (today), providing AI with rich temporal context
📋 Conversation History Tracking Stores complete chat logs in n8n Data Table with full CRUD operations, sorted by creation time with Vietnam timezone support
👀 Messenger UX Effects Implements "Seen" marker and "Typing..." indicator for natural, human-like responsiveness
🎯 AI Agent Integration Connects to Google Gemini, Groq, or any LLM with extensible system prompts for domain-specific consulting
📊 Advanced History Management Retrieves last 15 messages, sorts chronologically, and formats into session blocks with timestamps
🔧 Data Table Workaround Implements custom code-based sorting to overcome n8n Data Table's current sorting limitations
🌐 Multi-Language Support Handles Vietnamese addressing conventions (anh/chị/em) with customizable language settings

Technical Highlights

  • Idempotent processing: Prevents duplicate responses via processed flag
  • Timezone-aware: All timestamps formatted in Asia/Ho_Chi_Minh timezone
  • Facebook Markdown compatible: Auto-converts AI output to Messenger-safe formatting
  • 2000-character chunking: Intelligently splits long replies while preserving message structure
  • Error handling: Continues on node failures with graceful degradation
  • Extensible architecture: Easy to add calendar checks, CRM integration, or custom business logic

🚀 How It Works

Workflow Architecture

┌─────────────────────────────────────────────────────────────┐
│  1. WEBHOOK RECEPTION & VALIDATION                          │
│  • Facebook Webhook receives message                        │
│  • Validates message type (text only)                       │
│  • Filters out page echoes (self-sent messages)             │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  2. MESSAGE BATCHING & STORAGE                              │
│  • Insert message to Data Table (processed=false)           │
│  • Send "Seen" acknowledgment to user                       │
│  • Wait 3 seconds for additional messages                   │
│  • Retrieve all unprocessed messages for this user          │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  3. CONTEXT AGGREGATION & HISTORY BUILDING                  │
│  • Sort unprocessed messages by ID (ascending)              │
│  • Merge all user_text into single string                   │
│  • Identify max ID (latest message)                         │
│  • Retrieve last 15 processed messages                      │
│  • Sort by creation time (custom code)                      │
│  • Build session-separated history:                         │
│    - old_session_history (previous days)                    │
│    - now_session_history (today's messages)                 │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  4. AI PROCESSING & RESPONSE GENERATION                     │
│  • Check if current message = max ID                        │
│  • Send "Typing..." indicator                               │
│  • Pass merged_message + history to AI Agent                │
│  • AI analyzes context with session awareness               │
│  • Generate response in Facebook Markdown                   │
└─────────────────────────────────────────────────────────────┘
                          ↓
┌─────────────────────────────────────────────────────────────┐
│  5. RESPONSE DELIVERY & STATUS UPDATE                       │
│  • Format AI output (MD→FB, chunking)                       │
│  • Send text message to Messenger                           │
│  • Update bot_rep field in Data Table                       │
│  • Mark all unprocessed messages as processed=true          │
└─────────────────────────────────────────────────────────────┘

🛠️ Setup Guide

Prerequisites

  • ✅ n8n instance v1.113.0+ (self-hosted or cloud)
  • ✅ Facebook Developer Account
  • ✅ Facebook Page with Messenger enabled
  • ✅ SSL-enabled public domain for webhook
  • ✅ Google Gemini API key or Groq API key (for AI)

Step 1: Facebook App Configuration

  1. Create Facebook App

  2. Configure Webhook

    • Navigate to Messenger Settings → Webhooks
  3. Generate Page Access Token

    • In Messenger Settings → Access Tokens
    • Select your Page → Generate Token
    • Store this token securely (needed for "Set Context" node)
  4. Subscribe App to Page

    • Select your Page in Webhooks section
    • Click "Subscribe" to enable event delivery

Step 2: n8n Data Table Setup

To create:

  1. Open n8n sidebar → Data Tables
  2. Click "Create Table"
  3. Name it: Jenix_Page_Chat_history
  4. Add columns as specified above
  5. Save and note the table ID

Step 3: Import Workflow

  1. Copy the workflow JSON (provided separately)
  2. In n8n: WorkflowsAdd workflowImport from JSON
  3. Paste JSON and click Import

Step 4: Configure Critical Nodes

Node: "Facebook Webhook"

  • Path: jenix-facebook-page-00A1 (or customize)
  • Methods: GET + POST enabled
  • Response Mode: "Using Respond to Webhook node"

Node: "Set Context"

  • Replace page_token value with your Page Access Token from Step 1
  • Example:
    {
      "user_id": "{{ $json.body.entry[0].messaging[0].sender.id }}",
      "user_text": "{{ $json.body.entry[0].messaging[0].message.text }}",
      "page_id": "{{ $json.body.entry[0].id }}",
      "page_token": "YOUR_PAGE_ACCESS_TOKEN_HERE"
    }
    

Node: "Insert To Process" (and all Data Table nodes)

  • Data Table ID: Select Jenix_Page_Chat_history from dropdown
  • If table doesn't appear, refresh or re-enter table ID manually

Node: "Process Merged Message" (AI Agent)

  • Model Selection:
    • Google Gemini: Connect "Google Gemini Chat Model" node
    • Groq: Connect "Groq Chat Model" node (faster, cheaper)
  • System Prompt Customization:
    • Modify persona name, business description, services
    • Adjust tone, language (Vietnamese/English/multilingual)
    • Add custom instructions for your use case

Step 5: Test & Deploy

  1. Activate workflow in n8n
  2. Verify webhook in Facebook Developer Console
  3. Send test message to your Page via Messenger
  4. Check execution log in n8n for any errors
  5. Monitor Data Table to see message storage

Customization Ideas

Business-Specific Features:

  • 📅 Appointment Booking: Add calendar integration (Google Calendar node)
  • 💳 Payment Links: Generate Stripe/PayPal links in replies
  • 📧 Lead Capture: Store user info in CRM (HubSpot, Airtable nodes)
  • 🎫 Ticket Creation: Auto-create support tickets in Zendesk/Jira
  • 🔔 Notifications: Alert team on Slack when high-value lead detected

Persona Customization:

// In AI Agent system prompt
# Persona
You are [Your Bot Name], the [role] for [Company Name].

# Services
1. [Service 1]: [Description]
2. [Service 2]: [Description]

# Tone
- [Personality trait 1]
- [Personality trait 2]
- [Language style]

# Language Rules
- Address user as: [sir/madam/custom]
- Refer to self as: [I/we/bot name]

Multi-Page Support:

  • Duplicate workflow for each page
  • Modify webhook path and page_token per workflow
  • Use same Data Table with page_id differentiation

🐛 Troubleshooting Guide

Common Issues & Solutions

Issue Cause Solution
Webhook verification fails Incorrect verify token Match token in Facebook settings and n8n webhook
Bot responds multiple times Batching not working Check "Wait 3s" node is active and connected
No response from bot AI node error Check AI API credentials and model availability
Message history empty Data Table not saving Verify table ID in all Data Table nodes
Timezone incorrect Wrong timezone in code Update timezone in "Merge History" node
Long messages truncated Chunking issue Check "Format for Facebook Output" node logic

Debug Checklist

  1. ✅ Workflow is Active (toggle in top-right)
  2. ✅ Facebook webhook status is Green in Developer Console
  3. ✅ Page Access Token is valid and not expired
  4. ✅ Data Table exists and has correct column names
  5. ✅ AI model credentials are configured and working
  6. ✅ Webhook URL is publicly accessible (HTTPS)
  7. ✅ Check n8n Execution Log for specific errors

Testing Workflow

Test Message Sequence:

  1. Send: Hello → Should get greeting
  2. Send: What do you do? → Should get service description
  3. Send: Pricing → Should reference previous context
  4. Wait 1 hour → Send: Hi again → Should resume conversation

📈 Performance Metrics

Metric Value Notes
Average Response Time 2-5 seconds Depends on AI model speed
Batching Window 3 seconds Adjustable in "Wait" node
Max History Length 15 messages ~7-8 user-bot exchanges
Message Chunking 2000 chars/chunk Facebook Messenger limit
Concurrent Users Unlimited Webhook-based, auto-scales
Data Table Rows Varies by plan Check n8n plan limits

🔄 Version History

Version 2.0 (Current - October 2025)

Major Updates:

  • ✨ Added "Get 15 Newest Rows" node to overcome Data Table sorting limitations
  • 🧠 Enhanced "Merge History" with session-aware context separation (old vs. current)
  • 📅 Implemented timezone-aware timestamp formatting (Vietnam timezone)
  • 🎯 Improved AI Agent system prompt with dual-context variables
  • 🔧 Optimized message sorting logic for chronological accuracy
  • 📝 Added session start timestamps to history blocks
  • 🚀 Performance improvements in code execution

Breaking Changes:

  • AI Agent now expects old_session_history and now_session_history instead of single history
  • "Get history message" node now uses returnAll: true
  • Requires manual update of system prompt in existing workflows

Version 1.0 (October 2025)

Initial Release:

  • ✅ Basic message batching and storage
  • ✅ Simple conversation history tracking
  • ✅ Facebook Messenger integration
  • ✅ AI Agent with single history context
  • ✅ Seen/Typing effects
  • ✅ Facebook Markdown formatting

📚 Technical Architecture

Node Type Breakdown

Node Type Count Purpose
Webhook 1 Receives Facebook events
IF (Conditional) 3 Message validation, echo filter, max ID check
HTTP Request 3 Seen, Typing, Send Text to Facebook API
Set 1 Extract and structure context variables
Wait 1 Batching delay window
Data Table 4 Insert, Get unprocessed, Get history, Update
Code 3 Get 15 rows, Merge messages, Format output
AI Agent 1 LLM-powered response generation
LLM Chat Model 2 Google Gemini + Groq (switchable)
Respond to Webhook 1 Confirm webhook verification
Sticky Note 6 Documentation and workflow annotations

Data Model

Batch_messages Table Schema:

CREATE TABLE Batch_messages (
  id INTEGER PRIMARY KEY AUTO_INCREMENT,
  user_id VARCHAR(255) NOT NULL,
  user_text TEXT,
  bot_rep TEXT,
  processed BOOLEAN DEFAULT FALSE,
  createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
  updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Indexes (Recommended):

CREATE INDEX idx_user_processed ON Batch_messages(user_id, processed);
CREATE INDEX idx_created_at ON Batch_messages(createdAt DESC);

🔐 Security & Privacy

Data Handling

  • User messages stored in n8n Data Table (private to your instance)
  • No third-party message logging (except AI provider's processing)
  • Page Access Token secured in Set node (not exposed in logs)
  • Webhook signature validation via Facebook's x-hub-signature-256
  • HTTPS-only webhook endpoint (required by Facebook)

Best Practices

  1. Rotate Page Access Tokens quarterly
  2. Monitor Data Table size and archive old data
  3. Use environment variables for tokens (if using n8n Cloud)
  4. Enable n8n workflow encryption (Enterprise feature)
  5. Limit AI prompt injection by sanitizing user input
  6. Comply with GDPR/data regulations in your region

🌐 Multi-Language Adaptation

Current Setup (Vietnamese)

System prompt uses:

  • Address user: anh or chị
  • Refer to self: em
  • Friendly, witty tone

Adapting to English

Modify AI Agent system prompt:

# Language Rules
- Address user as: "you" or "[Name]"
- Refer to self as: "I" or "[Bot Name]"
- Use professional yet friendly tone

Supporting Multiple Languages

Add language detection node:

const userText = $json.user_text;
const isVietnamese = /[àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêềếểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ]/i.test(userText);
return [{ json: { language: isVietnamese ? 'vi' : 'en' } }];

Then route to language-specific AI Agent nodes.


🎓 Learning Resources

Understanding Key Concepts

  1. Message Batching

    • Why: Prevents fragmented AI responses
    • How: Accumulates messages during wait period
    • Trade-off: Slight delay vs. response quality
  2. Session Awareness

    • Why: AI needs temporal context
    • How: Separates history by date boundaries
    • Benefit: Natural conversation resumption
  3. Data Table Limitations

    • Issue: No native descending sort by date
    • Workaround: Custom code for sorting
    • Future: May be resolved in n8n updates

Further Reading


🤝 Support & Community

Need Help?

  1. Check the full tutorial:
    nguyenthieutoan.com/facebook-messenger-smart-chatbot

  2. Common questions:

    • How to change AI model? → Swap LLM Chat Model node
    • How to add features? → Insert nodes between AI Agent and Send Text
    • How to debug? → Check n8n Execution log and Data Table
  3. Contact the creator:

Contributing

Found an improvement? Have a feature idea?

  • Share your enhanced version in the n8n community
  • Credit the original workflow and author
  • Document your changes clearly

👤 About the Creator

Nguyen Thieu Toan (Nguyễn Thiệu Toàn / Jay Nguyen)

AI Automation Specialist | Chatbot Developer | Business Optimization Expert

With a background in marketing management and expertise in n8n workflow engineering, Jay helps businesses transform customer interactions through intelligent automation. Specializing in:

  • 🤖 Custom AI chatbot development (Messenger, Telegram, WhatsApp)
  • ⚙️ Business process automation with n8n
  • 📊 CRM integration and lead management systems
  • 🎓 AI & automation training for teams and businesses

Services:

  • AI Automation Solutions for Businesses
  • n8n Workflow Development & Consulting
  • AI & Automation Training Programs
  • Custom Chatbot Implementation

Website: nguyenthieutoan.com


📝 License & Usage

License: After purchase, you may use this workflow in your own commercial or personal projects. Redistribution, resale, or repackaging of the workflow—whether modified or not—is not permitted under any circumstances.

Attribution Requirements:

  • ✅ Keep author name when sharing
  • ✅ Link to original workflow source
  • ✅ Mention modifications made (if any)

Not Required But Appreciated:

  • ⭐ Star the workflow on n8n community
  • 📢 Share your success story
  • 💬 Leave feedback or testimonials
  • ☕ Support the creator (link on website)

🎯 Quick Start Checklist

Before deploying, ensure:

  • [ ] Facebook App created and Messenger added
  • [ ] Webhook configured with correct callback URL and verify token
  • [ ] Page Access Token generated and copied
  • [ ] Data Table Jenix_Page_Chat_history created with correct schema
  • [ ] Workflow imported into n8n
  • [ ] "Set Context" node updated with your Page Access Token
  • [ ] All Data Table nodes linked to correct table ID
  • [ ] AI model credentials configured (Gemini or Groq)
  • [ ] Workflow activated
  • [ ] Webhook verified in Facebook Developer Console
  • [ ] Test message sent and response received

Last Updated: October 24, 2025
Workflow Version: 2.0
n8n Compatibility: v1.113.0+
Author: Nguyen Thieu Toan


Ready to deploy your intelligent chatbot? Import this workflow and transform your Facebook Messenger into a powerful AI assistant! 🚀