Telegram AI Chatbot with Image Generation (OpenAI)

Overview

This workflow transforms a Telegram bot into an intelligent AI assistant powered by OpenAI's GPT-4 and DALL-E models. It automatically detects user language, responds conversationally with emojis, and can generate images on demand using the /image command. The workflow is ideal for building a friendly, multi-functional Telegram bot that handles both text conversations and image creation requests without requiring any manual intervention.

How It Works

Node-by-Node Breakdown

  1. Telegram Trigger (No auth) — Listens for all incoming Telegram messages (text, commands, etc.). This node uses a webhook to receive updates from Telegram in real-time. No authentication is required because Telegram's Bot API uses a token set at the bot level.

  2. PreProcessing (No auth) — A Set node that ensures the message.text field exists (defaults to empty string if missing). This prevents errors when the message has no text (e.g., stickers or photos). Uses dot notation to safely access nested JSON.

  3. Settings (No auth) — A Set node that defines configuration variables:

    • model_temperature: 0.8 (controls AI response creativity)
    • token_length: 500 (maximum response length)
    • system_command: A system prompt instructing the AI to detect the user's language, reply in the same language, include emojis, and use the user's first name
    • bot_typing: Dynamically sets the Telegram typing action — "upload_photo" if the message starts with /image, otherwise "typing"
  4. Send Typing action (Telegram API — Bot Token auth) — Sends a "typing" or "uploading photo" indicator to the user, providing real-time feedback while the AI processes the request. Uses the sendChatAction operation.

  5. Merge (No auth) — A branch merger node that combines the two parallel paths (Settings and Send Typing action) into a single output for the next node.

  6. CheckCommand (No auth) — A Switch node that routes the message based on its content:

    • Output 0 (default): Any text that doesn't start with / — routes to Chat_mode
    • Output 1: Messages starting with /start — routes to Greeting
    • Output 2: Messages starting with /image — routes to Create an image
    • Output 3 (fallback): Any other command — routes to Send error message
  7. Chat_mode (OpenAI — API Key auth) — Sends the user's message to OpenAI's GPT-4 chat completion endpoint. Uses the system prompt from Settings to guide the AI's behavior (language detection, emoji usage). Returns a natural language reply.

  8. Greeting (OpenAI — API Key auth) — Also uses GPT-4, but with a special prompt that welcomes the user in their detected language. Triggered only by the /start command.

  9. Create an image (OpenAI — API Key auth) — Uses OpenAI's DALL-E image generation model. Extracts the prompt by removing the /image prefix from the message text. Generates a single 512x512 image.

  10. Text reply (Telegram API — Bot Token auth) — Sends the AI's text response back to the user. Uses Markdown parsing for formatted replies. The chat ID is dynamically retrieved from the Settings node's output.

  11. Send image (Telegram API — Bot Token auth) — Sends the generated image to the user using the sendPhoto operation. The image URL comes from the OpenAI response.

  12. Send error message (Telegram API — Bot Token auth) — Sends a friendly error message when the user types an unsupported command, explaining how to use the /image command with examples.

Setup Instructions

Prerequisites

  1. Telegram Bot: Create a bot via @BotFather on Telegram. You'll receive a Bot Token (e.g., 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
  2. OpenAI Account: Sign up at platform.openai.com and create an API key with access to GPT-4 and DALL-E models.
  3. n8n Instance: This workflow requires n8n to be publicly accessible (for Telegram webhooks) or use n8n's cloud version.

Configuration Steps

  1. Telegram Trigger: No configuration needed beyond setting up the webhook. n8n will automatically register the webhook URL with Telegram when you activate the workflow.
  2. OpenAI nodes: Add your OpenAI API key as a credential in n8n (Settings → Credentials → OpenAI). Select this credential in both Chat_mode, Greeting, and Create an image nodes.
  3. Telegram nodes: Add your Telegram Bot Token as a credential in n8n (Settings → Credentials → Telegram API). Select this credential in Send Typing action, Text reply, Send image, and Send error message nodes.
  4. Activate: Toggle the workflow to active. The Telegram Trigger will register the webhook automatically.

