Build an AI Chatbot with Long-Term Memory & Telegram Integration using n8n

Learn how to create a powerful AI chatbot using n8n that remembers past conversations with long-term memory in Google Docs and interacts via Telegram. This workflow transforms chatbots with context-aware, personalized responses reducing user frustration and saving hours of repetitive answering.
chatTrigger
googleDocs
agent
+8
Workflow Identifier: 1181
NODES in Use: chatTrigger, stickyNote, lmChatOpenAi, set, memoryBufferWindow, googleDocsTool, googleDocs, merge, aggregate, agent, telegram

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

Opening Problem Statement

Meet Sarah, a freelance consultant who spends countless hours answering repetitive questions from her clients over messaging apps. She often struggles to keep track of previous client preferences, instructions, and notes, leading to repeated misunderstandings and wasted time clarifying details. This disorganized interaction not only frustrates her clients but also eats into her billable hours, costing her both time and money. Sarah wants an AI chatbot that doesn’t just answer queries but remembers interactions over time and helps store important notes seamlessly — preferably integrated into the messaging platform she already uses, Telegram.

Without a long-term memory, typical chatbots respond in isolation, losing context after every conversation ends. This creates robotic experiences that frustrate users more than they help. Sarah needs an advanced chatbot that can recall past conversations, store meaningful memories, and keep notes accessible — all automated in one workflow.

What This Automation Does

This specific n8n workflow builds a conversational AI agent chatbot with several powerful capabilities tailored to Sarah’s exact needs:

  • Real-time chat input capturing: The chatbot listens for messages via a LangChain Chat Trigger node.
  • Memory retrieval: It retrieves long-term memories and notes stored in Google Docs to provide contextually relevant responses.
  • Dynamic AI agent interaction: Uses LangChain’s AI Tools Agent node paired with OpenAI’s models like GPT-4o-mini, to generate personalized and meaningful responses.
  • Long-term memory & notes saving: After processing the chat input, the workflow selectively saves meaningful memories or notes back into Google Docs for future reference.
  • Telegram messaging integration: It can optionally send responses directly to users in Telegram chats, ensuring seamless user interaction on a familiar platform.
  • Context window memory: Maintains recent conversation context with the Window Buffer Memory node to keep replies relevant within a session.

The benefits include saving Sarah hours every week by automating client communications, reducing repetitive clarifications, and providing a personalized assistant experience that recalls past interactions authentically.

Prerequisites ⚙️

  • n8n account (cloud or self-hosted) 🔌
  • OpenAI account with API key for GPT models 🔑
  • Google Docs account with OAuth2 credentials connected to n8n for storing memories and notes 📁
  • Telegram bot credentials with chat ID for sending messages via the Telegram node 💬📧
  • Basic familiarity with n8n workflow editor interface

For those wanting full control and privacy, you can opt to self-host n8n (e.g., using Hostinger hosting), which is ideal for sensitive data handling.

Step-by-Step Guide to Build This Workflow

  1. Set up the chat trigger to listen for incoming messages
    In n8n, add the LangChain Chat Trigger node. Set it to listen for chat inputs. This node provides the starting point for all message processing. The webhook URL generated here can be used to connect your chat platform (in this case, Telegram via bot or other interface).
    Expected outcome: Incoming chat messages trigger the workflow.
    Common mistake: Forgetting to deploy the webhook or mismatching the trigger with your actual messaging source.
  2. Retrieve long-term memories from Google Docs
    Add the Google Docs node configured with ‘Get’ operation to fetch stored long-term memories. Enter the Google Doc URL in the node parameters.
    Expected outcome: The node outputs the content of previously saved memories.
    Common mistake: Incorrect or missing Google Doc ID causing no data retrieval.
  3. Retrieve notes from Google Docs
    Add another Google Docs node similarly configured to fetch stored notes separately. This keeps notes and memories distinct.
    Expected outcome: Notes data made available for AI context.
    Common mistake: Mixing note and memory document URLs, which can confuse data handling.
  4. Merge retrieved memories and notes
    Add a Merge node to combine data streams from both Google Docs nodes. Select ‘Merge By Index’ to keep paired inputs aligned.
    Expected outcome: Single merged data stream for AI input.
    Common mistake: Choosing the wrong merge mode, which can lead to misaligned data.
  5. Aggregate all incoming items for full context
    Add an Aggregate node to compile the merged data into one aggregated item.
    Expected outcome: One cohesive data input for the AI Tools Agent.
    Common mistake: Forgetting to aggregate can cause incomplete information passed downstream.
  6. Process chat input with AI Tools Agent
    Add the AI Tools Agent (LangChain Agent) node. Configure it with the chat input text from the trigger node and the merged long-term memories and notes as context. Use the system prompt designed to manage memory saving and notes accordingly.
    Expected outcome: The AI generates a custom response and decides which memories or notes to update.
    Common mistake: Misconfiguring the system message or forgetting to map chat input properly.
  7. Maintain session context with Window Buffer Memory
    Add the Window Buffer Memory node to keep recent messages in session context, set session key by session ID from trigger.
    Expected outcome: Improved continuity in responses.
    Common mistake: Wrong session key leading to losing context between messages.
  8. Update long-term memories back to Google Docs
    Add the Google Docs Tool node configured on ‘Update’ operation pointing to the same document as memories. Use the AI output to append new memory data.
    Expected outcome: Stored memories are consistently updated.
    Common mistake: Overwriting or corrupting document if editing paths are wrong.
  9. Update notes back to Google Docs
    Add another Google Docs Tool node for notes, configured similarly to update the notes document with new entries.
    Expected outcome: Notes remain up to date for easy retrieval.
    Common mistake: Mixing notes memory fields or failing to distinguish note saving.
  10. Create AI language model node for fallback/complex responses
    Include an additional OpenAI GPT-4o-mini node for language model fallback or enhanced response generation.
    Expected outcome: Enhanced AI replies when needed.
    Common mistake: API key misconfiguration or quota exceeded errors.
  11. Send response to Telegram user
    Add the Telegram node configured with chat ID and extract AI response text.
    Expected outcome: Seamless reply via Telegram chat.
    Common mistake: Incorrect chat ID or bot permissions blocking messages.
  12. Set a simplified chat response output
    Add a Set node to format the AI-generated output neatly for logging and response validation.
    Expected outcome: Clear output for downstream use or monitoring.
    Common mistake: Not referencing correct data path for AI output.

