Build an AI Telegram Bot with LangChain & n8n

Learn how to create a Telegram AI bot using n8n, LangChain nodes, and OpenAI to chat, remember context, and generate images with Dall-E 3. Automate personalized user interaction with smart memory and multi-tool AI responses.
lmChatOpenAi
memoryBufferWindow
telegramTrigger
+5
Workflow Identifier: 1649
NODES in Use: lmChatOpenAi, memoryBufferWindow, telegramTrigger, stickyNote, telegram, telegramTool, toolHttpRequest, agent

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

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

1. Opening Problem Statement

Meet Alex, a digital content creator juggling multiple social media channels and messaging platforms. Alex receives countless questions daily from followers on Telegram, ranging from simple queries to complex requests for AI-generated art. Manually responding is time-consuming, error-prone, and frankly, overwhelming. Important messages get missed, followers wait too long for replies, and Alex loses precious time that could be better spent creating content.

This exact problem is what our unique n8n workflow solves: turning Telegram messages into intelligent AI-driven conversations with contextual memory, personalized replies, and even the ability to generate and send AI-created images automatically via Telegram.

2. What This Automation Does

When you activate this workflow, here’s what happens:

  • Real-time AI Chatting: The bot listens to every Telegram message and uses OpenAI’s GPT-4o model to provide human-like, context-aware responses.
  • Contextual Memory Management: By storing recent chat context with LangChain’s Window Buffer Memory, the bot remembers the ongoing conversation and keeps replies relevant.
  • AI Image Generation: The workflow can generate images based on user requests using Dall-E 3, instantly sending those images back to Telegram chats.
  • Multi-tool AI Integration: Leveraging LangChain’s AI Agent node, the bot intelligently switches between chatting and image generation tools depending on user input.
  • Failure Resilience: The Telegram “Send final reply” node includes error handling that ensures smooth continuation even if sending a message fails.
  • Personalized Replies: The AI addresses users by their first name in messages, enhancing engagement and user experience.

Overall, it eliminates hours of manual social media engagement and introduces a scalable way to automate interactions with Telegram users using state-of-the-art AI.

3. Prerequisites ⚙️

  • n8n Account: You need an n8n instance (cloud or self-hosted). For self-hosting, platforms like Hostinger are recommended.
  • Telegram Bot API Token: Create a Telegram bot via BotFather and note down the API token.
  • OpenAI API Key: Get access with proper permissions for GPT-4o and Dall-E image generation.
  • LangChain nodes installed: LangChain nodes for AI chat models, memory buffer, and tools must be installed in your n8n instance.

4. Step-by-Step Guide to Build the Telegram AI Bot

Step 1: Set Up Telegram Trigger Node

In your n8n editor, click “+ Add Node” → “Telegram Trigger”. Choose your Telegram API credentials (linked to your bot token). Under “Updates,” select “*” to listen to all message types. This node listens for incoming Telegram messages from any chat.

You should see the node waiting for webhook calls whenever a new Telegram message arrives.

Common Mistake: Not using the correct bot token or forgetting to start the workflow will cause no messages to trigger.

Step 2: Add LangChain AI Agent Node

Add a “AI Agent” node from LangChain nodes. Set its input text parameter to {{ $json.message.text }}, so it receives user messages dynamically. In options, customize the system message to greet users by their first name: You are a helpful assistant. You are communicating with a user named {{ $json.message.from.first_name }}. This personalizes responses.

Connect the output of the Telegram trigger to this AI Agent node. The AI Agent will be the core processing unit deciding whether to chat or generate an image.

Common Mistake: Misconfiguring the prompt or not connecting properly will break message understanding.

Step 3: Configure Language Model Node (OpenAI Chat Model)

Insert the OpenAI Chat Model node. Choose GPT-4o as the model with these options: temperature 0.7 and frequency penalty 0.2 to balance creativity and consistency. Link this node to the AI Agent as its language model backend.

This node generates the actual text responses.

Step 4: Add Window Buffer Memory Node

