Advanced AI-powered chatbot with intelligent message batching, session-aware conversation tracking, and natural Messenger integration
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:
Requires: n8n v1.113.0+ (for Data Table feature)
| 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 |
processed flag┌─────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────┘
Create Facebook App
Configure Webhook
Generate Page Access Token
Subscribe App to Page
To create:
Jenix_Page_Chat_historyjenix-facebook-page-00A1 (or customize)page_token value with your Page Access Token from Step 1{
"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"
}
Jenix_Page_Chat_history from dropdownBusiness-Specific Features:
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:
| 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 |
Test Message Sequence:
Hello → Should get greetingWhat do you do? → Should get service descriptionPricing → Should reference previous contextHi again → Should resume conversation| 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 |
Major Updates:
Breaking Changes:
old_session_history and now_session_history instead of single historyreturnAll: trueInitial Release:
| 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 |
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);
x-hub-signature-256System prompt uses:
anh or chịemModify 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
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.
Message Batching
Session Awareness
Data Table Limitations
Check the full tutorial:
nguyenthieutoan.com/facebook-messenger-smart-chatbot
Common questions:
Contact the creator:
Found an improvement? Have a feature idea?
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:
Services:
Website: nguyenthieutoan.com
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:
Not Required But Appreciated:
Before deploying, ensure:
Jenix_Page_Chat_history created with correct schemaLast 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! 🚀