Build a Telegram AI Bot with Langchain & OpenAI GPT-4

Automate intelligent conversation and image generation in Telegram using OpenAI GPT-4 and Langchain. This workflow streamlines chat and visual responses with advanced AI tools, saving hours of manual customer support and creative tasks.
telegramTrigger
agent
lmChatOpenAi
+5
Workflow Identifier: 1338
NODES in Use: telegramTrigger, agent, lmChatOpenAi, memoryBufferWindow, toolWorkflow, httpRequest, telegram, set

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 Alex, a freelance content creator and community manager who handles dozens of Telegram group chats daily. Alex often spends several hours answering repetitive questions, generating content ideas, and occasionally sharing creative images. Manual responses slow down engagement and tire Alex, who wishes for an intelligent assistant to help manage these conversations. Additionally, sharing creative images promptly during chats feels clunky without integrated tools.

Without automation, Alex loses 3-4 hours weekly on repetitive messaging and creative content generation, delaying community engagement and reducing overall efficiency.

What This Automation Does

This specific n8n workflow transforms Telegram chat management by integrating AI-powered conversational intelligence and image generation. When this workflow runs, it:

  • Listens for incoming Telegram messages in any linked chat or group, triggering instantly on each new message.
  • Processes messages with OpenAI GPT-4 via Langchain to generate smart, context-aware replies thanks to a windowed memory buffer.
  • Detects image generation requests and invokes Dall-E 3 to create unique images aligned with user prompts.
  • Sends back AI-generated textual responses or images directly in Telegram, keeping conversations seamless and engaging.
  • Corrects and escapes special HTML characters in AI responses for flawless display within Telegram messages.
  • Maintains session continuity by tracking conversation context per user using chat IDs, enhancing natural dialog flow over time.

Using this workflow, Alex saves approximately 3-4 hours per week previously spent on manual replies and image sharing, boosting interaction quality and reducing burnout.

Prerequisites ⚙️

  • n8n account with access to Langchain nodes and HTTP Request node
  • OpenAI account with API access to GPT-4 and Dall-E 3 models 🔑
  • Telegram bot account configured with API token 📱 (Telegram Trigger and Telegram nodes require credentials)
  • Optional: Self-hosting solution for n8n if preferred (e.g., using Hostinger) 🔌

Step-by-Step Guide

1. Set Up Telegram Trigger Node to Listen for Messages

First, log into n8n and create a new workflow. Click + Add Node, search for Telegram Trigger node, and add it. Configure the triggering events to listen for message updates. Connect your Telegram Bot API credentials to authorize it.

You should see the webhook URL generated, which Telegram uses to notify n8n about incoming messages from users.

Common mistake: Forgetting to enable message updates in your Telegram bot settings prevents any trigger from firing.

2. Configure the AI Agent Node to Process Text Input

Add the AI Agent node from the Langchain nodes collection. Link it to the Telegram Trigger node. Set the text parameter to {{$json.message.text}} to use the incoming message content.

In its options, paste the provided system and human messages that establish the AI personality and available tools. This instructs the AI on how to interpret user input and when to call tools like image generation.

Expected outcome: The AI Agent will parse user inputs, decide if an image generation or text response is needed, and formulate a response JSON blob accordingly.

3. Add OpenAI Chat Model Node to Handle GPT-4 Conversations

Insert the OpenAI Chat Model Langchain node to serve as the language model for the AI Agent. Configure it with your OpenAI API credentials and select gpt-4-1106-preview as the model. Adjust settings like temperature (0.7) and frequencyPenalty (0.2) to balance creativity and focus.

Connect this node to the AI Agent to be invoked as the language reasoning engine.

4. Enhance Context with Window Buffer Memory

To maintain conversation flow, add the Window Buffer Memory node from Langchain. This node stores the last 10 dialog turns per user for context-aware replies.

Set the session key dynamically by extracting the chat ID from the incoming Telegram message using the expression:
=chat_with_{{ $('Listen for incoming events').first().json.message.chat.id }}

This ensures each user’s conversation history remains isolated.

Common mistake: Setting a static session key results in mixed conversation histories.

5. Handle Image Generation Requests with Dall-E 3 Tool

Include the Dall-E 3 Tool Langchain node to interpret user commands asking for images. This tool triggers the Generate image in Dall-E 3 HTTP Request node, which calls the OpenAI image generation API.

