Automation

How to Create an n8n Telegram Workflow – Step-by-Step Guide

Build a Telegram chatbot in n8n that listens to messages, replies through an AI agent powered by Gemini, remembers context with Simple Memory, and logs every conversation to Google Sheets. No code required.

BTBitPixel TeamMay 28, 20265 min read16 views
How to Create an n8n Telegram Workflow – Step-by-Step Guide

Summarize this blog post with:

Telegram is one of the quickest places to put a chatbot in front of real users. There's no app-store review, no SDK to install, no Stripe verification, and you can ship something useful in an afternoon. Plug an LLM behind it and you have a 24/7 support agent, lead-capture form, or internal assistant — for less than what most teams spend on coffee.

This guide walks through wiring up a Telegram bot inside n8n that listens for messages, runs them through an AI agent powered by Google Gemini, keeps a short memory of the conversation so it doesn't lose context between turns, and logs every exchange into a Google Sheet you can read later. The whole thing is built in n8n's visual editor — no code required.

By the end you'll have: a working Telegram bot with its own @username, an AI agent that can hold a multi-turn conversation, a Google Sheet that fills up with every interaction (great for CRM/lead-tracking), and a workflow you can extend with payments, file handling, calendar bookings, or any of n8n's 400+ integrations.

What We're Building

The finished workflow has three top-level nodes wired in a straight line: a Telegram Trigger that fires on every incoming message, an AI Agent that decides what to say, and a Telegram Send Message node that delivers the reply back to the user. Three smaller tools hang off the AI Agent — Gemini (the brain), Simple Memory (short-term context window), and Google Sheets (read + write).

text
Telegram Trigger
   ↓
AI Agent
   ├── Chat Model:  Google Gemini
   ├── Memory:      Simple Memory (per-chat)
   ├── Tool:        Google Sheets — Get Row
   └── Tool:        Google Sheets — Update Row
   ↓
Telegram Send Message

Each arrow is a wire you drag in the n8n canvas. Each tool is a separate node you attach to one of the AI Agent's three slots: Chat Model, Memory, and Tool. We'll build them in roughly that order.

Why Build a Telegram AI Bot in the First Place?

Before you start clicking around the n8n editor, it's worth being honest about whether this stack is the right fit. Here's where it shines:

  • First-line customer support — answer pricing, onboarding, and "how do I…" questions without paying for Intercom or Zendesk.
  • Lead capture — qualify inbound interest, collect contact details, and drop new leads straight into your sales sheet.
  • Internal team assistant — give your ops/finance/sales team a private bot that looks up data, summarises docs, or triggers actions.
  • E-commerce order tracker — let customers check order status by sending an order number, with no login flow.
  • Content moderation — pre-screen submissions to a community group before they go live.
  • Notifications + chat-back — push alerts to users and let them reply naturally, with the agent routing the response.

Where it doesn't shine: anything that needs end-to-end encryption guarantees, regulated data flows (HIPAA, finance — Telegram's TOS doesn't cover you), or extremely high throughput (more than a few hundred messages per second on a single bot). For those, you'll want a dedicated chat infrastructure.

Telegram is also the easiest place to prototype before committing to WhatsApp Business API, which costs money per conversation and requires Meta business verification. Build it on Telegram, prove the value, then port to WhatsApp once revenue justifies the friction.

Prerequisites

  • A running n8n instance — self-hosted (we have a guide on installing n8n on AWS EC2, linked below) or n8n Cloud. Either works identically.
  • A Telegram account on any device. The mobile app is fine; you don't need a desktop client.
  • A Google account with access to Google Sheets. A free personal account is enough for this tutorial.
  • A Gemini API key from Google AI Studio (aistudio.google.com → "Get API Key"). The free tier covers about 15 requests per minute on gemini-1.5-flash, which is plenty for testing and small production loads.
  • About 45–60 minutes if you're new to n8n; 15 minutes if you've built workflows before.

Step 1 – Create a Telegram Bot with BotFather

BotFather is Telegram's official bot for managing bots. You talk to it through Telegram itself — no external dashboard. Every bot you'll ever create starts here.

Register the bot

