π€ 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 Create Facebook App Go to Facebook Developers Create new app β Choose "Business" type Add "Messenger" product Configure Webhook Navigate to Messenger Settings β Webhooks Generate Page Access Token In Messenger Settings β Access Tokens Select your Page β Generate Token Store this token securely (needed for "Set Context" node) Subscribe App to Page Select your Page in Webhooks section Click "Subscribe" to enable event delivery Step 2: n8n Data Table Setup To create: Open n8n sidebar β Data Tables Click "Create Table" Name it: Jenix_Page_Chat_history Add columns as specified above Save and note the table ID Step 3: Import Workflow Copy the workflow JSON (provided separately) In n8n: Workflows β Add workflow β Import from JSON 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 Activate workflow in n8n Verify webhook in Facebook Developer Console Send test message to your Page via Messenger Check execution log in n8n for any errors 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 β
Workflow is Active (toggle in top-right) β
Facebook webhook status is Green in Developer Console β
Page Access Token is valid and not expired β
Data Table exists and has correct column names β
AI model credentials are configured and working β
Webhook URL is publicly accessible (HTTPS) β
Check n8n Execution Log for specific errors Testing Workflow Test Message Sequence: Send: Hello β Should get greeting Send: What do you do? β Should get service description Send: Pricing β Should reference previous context 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 Rotate Page Access Tokens quarterly Monitor Data Table size and archive old data Use environment variables for tokens (if using n8n Cloud) Enable n8n workflow encryption (Enterprise feature) Limit AI prompt injection by sanitizing user input 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 Message Batching Why: Prevents fragmented AI responses How: Accumulates messages during wait period Trade-off: Slight delay vs. response quality Session Awareness Why: AI needs temporal context How: Separates history by date boundaries Benefit: Natural conversation resumption Data Table Limitations Issue: No native descending sort by date Workaround: Custom code for sorting Future: May be resolved in n8n updates Further Reading n8n Data Table Documentation Facebook Messenger Platform API LangChain AI Agent Guide Workflow Best Practices π€ Support & Community Need Help? Check the full tutorial: nguyenthieutoan.com/facebook-messenger-smart-chatbot 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 Contact the creator: Website: nguyenthieutoan.com Consultation booking available on site 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! π