Add the Window Buffer Memory node to store recent conversation history. Configure it to use a session key tied to Telegram chat IDs: chat_with_{{ $('Listen for incoming events').first().json.message.chat.id }}. Set the context window length to 10 messages to remember recent chat context.

Connect this node to the AI Agent node as its memory source.

Step 5: Integrate Dall-E Image Generation Node

Place the LangChain HTTP Request node set to call OpenAI’s image generation API (Dall-E 3). Use POST method to https://api.openai.com/v1/images/generations. Add parameters: model: dall-e-3 and prompt which comes from AI Agent’s command to generate images.

This node acts as a tool the AI Agent calls when an image is requested.

Step 6: Add Telegram Tool Node to Send Back Images

Next, include the Telegram Tool node configured to send documents (images) back to users. Use the expression to get the image URL: {{ $fromAI("url", "a valid url of an image", "string", " ") }}. Connect this node to the AI Agent’s tool output.

Step 7: Set Telegram Node to Send Final Text Reply

Finally, add the Telegram node to send back final AI-generated text replies. Use expressions to grab the output and chat ID dynamically:

text:={{ $json.output }}
chatId:={{ $('Listen for incoming events').first().json.message.from.id }}

Enable the “Continue On Error” option to keep workflow running even if message fails to send.

Step 8: Connect All Nodes and Activate the Workflow

Ensure all connections are properly set: Telegram Trigger -> AI Agent -> OpenAI Chat Model and Memory Buffer for language model and memory inputs, AI Agent outputs leading to Telegram nodes for message and images.

After connecting, save and activate the workflow. Test it by sending messages in your linked Telegram chat.

5. Customizations ✏️

  • Customize Greeting Message: In the AI Agent node, modify the systemMessage parameter to include different greetings or user information for a more tailored experience.
  • Adjust Memory Window Length: Increase or decrease the context window length in Window Buffer Memory node to remember longer or shorter conversation history.
  • Change AI Model Settings: Tune temperature and frequency penalties in the OpenAI Chat Model node to make the bot more creative or precise.
  • Image Generation Filters: Add additional prompt parameters in the Generate image in Dalle node to influence style or content of generated images.
  • Multi-language Support: In the AI Agent system message, add instructions to respond in different languages based on user input.

6. Troubleshooting 🔧

Problem: “Telegram API error sending message”

Cause: This usually happens if the chat ID is incorrect or the bot is blocked by the user.

Solution: Verify you are using the user ID from the correct message field and ensure the bot is an active participant in the chat. Also, enable “Continue On Error” in the Telegram node to prevent workflow stops.

Problem: “OpenAI API authentication failed”

Cause: Invalid or expired API key for OpenAI.

Solution: Update your OpenAI API credentials in n8n, ensure your key has access to GPT-4o and Dall-E, and test the connection in each API node.

Problem: “Memory node not storing context properly”

Cause: Misconfigured session key or context window length.

Solution: Double-check the session key expression matches Telegram chat ID exactly and that context length suits your conversation flow.

7. Pre-Production Checklist ✅

  • Confirm Telegram bot webhook URL and trigger node receive live messages.
  • Test OpenAI API connectivity separately with example prompts.
  • Send test messages to Telegram and verify AI responses.
  • Validate image generation triggers by requesting pictures.
  • Backup your n8n workflow export before any major changes.

8. Deployment Guide

Activate your workflow by toggling the “Active” switch in the n8n editor. Make sure your n8n instance is reachable via HTTPS for Telegram webhooks to work.

Monitor the workflow via n8n execution logs to catch errors early. Periodically update your OpenAI credentials and Telegram tokens to prevent failures.

This setup is ideal for small businesses, content creators, or community managers who want to automate Telegram support and engagement with advanced AI capabilities.

10. Conclusion

By following this detailed guide, you built a powerful Telegram AI bot combining LangChain and OpenAI technologies inside n8n. You’ve automated personalized chats, added memory for natural conversations, and enabled instant AI-generated artwork responses.

This workflow can save countless hours weekly and greatly improve user interaction quality on Telegram.

Next, consider enhancing this bot with voice message processing, sentiment analysis, or multi-platform chat support for even richer features.

Happy automating!

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