Open Telegram and search for the user @BotFather (yes, the F is capital, and yes, it's verified with a blue tick). Start a chat and send /newbot. BotFather will ask for two things in sequence:

  • Display name — what users see in chat headers. Can be anything, e.g. "Acme Support".
  • Username — the @handle people use to find your bot. Must be unique across all of Telegram and must end in "bot" (e.g. acme_support_bot).

Once you confirm both, BotFather returns an HTTP API token that looks like this:

text
7340492:AAEhBP8oFp_a1b2c3d4e5f6g7h8i9j0klmnop

Copy it somewhere safe — you'll paste it into n8n in the next step. If you ever lose it or suspect it's been leaked, send /revoke to BotFather to get a fresh one.

Polish the bot profile (optional but recommended)

While you're still in the BotFather chat, set a few extras that make the bot feel finished:

  • /setdescription — the long text users see before they hit Start.
  • /setabouttext — the short text on the bot's profile card.
  • /setuserpic — a 512x512 avatar (use your logo).
  • /setcommands — a menu of slash commands like /help, /start, /reset that shows up in the Telegram UI.

Treat the bot token like a database password. Anyone who has it can send and receive messages as your bot, read every conversation, and impersonate the bot to your users. Never commit it to git, never paste it in a public thread, and rotate it the moment you suspect a leak.

Step 1 – BotFather creating a new bot

Step 2 – Add the Telegram Trigger Node

Inside n8n, create a new workflow (top-right "+ Add workflow") and click the big "+" on the canvas to add the first node. Search for "Telegram Trigger" — there are two Telegram entries in the list, you want the one marked Trigger, not the regular action node.

Set up the credentials

In the Credentials dropdown, click "Create New". Give the credential a sensible name (e.g. "Acme Support Bot"), paste your BotFather token into the Access Token field, and save. n8n stores credentials encrypted at rest, so the raw token never appears in the workflow JSON or logs.

Choose which updates fire the workflow

Back on the trigger node, you'll see an "Updates" field. The defaults work for most cases:

  • message — every new text message, photo, or document sent to your bot. This is the one you want for a chatbot.
  • edited_message — fires when a user edits a previously sent message. Useful if you want to re-process corrections.
  • callback_query — fires when a user clicks an inline keyboard button (Yes/No prompts, menu choices).
  • channel_post — fires when a message is posted to a channel the bot is in. Skip this unless you're moderating channels.

Pick "message" for now. We can add the others later if the bot grows.

Webhook vs polling

Under the hood, n8n's Telegram Trigger uses webhooks — Telegram pushes a JSON payload to a public URL the moment a message arrives. That means your n8n instance must be reachable from the public internet over HTTPS. If you're on n8n Cloud, this is handled for you. If you're self-hosting, set the WEBHOOK_URL env var to your public domain (e.g. https://n8n.yourdomain.com) and make sure your reverse proxy is forwarding /webhook/* to n8n. Localhost won't work — Telegram refuses to send updates to non-public URLs.

Smoke-test the trigger

Click "Execute Step" (the play icon on the node), then open Telegram and send /start to your bot. n8n should light up with the incoming payload — chat ID, user ID, first name, message text, timestamp. That's your first successful trigger. If nothing happens after 10 seconds, the most likely culprit is webhook reachability — see the gotchas section at the end.

Step 2 – Telegram Trigger node in n8n

Step 3 – Add the AI Agent Node

Click the "+" on the right side of the Telegram Trigger and search for "AI Agent". You'll see two variants: Tools Agent and Conversational Agent. Pick Tools Agent — it's the one that can call external tools (our Google Sheets nodes), reason about which tool to use, and handle multi-step plans. The Conversational variant is text-only.

Configure the prompt source

Open the agent node and set Prompt to "Define below". This gives you a free-text System Prompt field where you write the bot's personality, knowledge boundaries, and behaviour rules. A useful starting template:

text
You are a friendly customer-support assistant for Acme Co.

What you can help with:
- Pricing and plan questions
- Onboarding and account setup
- Logging new leads into our Google Sheet
- Looking up existing customer details when asked

Rules:
- Keep replies under 3 sentences unless the user asks for detail.
- Never invent prices or features. If unsure, say you'll connect them with a human.
- When a user provides an email or phone number, call the Google Sheets Update Row tool to log it.
- Always greet by first name if you know it.

User message: {{ $json.message.text }}

Pull the user's message into the prompt

The {{ $json.message.text }} expression at the bottom is what wires the Telegram message into the prompt. n8n's expression language uses double curly braces and supports JavaScript inside them, so you can do things like {{ $json.message.text.toLowerCase() }} or {{ $json.message.from.first_name || 'there' }}.

The system prompt is the single most important lever in the whole workflow. Being specific about industry, tone, what to avoid, and when to call tools makes a much bigger difference than swapping models. Spend 10 minutes here — not 10 minutes hunting for a better LLM.

Step 3 – AI Agent node configuration

Step 4 – Connect Gemini as the Chat Model

With the AI Agent selected, you'll notice three sub-slots underneath it on the canvas: Chat Model, Memory, and Tool. Click the Chat Model slot — a little dotted box marked "+ Chat Model" — and pick "Google Gemini Chat Model" from the list.

Add the API key

Create new credentials, paste your Gemini API key from Google AI Studio, and save. Pick a model from the dropdown. The defaults for most chatbots:

  • gemini-1.5-flash — fast, very cheap, good enough for support-style chat. ~$0.075 per million input tokens.
  • gemini-1.5-pro — better reasoning, longer context (2M tokens), about 10× the cost of Flash. Use it for complex multi-step workflows or document analysis.
  • gemini-2.0-flash — newer, faster, similar pricing to 1.5-flash. Worth testing if you need lower latency.

Why Gemini for a Telegram bot?

There's nothing magic about Gemini here — you could swap in OpenAI's gpt-4o-mini or Anthropic's Claude Haiku and the workflow is identical. We pick Gemini Flash because its free tier (15 requests/minute) is the most generous of the three, which matters when you're prototyping and don't want to think about billing yet. For production, do a quick A/B with Claude Haiku or gpt-4o-mini and pick whichever gives better answers on your actual prompts.

Step 4 – Google Gemini Chat Model connected to the AI Agent

Step 5 – Add Simple Memory

Without memory, every user message gets treated as a fresh conversation. The bot won't remember that the user said their name was Priya two messages ago, won't remember the order number they just gave, and will keep re-introducing itself. Memory fixes that.

Attach the memory node

Click the Memory slot under the AI Agent and pick "Simple Memory". It's the n8n built-in option — no extra credentials or services needed. Behind the scenes it just stores the last N message turns in the workflow's in-memory store.

Set the Session ID per chat

The single most important setting here is Session ID. Without it, every user's messages end up in the same memory window — which is both a privacy hole and a context disaster. Set the Session ID expression to:

text
{{ $json.message.chat.id }}

Each Telegram chat has a unique numeric chat ID. Using it as the session ID means every user gets their own private memory window — no cross-contamination, no privacy issues.

Tune the window size

Set "Context Window Length" to somewhere between 5 and 15. Five means the bot remembers the last 5 user-assistant pairs (10 messages); fifteen means 15 pairs. Bigger windows mean more accurate continuation but higher token costs. For most support bots, 8–10 is the sweet spot.

Simple Memory is in-memory only. When the workflow restarts or your n8n instance reboots, every conversation resets. For persistent memory across restarts, swap Simple Memory for a Postgres-backed memory node or a vector store like Pinecone — but only when the trade-off is worth the extra complexity.

Step 5 – Simple Memory node attached to the AI Agent

Step 6 – Add the Google Sheets Get Row Node

Now we give the AI Agent the ability to read from a Google Sheet. Click the Tool slot under the AI Agent and search "Google Sheets — Get Row(s)". This is one of n8n's "AI-enabled" Google Sheets variants, which means it exposes itself as a tool the agent can call autonomously.

Connect Google

Create new credentials and run through the OAuth flow. Sign in with the Google account that owns the spreadsheet you want the bot to read. Once authorised, n8n stores the refresh token; you won't have to log in again.

Pick the spreadsheet and sheet

Select the spreadsheet from the dropdown (or paste the Sheet ID — the long string from the URL). Pick the specific tab. For this tutorial, assume a sheet with columns: chat_id, name, email, phone, status, last_message, updated_at.

Write a clear tool description

Below the credentials, you'll find a "Tool Description" field. This is what the AI Agent reads to decide whether to call this tool. Be explicit:

text
Look up an existing lead or customer by their Telegram chat_id, email, or phone number. Returns their full record so you can personalise the reply. Use this BEFORE asking the user for details they may have already given.

A vague description ("Get data from sheet") leads to either over-use or under-use of the tool. A clear one — what it returns and when to use it — gives the agent reliable behaviour.

Step 6 – Google Sheets Get Row node

Step 7 – Add the Google Sheets Update Row Node

Click the Tool slot again and add "Google Sheets — Update Row". Same credentials, same spreadsheet. This is the write path — how the agent saves data back.

Map columns to agent outputs

In the Columns section, set each column's value to an expression the agent can fill in at runtime. Use n8n's "Define Below" mode and let the agent generate the values. The matching column for lookups should be chat_id (so updates target the right row).

Write an explicit tool description

text
Save or update a lead's details — name, email, phone, status, last_message — matched by their chat_id. Call this whenever the user provides a new piece of contact info, confirms an order, or finishes a conversation. The chat_id is always available in the incoming message.

Notice the description tells the agent both what the tool does AND when to call it. Tool descriptions are a form of prompt engineering — the more specific, the better the agent's tool-use decisions.

Step 7 – Google Sheets Update Row node

Why Use Google Sheets?

There are objectively fancier options — Airtable for richer schemas, Notion for prose-style records, Postgres for proper data hygiene, HubSpot or Salesforce for full CRM features. For a first-version chatbot, though, Google Sheets is hard to beat:

  • Save user messages as they come in — one row per conversation, one column per turn.
  • Store chatbot history per chat ID — useful for retraining and debugging.
  • Build a lightweight AI conversation log without paying for a separate logging service.
  • Manage leads without paying for a CRM — your sales team can sort, filter, and assign directly in the sheet.
  • Trigger downstream automations from the sheet — Apps Script, Zapier, Make, or more n8n.
  • Share the sheet read-only with stakeholders who want to peek at the bot's output.

When to outgrow it: you're past a few thousand rows and queries are slow, multiple agents are writing to the same row and you're hitting race conditions, or you need joins/foreign keys/complex queries. At that point, port the schema to Postgres or Supabase and use n8n's database nodes instead.

Step 8 – Send the Reply Back to Telegram

The AI Agent has produced a reply, but we still need to deliver it. Click the "+" on the right side of the AI Agent node and add a regular Telegram node (not the Trigger). Pick the same credentials you used in Step 2.

Set the operation

In the Resource dropdown choose "Message", and in Operation choose "Send Message". Then fill in:

  • Chat ID: {{ $('Telegram Trigger').item.json.message.chat.id }} — always pull this from the trigger, never from the agent.
  • Text: {{ $json.output }} — the agent's reply.
  • Parse Mode: Markdown (lets the agent return bold, italics, and inline code blocks).

Add inline buttons (optional)

If you want to ship clickable Yes/No buttons, scroll down to "Reply Markup" and add an inline keyboard. The buttons fire a callback_query back to the trigger — which is why you may want to enable that update type in Step 2 later on.

Step 8 – Telegram Send Message node configuration

Final Workflow

Save the workflow with the disk icon, flip the toggle in the top-right from Inactive to Active, and message your bot. Your canvas should now look like this:

text
Telegram Trigger
   ↓
AI Agent  ── Gemini Chat Model
   ↓        ── Simple Memory
   ↓        ── Google Sheets (Get Row + Update Row)
Telegram Send Message

Connected tools on the AI Agent:

  • Gemini AI
  • Simple Memory
  • Google Sheets (Get Row and Update Row)

Test the End-to-End Flow

Before showing the bot to anyone else, run it through a quick test sequence yourself. Open Telegram, find your bot by @username, and send:

  • /start — checks that the trigger fires and the agent introduces itself.
  • "My name is Priya, what plans do you have?" — tests that memory captures the name AND the agent answers from your system prompt.
  • "What was my name again?" — confirms memory is working.
  • "Please log my email as priya@example.com" — tests the Google Sheets Update Row tool.
  • Open the sheet and confirm the row appeared with the right chat_id, name, and email.

Reading the execution history

In n8n, click "Executions" in the left sidebar. Each run of the workflow shows up here with a green checkmark or red X. Click any run to see the exact JSON that flowed between every node — the message that came in, the tools the agent called, the values it passed to them, and the final reply. This is your single best debugging tool. If something looks off, 90% of the time the answer is in the execution view.

Going to Production: Hardening Tips

The version we just built works. It's not yet ready for real users. Five upgrades to make before opening the bot up:

1. Add an error-handling branch

Right-click the AI Agent and add an "On Error" output. Wire it to a fallback Telegram Send Message that says something like "Sorry, I hit an issue — a human will follow up shortly". Without this, errors bubble up as silence on the user's side, which feels broken.

2. Rate-limit per user

Drop a Function or Switch node between the Trigger and the AI Agent. Track how many messages each chat_id has sent in the last minute (you can use the workflow's static data store or a Redis node) and short-circuit with a polite "slow down" reply if the rate exceeds your threshold. This protects you against a single user accidentally — or maliciously — burning your Gemini quota.

3. Log execution metadata to a separate sheet

Add a second Update Row node that writes execution_id, chat_id, latency, tokens_used, and model into a logs sheet. You'll thank yourself the first time a user reports "the bot gave me the wrong answer" — you can replay the exact run.

4. Set a timeout on the AI Agent

In the agent node's options, set Max Iterations to 5 (default is unlimited). This prevents runaway tool-calling loops if the agent gets confused. Five iterations is plenty for a support bot and bounds your worst-case cost.

5. Pin your bot's Webhook URL

If you self-host n8n, set WEBHOOK_URL explicitly in your env vars and serve it behind HTTPS via Nginx or Caddy. Telegram will silently stop delivering messages if the URL ever returns a non-2xx response — and you won't get an alert unless you've wired one up.

What Does This Cost to Run?

A realistic monthly cost for a small-to-mid production deployment (around 1,000 conversations a month, each averaging 6 turns):

  • n8n hosting — $5–10/month on a DigitalOcean or AWS Lightsail $5 droplet, or $0 if you use n8n Cloud's free tier (1,000 executions/month).
  • Gemini 1.5 Flash API — ~$1–3/month at this volume. The free tier (15 RPM, 1500 RPD) likely covers it entirely.
  • Google Sheets — free. Quota is 5M cells per spreadsheet, plenty.
  • Telegram — free. No per-message charge, no business verification.

Total: $5–15/month for a production-grade Telegram AI bot serving roughly 6,000 messages. Compare that to typical SaaS chatbot platforms ($50–500/month) and the economics speak for themselves.

The single line item that can spike is the Gemini API bill. If you migrate to gemini-1.5-pro or you let conversations run very long, costs scale linearly with tokens. Add the rate-limit and logging from the hardening section above and you'll never get a surprise.

Real Use Cases This Same Workflow Powers

The bot you just built is a template — change the system prompt and the columns, and you have a different product. A few real shapes we see:

Lead-capture bot for B2B services

Replace the support prompt with a qualifying script (industry, team size, budget range, timeline). The agent asks the questions naturally over chat, writes the answers to a Sheet, and triggers an email to your sales team when the lead meets your criteria. We've seen this convert 3–5× better than a static contact form.

Internal team assistant

Point the Google Sheets tools at an internal data sheet (employee directory, vendor list, recurring expenses). Add the bot to a private Telegram group with your ops team. Now anyone can ask "who's our DigitalOcean account contact?" or "what's the Acme contract renewal date?" without digging through email.

Order tracker for e-commerce

Wire the Google Sheets tools (or swap for an Airtable or Postgres node) to your orders table. Users send their order number, the agent looks it up and replies with the status, tracking number, and ETA. Add a webhook from your fulfilment system to push status updates back to Telegram automatically.

Multilingual support over chat

Gemini handles 30+ languages well out of the box. Add a single line to the system prompt: "Detect the user's language and reply in the same language." Suddenly you have multilingual support without separate flows.

Things That Will Trip You Up

  • Forgetting to activate the workflow — n8n won't fire the trigger if the workflow is saved but inactive. The Active/Inactive toggle is in the top-right.
  • Using the wrong Chat ID expression in the Send Message node. Always pull it from the Telegram Trigger output ($('Telegram Trigger').item.json.message.chat.id), never from the AI Agent — the agent doesn't know about chat IDs.
  • Sheet permissions. The Google account behind your credentials needs Editor access to the spreadsheet, not just View. The OAuth flow won't tell you this until the first Update Row call fails.
  • Gemini API quota. The free tier is generous but will throttle if you burst dozens of requests in a few seconds while testing. Either wait 60 seconds or add a paid billing account to lift the limits.
  • Webhook URL. If you're self-hosting n8n, make sure WEBHOOK_URL is set to your public HTTPS domain — Telegram won't deliver to localhost or a non-2xx-returning URL.
  • Markdown parse errors. If the agent reply contains an unmatched asterisk or underscore and Parse Mode is set to Markdown, Telegram returns 400 Bad Request and the message never delivers. Either use the plain text mode or strip markdown in a Function node before sending.
  • Memory not isolating users. If you forget to set Session ID to {{ $json.message.chat.id }}, every user shares one memory window — both a privacy violation and a context mess.
  • Long-running tool calls. If the Get Row node takes more than 10 seconds (huge sheets), Telegram may show "typing" indefinitely and the user will think the bot is broken. Either narrow the lookup (use a specific row index) or paginate.

Test the workflow end-to-end before sharing your bot's username. A broken Telegram bot looks identical to a working one until the first message goes unanswered — and users rarely give it a second try.

Want a production-grade Telegram or WhatsApp bot wired into your CRM, ERP, or AI stack? BitPixel Coders builds custom n8n automations, AI agents, and chatbot workflows for businesses worldwide. Get in touch for a free workflow audit and we'll map out exactly what your use case needs.

Get a Free Consultation

Frequently Asked Questions

No. Every step uses n8n's visual node editor. The only "code" you write is a system prompt for the AI Agent in plain English and a couple of {{ }} expressions to pull data from earlier nodes. If you can write a thoughtful job description, you can write a useful system prompt.

Yes. In Step 4 swap the Chat Model node for "OpenAI Chat Model" or "Anthropic Chat Model" and use that provider's API key. The rest of the workflow stays identical. Pricing and free-tier limits differ — Claude Haiku is roughly comparable to Gemini Flash in cost; gpt-4o-mini is similar; gpt-4o is about 10× more expensive but noticeably stronger on nuanced replies.

Simple Memory holds context in process memory only, so it resets on workflow restart or n8n reboot. For persistent memory, swap it for a Postgres-backed memory node, Redis-backed memory, or a vector store like Pinecone. The trade-off is more moving parts; only upgrade once you genuinely need persistence.

Three viable options. (1) n8n Cloud's free tier — 1,000 executions per month, fastest to set up. (2) Self-hosted on AWS EC2, DigitalOcean, or Hetzner — $4–10/month for a small instance. (3) Docker on a Raspberry Pi at home — free but you need a tunnel like Cloudflare Tunnel to expose the webhook. We have a full guide on installing n8n on AWS EC2 — linked below.

Three usual suspects, in order of frequency. (1) The workflow isn't active — flip the Active toggle in the top-right. (2) The webhook URL isn't reachable from the internet — Telegram requires HTTPS and a 2xx response. Test by hitting your n8n /webhook/test URL from a browser. (3) The bot token is wrong — verify by visiting api.telegram.org/bot<TOKEN>/getMe in a browser. If you see your bot's info, the token is valid.

Yes — Telegram sends all of them through the same Trigger node. The payload includes file_id, which you pass to Telegram's getFile endpoint to get a temporary download URL. For images, plug them into a multimodal Chat Model (Gemini and gpt-4o both handle images). For voice notes, route through a Speech-to-Text node first (OpenAI Whisper, Google Speech-to-Text, or Deepgram).

Each bot has its own token from BotFather. In n8n, create a separate Telegram credential per bot, then duplicate the workflow and swap the credential. One n8n instance can comfortably run dozens of bots — execution is per-trigger, not per-bot.

Telegram cloud chats (which bots use) are NOT end-to-end encrypted — Telegram has access to message content. For most B2B use cases this is fine, but it's a non-starter for healthcare, financial PII, or anything covered by HIPAA or PCI. For regulated data, use a dedicated chat infrastructure or move to WhatsApp Business API with explicit encryption guarantees.

AB
Anju BattaSenior Full Stack Developer & AI Automation Architect

15+ years experience building web applications, AI automation systems, and cloud infrastructure. Delivered 500+ projects for clients worldwide at BitPixel Coders.

LinkedIn Profile →