Configure the HTTP Request node as follows:

Method: POST
URL: https://api.openai.com/v1/images/generations
Headers: Authorization (bearer token from OpenAI credentials)
Body (JSON):
{
  "model": "dall-e-3",
  "prompt": "={{ $json.query }}",
  "n": 1,
  "size": "1024x1024"
}

Connect this to the previous tool node and prepare the response to forward the generated image URL to Telegram.

6. Send the Generated Image Back via Telegram Node

Add a Telegram node configured with your bot credentials, set to sendPhoto operation. Use the expression {{$json.data[0].url}} to get the image URL from the previous node. Specify chat ID as received earlier.

This sends back the generated image to the user chat, completing the visual interaction.

7. Post-AI Text Reply with Correct Error Handling

To ensure AI responses display correctly in Telegram HTML format, add an additional Telegram node named Correct errors. Use string replacement expressions to escape special characters:

{{ $('AI Agent').item.json.output.replace(/&/g, "&").replace(/>/g, ">").replace(/

This node sends cleaned AI text to the user.

8. (Optional) Add Response Confirmation Field

Add a Set node to append a response status field like "Success" to workflow output. This can help with debugging or logging.

Customizations ✏️

  • Change AI Model Configuration: In the OpenAI Chat Model node, swap to other GPT-4 or GPT-3.5 models by editing the model field, adjusting the tone and creativity.
  • Adjust Memory Window Size: Modify Window Buffer Memory's contextWindowLength to a larger or smaller number to keep shorter or longer conversation history.
  • Expand Supported Tools: Introduce new Langchain tools or integrate APIs such as Wikipedia lookup or weather fetching for richer assistant capabilities.
  • Customize Telegram Message Format: Adjust the parse_mode parameter in Telegram nodes to Markdown if preferred for different text styling.
  • Multi-language Support: Extend prompts and system messages in the AI Agent node to support multiple languages, enhancing global usability.

Troubleshooting 🔧

Problem: "Webhook not triggering on incoming Telegram messages"

Cause: Telegram bot webhook URL not correctly set or bot permissions missing.

Solution:

  1. Verify the webhook URL generated by the Telegram Trigger node is properly registered in your Telegram Bot API settings.
  2. Ensure your bot has permission to receive messages (bot privacy settings).
  3. Confirm n8n webhook endpoint is publicly accessible.

Problem: "AI Agent returns empty or irrelevant responses"

Cause: Incorrect session key setup or missing AI model credentials.

Solution:

  1. Double-check the Window Buffer Memory session key uses dynamic chat IDs.
  2. Verify OpenAI credentials are valid and connected.
  3. Test the OpenAI Chat Model node independently for expected outputs.

Pre-Production Checklist ✅

  • Test Telegram bot can receive and send messages manually using Telegram app.
  • Verify OpenAI API key permissions for both GPT-4 and Dall-E 3 usage.
  • Check all node connections and expressions for dynamic chat ID references.
  • Run test conversations including image requests to confirm end-to-end response flow.
  • Backup your workflow JSON export before major changes.

Deployment Guide

Once tested, activate the workflow in n8n by toggling the active switch. Ensure your n8n instance is running with stable internet and correct API credentials.

Monitor executions via n8n’s built-in execution log to review any errors or performance bottlenecks. Adjust AI model parameters as needed to optimize response quality.

FAQs

Can I use other AI models instead of GPT-4?

Yes, you can replace the OpenAI Chat Model node's model parameter with other available models like GPT-3.5 or custom fine-tuned variants.

Will this workflow consume my OpenAI API quota quickly?

AI processing and image generations do use your API calls but can be managed by controlling request frequency and model complexity to avoid excessive costs.

Is user data safe with this automation?

Your data is transmitted securely via Telegram and OpenAI APIs, but always ensure compliance with data privacy regulations depending on your use case.

Conclusion

By following this guide, you have built a sophisticated Telegram AI chatbot that uses Langchain with OpenAI's GPT-4 and Dall-E 3 to deliver both text and image responses seamlessly. This automation saves you hours each week on conversation management and creative content sharing.

Next, consider adding voice command support or multi-language translation nodes to extend your bot's capabilities even further. With this foundation, efficient, rich, and engaging Telegram interactions are at your fingertips.

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