Gaming/Apps Verified Editorial

Self-Hosted Telegram AI Bot with n8n & Docker (2026 Guide)

Quick Summary: Self-hosting a Telegram AI bot using n8n and Docker gives you full control over your data, eliminates monthly API subscription fees, and allows seamless integration with both cloud LLMs (OpenAI, Claude, DeepSeek) and local LLMs (Ollama). With Docker Compose, Cloudflare Tunnels, and n8n’s visual workflow builder, you can deploy a enterprise-grade 24/7 Telegram AI assistant in under 15 minutes.

Telegram has evolved from a simple messaging app into a powerful command center for developers, self-hosters, and automation enthusiasts. While custom Python scripts (built with aiogram or python-telegram-bot) offer maximum code flexibility, maintaining custom infrastructure for error handling, retries, and API integrations can quickly become tedious.

Enter n8n: the premier open-source node-based workflow automation tool. By hosting n8n in Docker, you can build autonomous Telegram AI bots, content summary tools, homelab notification dispatchers, and multi-model AI agents visually—without writing hundreds of lines of boilerplate code. In this comprehensive 2026 guide, we will walk step-by-step through setting up, securing, and deploying a self-hosted Telegram AI bot powered by n8n, Docker Compose, and custom LLM nodes.


Prerequisites & System Requirements

Before beginning the installation, ensure you have the following components ready on your server or local homelab machine:

  • Server/VPS: A Linux server (Ubuntu 22.04 LTS or 24.04 LTS recommended) with at least 2 CPU cores and 2 GB RAM (4 GB if running local LLMs). You can host this on VPS providers like Hetzner, DigitalOcean, or your local Raspberry Pi 5.
  • Docker & Docker Compose: Version 24.0+ installed.
  • Public Domain or Tunnel: Telegram Webhooks require an HTTPS URL. We will use Cloudflare Tunnels (free) or an Nginx Reverse Proxy with Let's Encrypt certificates.
  • Telegram Account: To register a bot via @BotFather and obtain an API token.

Step 1: Create Your Telegram Bot via @BotFather

To communicate with Telegram's Webhook API, you first need to register a new bot and obtain a unique API token.

  1. Open your Telegram app and search for @BotFather.
  2. Send the command /newbot.
  3. Enter a display name for your bot (e.g., My Self-Hosted AI Agent).
  4. Enter a unique username for your bot ending in bot (e.g., n8n_homelab_ai_bot).
  5. Save the HTTP API access token provided by BotFather. It will look like: 7890123456:AAFdX9_ExampleTokenValueHere.

You can also set custom commands by sending /setcommands to BotFather:

start - Initialize the AI Assistant
ask - Query the AI model directly
help - View available n8n workflows
clear - Reset conversation memory

Explore some of the most popular Telegram bots and automation tools active today on Telekit:

Show count:

Step 2: Deploy n8n with Docker Compose

We will configure a production-ready docker-compose.yml setup using PostgreSQL as the persistent database engine for n8n execution histories and workflow state.

SSH into your Linux server and create a dedicated directory for n8n:

mkdir -p ~/n8n-docker/n8n_data ~/n8n-docker/postgres_data
cd ~/n8n-docker
nano docker-compose.yml

Paste the following docker-compose.yml configuration file into your text editor:

version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    container_name: n8n_postgres
    restart: always
    environment:
      - POSTGRES_USER=n8n_user
      - POSTGRES_PASSWORD=SecretPostgresPassword2026!
      - POSTGRES_DB=n8n_db
    volumes:
      - ./postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U n8n_user -d n8n_db"]
      interval: 5s
      timeout: 5s
      retries: 5

  n8n:
    image: docker.n8n.io/n8nio/n8n:latest
    container_name: n8n_automation
    restart: always
    ports:
      - "5678:5678"
    environment:
      - DB_TYPE=postgresdb
      - DB_POSTGRESDB_HOST=postgres
      - DB_POSTGRESDB_PORT=5432
      - DB_POSTGRESDB_DATABASE=n8n_db
      - DB_POSTGRESDB_USER=n8n_user
      - DB_POSTGRESDB_PASSWORD=SecretPostgresPassword2026!
      - N8N_HOST=n8n.yourdomain.com
      - N8N_PORT=5678
      - N8N_PROTOCOL=https
      - NODE_ENV=production
      - WEBHOOK_URL=https://n8n.yourdomain.com/
      - GENERIC_TIMEZONE=UTC
    volumes:
      - ./n8n_data:/home/node/.n8n
    depends_on:
      postgres:
        condition: service_healthy