Use Cases and Variations

Primary Use Cases

  • Customer support bot: Replace the system prompt with company-specific instructions and knowledge base.
  • Language learning assistant: The built-in language detection makes it perfect for practicing foreign languages.
  • Creative companion: Generate images on demand for inspiration, design mockups, or fun.

Adaptation Ideas

  • Add memory: Connect a database (e.g., Redis, PostgreSQL) to store conversation history for context-aware responses.
  • Custom commands: Extend the CheckCommand switch to handle more commands like /help, /about, or /translate.
  • Change AI model: Swap GPT-4 for GPT-3.5-turbo to reduce costs, or use a local model via Ollama.
  • Image variations: Modify the Create an image node to generate multiple images or different sizes.
  • Moderation: Add a filter node before sending replies to block inappropriate content.
  • Multi-bot: Duplicate the workflow for different Telegram bots with different personalities or purposes.
16 nodesmanual triggerAI
SwitchSticky NoteSetOpen AITelegramMerge

Workflow JSON

{
  "id": "177",
  "meta": {
    "instanceId": "dfdeafd1c3ed2ee08eeab8c2fa0c3f522066931ed8138ccd35dc20a1e69decd3"
  },
  "name": "Telegram AI-bot",
  "tags": [
    {
      "id": "15",
      "name": "tutorial",
      "createdAt": "2022-10-04T20:07:25.607Z",
      "updatedAt": "2022-10-04T20:07:25.607Z"
    }
  ],
  "nodes": [
    {
      "id": "ea71a467-a646-4aca-b72e-cef1249c74e2",
      "name": "Telegram Trigger",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        20,
        340
      ],
      "webhookId": "51942fbb-ca0e-4ec4-9423-5fcc7d3c4281",
      "parameters": {
        "updates": [
          "*"
        ],
        "additionalFields": {}
      },
      "credentials": {
        "telegramApi": {
          "id": "70",
          "name": "Telegram bot"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "1cbe43d4-ea8b-4178-bc10-4bfad7abe143",
      "name": "CheckCommand",
      "type": "n8n-nodes-base.switch",
      "position": [
        980,
        360
      ],
      "parameters": {
        "rules": {
          "rules": [
            {
// ... truncated (copy to see full JSON)

How to Import This Workflow

  1. 1Copy the workflow JSON above using the Copy Workflow JSON button.
  2. 2Open your n8n instance and go to Workflows.
  3. 3Click Import from JSON and paste the copied workflow.

Don't have an n8n instance? Start your free trial at n8nautomation.cloud

Related Templates

Automated Blog Post Creation from News with AI and Blogger

This workflow automates the entire process of creating a fully SEO-optimized blog post from a news article. It fetches a trending technology news headline from Mediastack, generates relevant images from Pexels, uses two AI agents (via OpenRouter) to produce a title, slug, meta description, and a complete WordPress-compatible HTML blog post, then posts it directly to Blogger and sends you a Telegram notification. It's perfect for content marketers, bloggers, or anyone who wants to consistently publish fresh, data-driven content without manual effort. Node Breakdown Schedule Trigger (No auth) — Runs the workflow at a set interval (configured every minute by default, but you should change it to daily or hourly). Mediastack News (API Key auth via query parameter) — Fetches the latest technology news article in English from the Mediastack API. Parameters: set to . Genarate image (API Key auth via header, ) — Searches Pexels for up to 2 images related to the news title. Parameters: = , = 2. Send a text message1 (Telegram bot token auth) — Sends a Telegram message with the generated image URLs to the chat ID stored in . AI Agent (Uses OpenRouter Chat Model — API Key auth) — This agent takes the news title and returns a JSON object with three fields: , , and (meta description). The prompt includes strict guidelines for SEO-friendly output. OpenRouter Chat Model (API Key auth) — The language model for the first AI agent, using . Parsing (No auth) — A Code node that cleans the raw AI output (removes markdown code fences) and parses the JSON into usable fields. Copywriter AI Agent (Uses OpenRouter Chat Model2 — API Key auth) — This agent writes a complete 1,000-word SEO blog post in HTML format. It uses the title, meta, and the two images from Pexels. The prompt is very detailed, specifying structure, keyword placement, and styling. OpenRouter Chat Model2 (API Key auth) — Same model as the first, but used for the second agent. Cleanup HTML (No auth) — A Set node that removes any leftover htmlurlhttps://www.googleapis.com/blogger/v3/blogs/$vars.bloggerid/postsPOSThttpQueryAuthAuthorization$vars.telegramchatid$vars.bloggeridbusinesssports`) to match your niche. Multi-language Support — Modify the Mediastack query to fetch news in other languages, and adjust the AI prompts to write in that language. Custom Image Sources — Replace the Pexels node with another image API (e.g., Unsplash) or use a local image generation model. Different CMS — Swap the Blogger HTTP Request node with WordPress or any other CMS API (just change the URL and body format). Human-in-the-Loop — Add a Slack or email approval step before publishing to review the AI-generated content. Newsletter Integration — Instead of posting to a blog, send the formatted content as an email newsletter via Gmail or SendGrid.

16 nodes

AI Chat Agent with OpenAI, Memory, and Web Search

Overview This workflow creates an intelligent AI chat agent that combines OpenAI's language model with conversational memory and real-time web search capabilities via SerpAPI. It is designed to power interactive chat applications where the AI can remember context across messages and fetch up-to-date information from the internet when needed. This is particularly useful for building customer support bots, research assistants, or any conversational interface that requires both knowledge retention and live data access. The workflow is triggered by incoming chat messages and processes them through an AI agent that coordinates between the language model, memory buffer, and search tool. The agent can decide when to use web search to answer questions that require current information, while maintaining conversation history for coherent multi-turn dialogues. Workflow Steps Manual Trigger (No auth) — This node allows you to manually start the workflow for testing purposes. It has no parameters configured and simply provides a button to execute the workflow on demand. When chat message received (No auth) — This is a webhook-based trigger that listens for incoming chat messages. It generates a unique webhook URL that you can integrate with your chat frontend or messaging platform. The parameter is empty, meaning default webhook behavior is used. AI Agent (No auth) — This is the core orchestrator node that manages the conversation flow. It coordinates between the OpenAI model, memory buffer, and SerpAPI tool. The agent decides which tool to use based on the user's query and maintains the conversation state. OpenAI Chat Model (API Key auth) — This node connects to OpenAI's GPT-4o-mini model to generate responses. It requires an OpenAI API key configured in n8n credentials. The parameter is set to , which is a cost-effective and fast model suitable for chat applications. The parameter is empty, using default model settings. Window Buffer Memory (No auth) — This node implements a sliding window memory that stores recent conversation history. It allows the AI to remember context from previous messages within a configurable window size. The parameters are empty, using default memory settings. SerpAPI (API Key auth) — This tool node enables web search functionality via SerpAPI (Google Search API). It requires a SerpAPI API key configured in n8n credentials. The parameter is empty, using default search settings. The agent calls this node when it determines that real-time web data is needed to answer a query. Setup Instructions To use this workflow, you need the following accounts and credentials: OpenAI Account: Sign up at platform.openai.com and create an API key. In n8n, create an "OpenAI" credential and paste your API key. SerpAPI Account: Register at serpapi.com and obtain an API key. In n8n, create a "SerpAPI" credential with your key. Webhook URL: After activating the workflow, copy the webhook URL from the "When chat message received" node. Integrate this URL into your chat application (e.g., a custom web chat widget, Slack app, or Telegram bot). Optional: Configure the memory window size in the "Window Buffer Memory" node if you want to limit or extend conversation context. Use Cases and Variations This workflow can be adapted for multiple scenarios: Customer Support Bot: Replace SerpAPI with a knowledge base tool (e.g., vector store or database lookup) to answer product-specific questions. Research Assistant: Keep SerpAPI for web search and add additional tools like Wikipedia or news APIs. Multi-Platform Chat: Connect the webhook to different messaging platforms (Slack, Discord, Telegram) by adding appropriate trigger nodes. Personal Assistant: Add calendar or email tools to let the AI manage schedules and send messages. Language Translation: Replace the OpenAI model with a translation-specific model or add a translation tool node. To extend the workflow, you can add more tool nodes (e.g., database queries, file operations) and connect them to the AI Agent. The agent will automatically learn to use new tools based on their descriptions.

6 nodes

AI Blog Generator For WordPress Posts

AI Blog Generator For WordPress Posts This workflow automates the creation of blog post drafts by combining an n8n form, OpenAI's language model, and WordPress. It's designed for content creators, marketers, and bloggers who want to overcome writer's block and streamline their content pipeline. Instead of starting from a blank page, you submit a topic, target audience, and key points through a simple form, and the workflow generates a structured, well-written draft ready for your review and editing in WordPress. The core value of this workflow is its efficiency. It transforms a time-consuming task—writing a first draft—into a quick, structured process. By keeping the output as a 'draft' in WordPress, it ensures that nothing goes live without your final approval, maintaining editorial control. The workflow also includes thoughtful touches like automatic retries for the AI call and clear instructions for troubleshooting, making it robust and user-friendly. Workflow Nodes and Steps Here is a step-by-step breakdown of the workflow: Setup — read me first (Sticky Note) — Provides an overview, setup time, level, and links to the creator's site. How it runs (Sticky Note) — Explains the workflow's logic and data flow. If something breaks (Sticky Note) — Offers guidance on error handling and setting up an error workflow. Draft Request Form (Form Trigger) — This node hosts a web form with fields for 'Topic', 'Audience', and 'Key points (one per line)'. It starts the workflow when the form is submitted. (No auth required for the form itself). Write Draft (OpenAI) — This node uses the model to generate the blog post. It receives the form data and uses a carefully crafted prompt to produce a title and body in HTML format. (API Key auth). Split Title and Body (Code) — A JavaScript code node that parses the AI's response, extracting the title and the HTML body content into separate fields for the next step. (No auth). Create WordPress Draft (WordPress) — This node creates a new post in WordPress with the generated title and content, setting the status to 'draft' so it's not published immediately. (Application Password auth). Setup Instructions To use this workflow, you will need the following: OpenAI Account: You need an API key from OpenAI. Create an account at platform.openai.com, go to the API keys section, and create a new secret key. Add this key to the 'Write Draft' node's credentials. WordPress Site: You need a self-hosted WordPress.org site (not WordPress.com). To connect, you'll need to generate an Application Password. In your WordPress admin dashboard, go to Users > Profile and scroll down to the 'Application Passwords' section. Create a new one and use those credentials in the 'Create WordPress Draft' node. Activate the Workflow: After connecting your credentials, activate the workflow in n8n. The 'Draft Request Form' node will provide a production URL. Bookmark this URL to access your form. Use Cases and Variations Content Calendars: Integrate this with a Google Sheets node to log all generated drafts and their statuses. Multi-Platform Publishing: Add a step to convert the HTML draft to Markdown and send it to other CMSs like Ghost or Dev.to. SEO Optimization: Insert a node to analyze the generated content for keywords or readability scores before creating the WordPress post. Team Collaboration: Instead of a public form, trigger the workflow from a Slack command or email, allowing your team to submit topics without leaving their communication tools. Different Content Types: Modify the prompt in the 'Write Draft' node to generate other content formats like product descriptions, social media posts, or email newsletters.

7 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.