Customizations ✏️

  • Change memory storage platform: Replace Google Docs nodes with Google Sheets or external database nodes to suit your preferred storage method. Edit the documentURL or database configs accordingly.
  • Telegram chat ID dynamic input: Modify the Telegram node’s chatId field to use dynamic values from incoming messages or external lookups so you can chat with multiple users rather than the hardcoded ID.
  • Expand AI agent capabilities: Tweak the system message prompt in the AI Tools Agent node to adjust tone, politeness, or add new rules for memory management tailored to your personal or business style.
  • Session context length: Adjust the Window Buffer Memory node’s contextWindowLength parameter to suit conversations with longer or shorter context retention needs.
  • Add logging and error handling: Implement error nodes or additional Set nodes to log input and output at various stages for better monitoring and debugging.

Troubleshooting 🔧

  • Problem: “Google Docs node returns no data”
    Cause: The Google Doc URL or document ID is incorrect, or OAuth token permissions have expired.
    Solution: Verify document sharing settings, reauthenticate your Google Docs credentials in n8n, and double-check the document URL.
  • Problem: “Telegram messages not sending”
    Cause: Bot lacks permissions, wrong chat ID, or network issues.
    Solution: Confirm the Telegram bot’s chat ID is valid, the bot is added to the chat/group, and permissions are enabled. Test sending from Telegram node manually.
  • Problem: “AI Tools Agent returns no response”
    Cause: Incorrect system message configuration or missing AI input.
    Solution: Review the AI Tools Agent node setup, ensure correct mapping of input text and context, and validate API key functionality.

Pre-Production Checklist ✅

  • Confirm Google Docs URLs and OAuth credentials are correct and active.
  • Test the chat trigger webhook with sample messages to verify triggering.
  • Verify the AI Tools Agent node produces meaningful responses by trial inputs.
  • Check Telegram bot connectivity with test message sending.
  • Ensure the Window Buffer Memory retains context across multiple messages.

Deployment Guide

Activate your workflow in n8n’s editor by toggling the workflow status to “active.” Monitor live triggers via the execution logs.
Use n8n’s UI to track any errors and use built-in credentials management for secure API key storage.
For privacy, consider self-hosting n8n, especially when dealing with sensitive user memories and notes.

FAQs

  • Q: Can I use Google Sheets instead of Google Docs for memory storage?
    A: Yes, you can swap Google Docs nodes with Google Sheets nodes, but you’ll need to adjust your data handling accordingly.
  • Q: Does this workflow consume OpenAI API credits?
    A: Yes, API calls to OpenAI’s models count toward your usage quota.
  • Q: Is the user’s personal data stored securely?
    A: This depends on your Google Docs and n8n security setup. Use best practices like restricted document sharing and encrypted connections.
  • Q: Can I extend this chatbot to other messaging platforms?
    A: Absolutely. By changing the chat trigger and messaging nodes, you can integrate platforms like Slack or WhatsApp.

Conclusion

By building this AI chatbot workflow with long-term memory using n8n, you’ve created a powerful assistant that remembers past interactions and stores valuable notes. This setup saves hours of repetitive client communication, improves user experience, and delivers personalized, context-rich responses via Telegram or any chat platform you integrate.
Next, consider expanding to multitasking workflows like appointment scheduling AI, personalized marketing assistants, or knowledge base update bots to further boost your automation power. Keep iterating and making AI your trusted helper!

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free