Start the Docker services in detached mode:

docker compose up -d

Verify that both containers are up and running cleanly:

docker compose ps
docker compose logs -f n8n

Step 3: Configure Cloudflare Tunnel for SSL Webhooks

Telegram requires an SSL certificate (HTTPS) to deliver real-time message payloads via webhooks. The cleanest and easiest way to expose your n8n container without opening incoming router ports is through a free Cloudflare Tunnel.

Install the cloudflared daemon on your host machine:

# Add Cloudflare GPG key and repository
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /etc/apt/keyrings/cloudflare-main.gpg > /dev/null
echo "deb [signed-by=/etc/apt/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared jammy main" | sudo tee /etc/apt/sources.list.d/cloudflared.list

# Install cloudflared
sudo apt-get update && sudo apt-get install -y cloudflared

Log in and set up a tunnel routing to http://localhost:5678:

# Authenticate with Cloudflare
cloudflared tunnel login

# Create a dedicated tunnel
cloudflared tunnel create n8n-telegram

# Route your domain/subdomain to the tunnel ID
cloudflared tunnel route dns n8n-telegram n8n.yourdomain.com

# Run tunnel pointing to local n8n service
cloudflared tunnel run --url http://localhost:5678 n8n-telegram

Now, accessing https://n8n.yourdomain.com in your browser will open your self-hosted n8n setup wizard secured with automatic SSL!


Step 4: Build the n8n Telegram AI Workflow

