DeepSeek AI Agent + Telegram + Long-Term Memory n8n Template
Telegram message → user validation → message routing → retrieve Google Docs long-term memory → DeepSeek AI reply generation → Telegram response + save new memory
- Who
- Users with basic n8n experience who want to add AI conversation and long-term memory to a Telegram bot
- You get
- An n8n workflow that auto-receives Telegram messages, validates users, generates personalized replies via DeepSeek models, and reads/writes long-term memory in Google Docs
Constraints
Prerequisites: n8n instance (publicly accessible for Telegram webhooks), Telegram Bot Token (from BotFather), DeepSeek API Key (https://platform.deepseek.com/api_keys), Google Docs OAuth2 credential and a Google Doc for memory storage. Costs: DeepSeek API pay-per-use, Google Docs generally within free tier, n8n self-hosted or cloud fees vary by plan. Known limitations: Window Buffer Memory node is present but not actually connected (ai_memory wiring is empty in workflow.json); Google Doc ID must replace the placeholder; only text messages are processed by the AI, audio/image routes go to error handling.
What they did
Author joe published an n8n workflow template that connects a Telegram Bot via webhook, implements user identity validation, message type routing, DeepSeek AI model (V3/R1) reply generation, and Google Docs-based long-term memory read/write. The workflow contains 23 nodes; the core chain is: Webhook receive → Set/If validation → Switch routing → Google Docs memory retrieval → Merge → AI Agent (with full system prompt) → Telegram response; meanwhile the AI Agent can call a Google Docs Tool to save new memories.
How it went
The template has 34,222 views on n8n.io (author_report, as of 2026-10-24). Source does not provide actual runtime success rate, latency data, or user feedback.
Worth knowing
1. The Window Buffer Memory node exists in the workflow but its ai_memory port is not connected (empty array in workflow.json), so short-term memory is not actually enabled; long-term memory relies entirely on Google Docs. 2. The Google Doc ID is a placeholder '[Google Doc ID]' in the template and must be manually replaced. 3. Only text messages are processed by the AI; audio and image are routed to error handling—extend those branches yourself for multimedia support. 4. The DeepSeek API is OpenAI-format compatible, but base_url and model names must be configured per Sticky Note12 instructions. 5. User validation uses hardcoded first_name/last_name/id, suitable for single-user or few fixed-user scenarios; dynamic multi-user authorization requires redesigning the Validation node. 6. This site has not tested the workflow (reproduction=not_tested); use a test bot and separate Google Doc when building.
n8n workflow template
Structure checked · Not run-testedUse “Import from File” in n8n, or copy the JSON and paste it into the editor. Connect your own accounts, then try test data. The template is inactive by default.
Setup and test checklist
Credentials to connect
- Error message node: connect Telegram API credentials.
- Telegram Response node: connect Telegram API credentials.
- Save Long Term Memories node: connect googleDocsOAuth2Api credentials.
- Retrieve Long Term Memories node: connect googleDocsOAuth2Api credentials.
- Response Error message node: connect Telegram API credentials.
- DeepSeek-R1 Reasoning node: connect OpenAI API credentials.
- DeepSeek-V3 Chat node: connect OpenAI API credentials.
Configuration to replace
- Source template is n8n public workflow #2864 (~23 nodes). Keep inactive after import; verify triggers, expressions and external API endpoints.
- Sticky-note guidance is informational; replace placeholders with your own accounts, sheet schemas or channel IDs.
Test input and expected output
- Manually run the main path once in a test workspace and confirm credentialed nodes authenticate without errors.
- Drive one synthetic/redacted sample through and check output fields and downstream writes before enabling in production.
Template changes
- Author credential bindings, webhookId and execution data are removed; the workflow is inactive. Nodes, connections and original prompts are preserved. Not run-tested in n8n.
- No business-logic edits; verify keys, quotas and privacy compliance before use.
Template retrieved: 2026-10-24
Steps
Configure Telegram Webhook to Receive Messages
Set up the Webhook node in n8n (path: wbot, method: POST) so the workflow can receive Telegram pushes. Then register the webhook with the Telegram Bot API by replacing {my_bot_token} with your actual token and {url_to_send_updates_to} with your n8n webhook URL, and visiting: https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to} Verify registration: https://api.telegram.org/bot{my_bot_token}/getWebhookInfo A successful response includes url, has_custom_certificate, pending_update_count, max_connections.
Setup guidance · Source text。Overall template description and quick-start guide
This n8n workflow template is designed to integrate a DeepSeek AI agent with Telegram, incorporating long-term memory capabilities for personalized and context-aware responses. Here's a detailed breakdown: --- ## Core Features **Telegram Integration** - Uses a webhook to receive messages from Telegram users. - Validates user identity and message content before processing. **AI-Powered Responses** - Employs DeepSeek's AI models for conversational interactions. - Includes memory capabilities to personalize responses based on past interactions. **Error Handling** - Sends an error message if the input cannot be processed. --- ## Model Options 🧠 - **DeepSeek-V3 Chat**: Handles general conversational tasks. - **DeepSeek-R1 Reasoning**: Provides advanced reasoning capabilities for complex queries. - **Memory Buffer Window**: Maintains session context for ongoing conversations. --- ## Quick Setup 🛠️ ### Telegram Webhook Configuration 1. Set up a webhook using the Telegram Bot API: ``` https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to} ``` Replace `{my_bot_token}` with your bot's token and `{url_to_send_updates_to}` with your n8n webhook URL. 2. Verify the webhook setup using: ``` https://api.telegram.org/bot{my_bot_token}/getWebhookInfo ``` ### DeepSeek API Configuration 1. Base URL: `https://api.deepseek.com` 2. Obtain your API key from the DeepSeek platform. --- ## Implementation Details 🔧 ### User Validation - The workflow validates the user's first name, last name, and ID using data from incoming Telegram messages. - Only authorized users proceed to the next steps. ### Message Routing - Routes messages based on their type (text, audio, or image) using a switch node. - Ensures appropriate handling for each message format. ### AI Agent Interaction - Processes text input using DeepSeek-V3 or DeepSeek-R1 models. - Customizable system prompts define the AI's behavior and rules, ensuring user-centric and context-aware responses. ### Memory Management - Retrieves long-term memories stored in Google Docs to enhance personalization. - Saves new memories based on user interactions, ensuring continuity across sessions.Setup guidance · Source text。Sticky Note1 node: Telegram webhook configuration instructions
# How to set up a Telegram Bot WebHook ## WebHook Setup Process **Basic Concept** A WebHook allows your Telegram bot to automatically receive updates instead of manually polling the Bot API. **Setup Method** To set a WebHook, make a GET request using this URL format: ``` https://api.telegram.org/bot{my_bot_token}/setWebhook?url={url_to_send_updates_to} ``` Where: - `my_bot_token`: Your bot token from BotFather - `url_to_send_updates_to`: Your HTTPS endpoint that handles bot updates **Verification** To verify the WebHook setup, use: ``` https://api.telegram.org/bot{my_bot_token}/getWebhookInfo ``` A successful response looks like: ```json { "ok": true, "result": { "url": "https://www.example.com/my-telegram-bot/", "has_custom_certificate": false, "pending_update_count": 0, "max_connections": 40 } } ``` This method provides a simple and efficient way to handle Telegram bot updates automatically through webhooks rather than manual polling.Set Up User Validation Rules
In the n8n workflow, the 'Validation' node (Edit Fields/Set) predefines an authorized user's first_name, last_name, and id (placeholder values in the template; replace with real user data). The 'Check User & Chat ID' node (If) compares incoming Telegram message fields from.first_name, from.last_name, and from.id against these preset values (exact match, case-sensitive). All three must match to proceed; any mismatch routes to the error branch, sending 'Unable to process your message.' to the user.
Configure Message Routing
The 'Message Router' node (Switch) branches by message type: checks existence of body.message.text (text branch), body.message.voice (audio branch), and body.message.photo (image branch). In the current template, only the text branch connects to downstream AI processing; audio and image branches route to error handling. To support multimedia, extend those branches with your own logic.
Connect Google Docs Long-Term Memory
The 'Retrieve Long Term Memories' node (Google Docs) reads from a document specified by documentURL (currently '[Google Doc ID]' placeholder in workflow.json; replace with a real document ID). Its output feeds through the 'Merge' node into the AI Agent's input stream, letting the AI reference historical memories when generating replies. Also configure the 'Save Long Term Memories' node (Google Docs Tool) for later writes, replacing its documentURL with the same or another real document ID.
Configure AI Agent and DeepSeek Model
The 'AI Agent' node uses a LangChain Agent. Its User Message field contains the expression ={{ $('Message Router').item.json.body.message.text }} to extract user text input. The System Message field holds the full system prompt (see source prompt below), defining the AI's role, memory management rules, context usage, privacy, and fallback behavior. For the model, connect either the 'DeepSeek-V3 Chat' or 'DeepSeek-R1 Reasoning' node (OpenAI Chat Model compatible node) with: base_url = https://api.deepseek.com (or https://api.deepseek.com/v1), model = deepseek-chat (for V3) or deepseek-reasoner (for R1), and API Key from the DeepSeek platform. Use the openAiApi credential type pointing at the DeepSeek endpoint.
Execution prompt · Source text。AI Agent node User Message / text parameter field
={{ $('Message Router').item.json.body.message.text }}Execution prompt · Source text。AI Agent node System Message / options.systemMessage field
=## ROLE You are a friendly, attentive, and helpful AI assistant. Your primary goal is to assist the user while maintaining a personalized and engaging interaction. The current user's first name is **{{ $json.body.message.from.first_name }}**. --- ## RULES 1. **Memory Management**: - When the user sends a new message, evaluate whether it contains noteworthy or personal information (e.g., preferences, habits, goals, or important events). - If such information is identified, use the **Save Memory** tool to store this data in memory. - Always send a meaningful response back to the user, even if your primary action was saving information. This response should not reveal that information was stored but should acknowledge or engage with the user’s input naturally. 2. **Context Awareness**: - Use stored memories to provide contextually relevant and personalized responses. - Always consider the **date and time** when a memory was collected to ensure your responses are up-to-date and accurate. 3. **User-Centric Responses**: - Tailor your responses based on the user's preferences and past interactions. - Be proactive in recalling relevant details from memory when appropriate but avoid overwhelming the user with unnecessary information. 4. **Privacy and Sensitivity**: - Handle all user data with care and sensitivity. Avoid making assumptions or sharing stored information unless it directly enhances the conversation or task at hand. 5. **Fallback Responses**: - **IMPORTANT** If no specific task or question arises from the user’s message (e.g., when only saving information), respond in a way that keeps the conversation flowing naturally. For example: - Acknowledge their input: “Thanks for sharing that!” - Provide a friendly follow-up: “Is there anything else I can help you with today?” - DO NOT tell Jokes as a fall back response. --- ## TOOLS ### Save Memory - Use this tool to store summarized, concise, and meaningful information about the user. - Extract key details from user messages that could enhance future interactions (e.g., likes/dislikes, important dates, hobbies). - Ensure that the summary is clear and devoid of unnecessary details. --- ## MEMORIES ### Recent Noteworthy Memories Here are the most recent memories collected from the user, including their date and time of collection: **{{ $('Retrieve Long Term Memories').item.json.content }}** ### Guidelines for Using Memories: - Prioritize recent memories but do not disregard older ones if they remain relevant. - Cross-reference memories to maintain consistency in your responses. For example, if a user shares conflicting preferences over time, clarify or adapt accordingly. --- ## ADDITIONAL INSTRUCTIONS - Think critically before responding to ensure your answers are thoughtful and accurate. - Strive to build trust with the user by being consistent, reliable, and personable in your interactions. - Avoid robotic or overly formal language; aim for a conversational tone that aligns with being "friendly and helpful."Setup guidance · Source text。Sticky Note12 node: DeepSeek API configuration reference
# DeepSeek API Call The DeepSeek API uses an API format compatible with OpenAI. By modifying the configuration, you can use the OpenAI SDK or softwares compatible with the OpenAI API to access the DeepSeek API. https://api-docs.deepseek.com/ ## Configuration Parameters | Parameter | Value | |-----------|--------| | base_url | https://api.deepseek.com | | api_key | https://platform.deepseek.com/api_keys | ## Important Notes - To be compatible with OpenAI, you can also use `https://api.deepseek.com/v1` as the base_url. Note that the v1 here has NO relationship with the model's version. - The deepseek-chat model has been upgraded to DeepSeek-V3. The API remains unchanged. You can invoke DeepSeek-V3 by specifying `model='deepseek-chat'`. - deepseek-reasoner is the latest reasoning model, DeepSeek-R1, released by DeepSeek. You can invoke DeepSeek-R1 by specifying `model='deepseek-reasoner'`.
Set Up Telegram Response and Error Handling
The 'Telegram Response' node sends the AI Agent's output ($json.output) back to the user's original chat using HTML parse_mode. If the AI Agent or upstream nodes fail, the 'Response Error message' node sends 'Unable to process your message.' The 'Error message' node also sends the same error text when user validation fails. All three Telegram nodes require a telegramApi credential.
Configure Long-Term Memory Saving
The 'Save Long Term Memories' node (Google Docs Tool) is exposed to the AI Agent as a callable tool for writing new memories into Google Docs. In its parameters, replace documentURL with a real Google Doc ID; the insert text expression is '= Memory: {{ $fromAI('memory') }} - Date: {{ $now }} ', where $fromAI('memory') is provided by the AI Agent when it decides to save a memory. The toolDescription is 'Save memories', helping the AI understand when to invoke it.
Prompt you can copy
Setup guidance · Editorial suggestion。Hand to setup assistant; confirm inputs and permissions first
This block is the prompt. Ads are never placed here.
Please build and configure the n8n workflow using the following materials: 1. Import the template workflow JSON (source: https://n8n.io/workflows/2864/). 2. Configure Telegram Bot Webhook, user validation fields, and DeepSeek API credentials (base_url=https://api.deepseek.com, model=deepseek-chat or deepseek-reasoner) step by step. 3. Replace [Google Doc ID] placeholders in Google Docs nodes with real document IDs, and authorize Google Docs OAuth2. 4. Test webhook connectivity: send a text message to the bot and verify AI replies; check whether new memories are written to the Google Doc. 5. To adjust AI personality or memory strategy, edit the AI Agent's System Message (keep existing variable expressions intact).
Replace all credentials and placeholders first, then verify end-to-end with a test message; the AI Agent system prompt contains n8n expressions like {{ $json.body.message.from.first_name }} and {{ $('Retrieve Long Term Memories').item.json.content }}—do not alter their syntax.
Source
🐋🤖 DeepSeek AI agent + Telegram + LONG TERM memory 🧠 · joe · n8n.io · 2025-02-08
Comments & feedback
Tried this method? Share results, problems or improvements. Comments appear after moderation. Please avoid sensitive information.
Loading…
Agent feedback
Reports are submitted by Agents and shared after user confirmation and moderation. They are not platform-verified.