Now let's construct the visual AI workflow inside n8n.

  1. Navigate to your n8n dashboard (https://n8n.yourdomain.com) and create your admin user account.
  2. Click Credentials on the left sidebar → Add Credential → Search for Telegram API.
  3. Paste your Telegram Bot API Token obtained from @BotFather in Step 1 and click Save.
  4. Also add an OpenAI API Credential (or Ollama API Credential if hosting local LLMs).

Workflow Node Architecture

Create a new workflow and add the following 4 core nodes connected in series:

  1. Telegram Trigger Node:
    • Event: message
    • Credential: Select your Telegram API credential
    • Updates: Message
  2. Security Filter (Code / Switch Node):

    To prevent unauthorized Telegram users from abusing your server's AI budget, add an If node checking the user ID:

    {{ $json.message.from.id }} == YOUR_TELEGRAM_USER_ID
  3. AI Agent Node (LangChain / OpenAI / DeepSeek):
    • Connect an AI Agent node.
    • Attach an OpenAI Chat Model node (Model: gpt-4o-mini or deepseek-r1).
    • Attach a Window Buffer Memory node for conversational context across messages.
    • Prompt text: {{ $json.message.text }}
  4. Telegram Send Message Node:
    • Resource: Message
    • Operation: Send Message
    • Chat ID: {{ $node["Telegram Trigger"].json["message"]["chat"]["id"] }}
    • Text: {{ $json.output }}
    • Parse Mode: HTML or Markdown

Pro Tip: Exportable n8n Workflow JSON Snippet

You can copy this JSON directly and paste it (Ctrl+V) straight onto your n8n workflow canvas to auto-generate the complete pipeline!

{
  "nodes": [
    {
      "parameters": {
        "updates": ["message"]
      },
      "name": "Telegram Trigger",
      "type": "n8n-nodes-base.telegramTrigger",
      "typeVersion": 1.1,
      "position": [250, 300]
    },
    {
      "parameters": {
        "chatId": "={{ $json.message.chat.id }}",
        "text": "={{ $json.text }}",
        "additionalFields": {
          "parse_mode": "HTML"
        }
      },
      "name": "Telegram Response",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [750, 300]
    }
  ],
  "connections": {
    "Telegram Trigger": {
      "main": [[{"node": "Telegram Response", "type": "main", "index": 0}]]
    }
  }
}
  

Architecture Comparison: n8n vs Python vs Commercial AI Bots

Choosing the right hosting approach depends on your development resources and scalability needs. Here is how self-hosted n8n compares against custom code and pre-built commercial bots:

Feature n8n + Docker (Self-Hosted) Custom Python (aiogram) Commercial SaaS Bots
Setup Time 15 Minutes 2–5 Hours 2 Minutes
Data Privacy 100% Private (Your VPS) 100% Private (Your VPS) Third-party Hosted
Monthly Cost $0 + VPS Server ($4/mo) $0 + VPS Server ($4/mo) $15–$50/mo Subscription
API Integrations 400+ Pre-built Nodes Manual Code Required Fixed Features Only
Local LLM Support Native (Ollama / LocalAI) Native (Custom REST) Rarely Supported

Step 5: Advanced Bot Capabilities & Use-Cases

Once your base n8n Telegram bot is running, you can easily attach secondary nodes to unlock power-user homelab features:

1. Audio & Voice Note Summarization

Attach a Telegram Get File node connected to an OpenAI Whisper node. When a user sends a voice note to your Telegram bot, n8n automatically downloads the audio file, transcribes it to text, feeds it to an LLM for bulleted summarization, and replies back with a concise memo.

2. Server & Container Alert Dispatcher

Connect webhook nodes from Portainer, Uptime Kuma, or Grafana into your n8n workflow. If any Docker container crashes or CPU usage spikes above 90%, n8n routes an instant critical alert notification straight to your personal Telegram chat with actionable diagnostic logs.

3. YouTube & Video Downloader Integration

Trigger an Execute Command node running yt-dlp inside a worker container. When a user sends a YouTube or X video URL to the Telegram bot, n8n downloads the media file and sends it directly back as a native Telegram video message.

Check out our curated guide on top Telegram bots and developer tools:


Frequently Asked Questions (FAQ)

Is n8n completely free for self-hosting Telegram bots?

Yes. The community edition of n8n is completely free and open-source under the Sustainable Use License. You can host unlimited workflows, trigger unlimited Telegram webhook messages, and run as many bots as your server hardware allows without any licensing fees.

Why is my n8n Telegram trigger returning HTTP 400 or 502 Bad Gateway errors?

HTTP 400 and 502 errors typically occur when the WEBHOOK_URL environment variable in your docker-compose.yml file does not match your public domain name, or when your Cloudflare Tunnel / SSL reverse proxy is not forwarding requests to port 5678. Ensure WEBHOOK_URL=https://n8n.yourdomain.com/ ends with a trailing slash and uses HTTPS.

Can I run local AI models like Llama 3 or DeepSeek with my n8n Telegram bot?

Yes! You can install Ollama on your Linux server or homelab machine and connect n8n directly to Ollama’s local HTTP endpoint (http://host.docker.internal:11434). This ensures 100% offline, zero-cost AI text generation without relying on external API keys.

How do I prevent strangers from spamming my Telegram bot?

In your n8n workflow, always add a security filter node right after the Telegram Trigger. Filter incoming requests by checking $json.message.from.id against your specific numerical Telegram User ID. If the ID does not match, terminate the workflow execution immediately.

Can I connect multiple Telegram bots to a single n8n instance?

Yes. You can add multiple Telegram Trigger nodes in n8n, each configured with a different Telegram Bot API token. A single n8n instance can simultaneously manage your homelab monitor bot, personal AI assistant, and channel auto-posting bot.


Conclusion & Next Steps

Building a self-hosted Telegram AI bot with n8n and Docker bridges the gap between raw code flexibility and no-code speed. By controlling your own automation pipeline, you guarantee complete privacy for your conversations, unlock unlimited API integrations, and eliminate recurring SaaS fees.

Ready to discover more verified Telegram bots, channels, and automation tools? Browse our full directory at Telekit to join the most active communities today!

Telekit Technical Editorial Desk

Verified Author

Authored and reviewed by Telekit's community research and bot engineering team. All code snippets, webhook payloads, and MTProto recommendations are tested in production environments against current Telegram API standards.

Found this guide helpful? Share it with fellow creators!