Bots · October 12, 2026 · 15 min read
How to Build a Telegram Bot with Node.js: A Complete Step-by-Step Guide from BotFather to Deployment
A hands-on, code-first walkthrough for building a Telegram bot in Node.js: registering it with BotFather, choosing between grammy and node-telegram-bot-api, handling commands and inline buttons, picking long polling vs webhooks, and deploying to a real server. Written for operators who want a bot that actually runs.
Why Node.js is the default choice for Telegram bots
Telegram bots are plain HTTPS programs that talk to the Telegram Bot API, and Node.js has become the default language for them for a simple reason: the Bot API is asynchronous, event-driven, and JSON-based, which is exactly the shape JavaScript and its async/await model are built for. You do not need a framework, a database, or a server farm to start — a single Node process can serve thousands of users on modest hardware because each update is a small, stateless HTTP exchange. This guide walks through the full path from a brand-new bot token to a deployed, webhook-backed bot handling commands and inline buttons. It is written for operators and indie developers who want a bot that actually runs in production, not a toy that works only on localhost. We use two libraries that together cover almost every Node Telegram project in the wild — grammy and node-telegram-bot-api — and explain when to reach for each. Nothing here promises search rankings or viral growth; the goal is a correct, maintainable bot you understand end to end.
Step 1 — Register your bot with BotFather and get a token
Every Telegram bot starts the same way: you talk to @BotFather, the official bot that manages bot accounts. Open Telegram, search for @BotFather, start it, and send /newbot. BotFather asks for a display name (what users see in chat, e.g. "Channel Economy Helper") and then a username, which must end in "bot" and be globally unique (e.g. "chanconomy_helper_bot"). Once you confirm, BotFather returns an API token that looks like 123456789:ABCdefGHIjklMNOpqrSTUvwxYZ — this token is the single credential your code uses to authenticate as the bot. Treat it like a password: never commit it to a public repository, never paste it into a chat, and rotate it immediately if it leaks (BotFather can issue a new one via /revoke and /token). Two useful follow-up commands: /setdescription controls the text users see before they start the bot, and /setcommands lets you register a command menu (like /start, /help, /stats) that Telegram renders as a shortcut list in the input bar. Registering commands here is optional — your code can also declare them at runtime via the setMyCommands API — but doing it in BotFather is the fastest way to get a clean menu while you are still developing.
Step 2 — Scaffold a Node.js project and install a library
You need Node.js 18 or newer installed locally (Node 20 LTS is a safe choice). Create a project folder, run npm init -y to generate a package.json, then install a Telegram library. The two mainstream options are grammy (modern, lightweight, excellent TypeScript support, great documentation) and node-telegram-bot-api (older, larger ecosystem of examples, callback-based API). For a new project, reach for grammy — its documentation is the best in the ecosystem and it handles webhooks, sessions, and middleware cleanly. Install it with npm install grammy. You will also want a way to load secrets, so add a .env file and the dotenv package: npm install dotenv. Create a .env file containing BOT_TOKEN=your-token-here and add .env to a .gitignore file so the token never leaves your machine through version control. The scaffold is intentionally minimal — one index.js file, one .env file, one dependency — because the fastest way to learn the Bot API is to keep the surface area small until you understand the request loop.
Step 3 — Write your first bot with long polling
Long polling is the simplest way to receive updates: your bot repeatedly asks Telegram "anything new?" and Telegram holds the connection open until an update arrives or a timeout passes. It requires no public URL, no TLS certificate, and no inbound port — perfect for local development. Here is a complete grammy bot that replies to /start and echoes any other message. Create index.js: require("dotenv").config(); const { Bot } = require("grammy"); const bot = new Bot(process.env.BOT_TOKEN); bot.command("start", (ctx) => ctx.reply("Hello! I am alive. Send me any text and I will echo it.")); bot.on("message:text", (ctx) => ctx.reply(`You said: ${ctx.message.text}`)); bot.start(); Run it with node index.js, open your bot in Telegram, send /start, and you should get a reply within a second. That is a working bot. The bot.start() call begins long polling and keeps the process alive; grammy handles retries and reconnection automatically. The two handlers show the core mental model: bot.command matches a specific slash command, and bot.on matches any update of a given type (here, any text message). Every feature you will ever build is a variation on registering a handler for a specific update type and replying with ctx.reply or a richer API call.
Step 4 — Add commands, arguments, and inline buttons
Real bots do more than echo text. Two patterns cover most needs: parsing command arguments and sending inline keyboard buttons. For arguments, grammy passes the raw text after the command in ctx.match — so for /stats @somedude, ctx.match holds "@somedude". For buttons, you send an InlineKeyboard with callback_data that your bot later receives as a callback_query update. Example: bot.command("menu", async (ctx) => { const keyboard = new InlineKeyboard().text("Show stats", "stats").text("Get help", "help"); await ctx.reply("Pick an option:", { reply_markup: keyboard }); }); bot.callbackQuery("stats", async (ctx) => { await ctx.answerCallbackQuery(); await ctx.reply("Your stats: 42 messages this week."); }); bot.callbackQuery("help", async (ctx) => { await ctx.answerCallbackQuery(); await ctx.reply("Send /menu anytime to see options."); }); The answerCallbackQuery call closes the loading spinner on the button — forgetting it leaves the button spinning, which is the most common bug in button code. Inline buttons are how you build menus, pagination, and in-bot navigation without forcing users to type commands, and they are the foundation of any interactive bot UX.
Step 5 — Long polling vs webhooks: which to use when
Long polling and webhooks both deliver the same updates; the difference is who initiates the connection. Long polling means your bot asks Telegram for updates repeatedly — easy, no public URL needed, fine for development and low-traffic bots, but it adds latency (each poll cycle has overhead) and does not scale gracefully to high update volumes. Webhooks mean Telegram pushes updates to your server the instant they arrive — lower latency, lower overhead, and the only sensible choice for production bots with real traffic, but they require a public HTTPS URL with a valid TLS certificate. The practical rule: develop with long polling, deploy with webhooks. A bot serving a few dozen users can run on long polling forever without issue; a bot serving thousands should switch to webhooks so Telegram is not waiting on your poll cycle. There is no cost difference and no API difference — you switch by calling setWebhook before going live and deleteWebhook if you drop back to polling for debugging. Never run both at once: if a webhook is set, long polling returns no updates, which confuses developers who expect their polling code to keep working after deployment.
Step 6 — Switch to webhooks for production
To run webhooks you need a public HTTPS endpoint. In development you can expose your local machine with a tunnel like ngrok (run ngrok http 3000 to get a temporary https URL pointing at your local port 3000). In production you deploy to a real host — a small VPS, a container platform, or a serverless function — and point Telegram at your domain. grammy makes the switch a few lines. Replace bot.start() with a web framework: const express = require("express"); const app = express(); app.use(express.json()); app.use(async (req, res) => { await bot.handleUpdate(req.body); res.sendStatus(200); }); app.listen(3000, () => console.log("listening on 3000")); Then register the webhook once: bot.api.setWebhook("https://yourdomain.com/webhook"); Telegram will now POST every update to that URL, and your express handler passes each one to bot.handleUpdate, which runs the same handlers you wrote for polling. The webhook URL must be HTTPS with a valid certificate — Telegram rejects self-signed or HTTP endpoints. Set a secret token via setWebhook's secret_token parameter and verify it on incoming requests so you can be sure a POST actually came from Telegram and not an attacker who found your URL; grammy and node-telegram-bot-api both support this verification natively.
Step 7 — Deploy: where to host your bot
A Telegram bot is a long-running process, so the host must keep it alive. Three tiers cover most cases. A small VPS (a $5/month Linux box from any provider) is the most flexible: you run your Node process under a process manager like PM2 (npm install -g pm2, then pm2 start index.js --name mybot and pm2 startup so it restarts on reboot), put a reverse proxy like nginx in front for TLS, and you have full control. A container platform (Render, Railway, Fly.io) removes the ops burden: you push code, it builds an image, and it keeps the container running with automatic restarts and managed TLS — ideal if you do not want to babysit a server. Serverless functions (AWS Lambda, Cloudflare Workers, Google Cloud Functions) are the cheapest for low traffic and pair naturally with webhooks, but they have cold-start latency and a request timeout that can bite long-running handlers, so they suit short, stateless bot actions rather than heavy processing. Match the host to your traffic and your willingness to do ops: a hobby bot is fine on a free tier; a bot you monetize deserves a managed host with uptime monitoring so a crash at 3am does not cost you a day of dead service.
Step 8 — Persist data: sessions, users, and a database
A bot that only replies statelessly is limited; most useful bots remember things — user preferences, conversation state, balances, subscription tiers. grammy ships a session middleware for in-memory per-user state, which is perfect for prototyping but resets when the process restarts, so anything that must survive a restart belongs in a database. For a new bot, start with SQLite (via the better-sqlite3 package) for a zero-config, file-based store that handles thousands of users comfortably on a single VPS; move to Postgres only when you outgrow a single machine or need concurrent writes from multiple bot instances. The pattern is straightforward: on each relevant update, read the user row by their Telegram user id, act on it, and write back. Always key your data on the Telegram user id (a stable integer), never on the username (which users can change). Store the minimum you need — over-collecting personal data creates a privacy and compliance burden for no benefit. If your bot collects email, payment, or identity data, read Telegram's data handling expectations and your local privacy law before you store a single row; a contact-form bot and a payment bot have very different obligations.
Step 9 — Handle payments with Telegram Stars and Telegram Payments
Once your bot does something useful, charging for it is the natural next step, and Telegram offers two rails covered in depth in our Stars monetization guide. For digital goods consumed inside Telegram — premium features, in-bot currency, saved templates — use Telegram Stars: call sendInvoice with the XTR currency code, receive a pre_checkout_query you must acknowledge within 10 seconds, then a successful_payment update that tells you the user paid, at which point you grant the entitlement in your database. For physical goods or delivered services, use Telegram Payments with a connected fiat provider (Stripe or a local processor) and the same invoice flow denominated in fiat. The single most common payment bug is granting access on the front-end callback instead of the server-side successful_payment webhook — a user who closes the app before the callback fires then loses what they paid for, so always reconcile against the webhook. The second most common is failing to acknowledge the pre_checkout_query in time, which silently fails the payment. Handle both before you accept a single real payment.
Step 10 — Secure your bot token and your webhook
A leaked bot token lets anyone fully control your bot — send messages as it, read its updates, change its webhook — so token hygiene is not optional. Keep the token in an environment variable loaded from .env or your host's secret store, never in source. Add .env to .gitignore and double-check it is ignored before your first push. If a token leaks, revoke it immediately via BotFather's /revoke command and issue a fresh one. On the webhook side, set a secret_token when you call setWebhook and verify it on every incoming request so only Telegram can deliver updates to your endpoint; reject any request whose header does not match. Rate-limit your own outbound messages: the Bot API enforces roughly 30 messages per second overall and tighter per-chat limits (about 1 message per second to the same chat), and exceeding them returns a 429 error with a retry_after value you must respect — grammy and node-telegram-bot-api handle 429 backoff automatically, but raw fetch code does not. Finally, validate all user input before you act on it: a command argument is untrusted user data, so sanitize it before it touches a shell, a database query, or an external API.
The metrics every bot owner should track from day one
A bot without instrumentation is a black box, and you cannot improve what you cannot measure. Track four numbers from launch. Active users: distinct Telegram user ids that sent at least one update in the last 7 and 30 days — this is your real audience size, far more meaningful than total starts. Command mix: a count of which commands and buttons users actually hit, so you know which features earn their place and which are dead weight. Error rate: the share of updates that threw an unhandled exception, tracked in your logs or a service like Sentry — anything above 1% means a bug is silently breaking the experience for real users. Latency: the median time from an update arriving to your reply sending, because users perceive anything over about 2 seconds as slow and will abandon the bot. Log each update with a timestamp, user id, command, outcome, and duration; a single structured log line per update is enough to derive all four metrics later. Avoid the vanity metric of total /start count — a million starts with no returning users is a dead bot, while ten thousand monthly actives who keep coming back is a healthy product.
Common mistakes that break bots in production
A handful of mistakes account for most production bot failures, and they are all avoidable. Running long polling in production instead of switching to webhooks leaves you with latency and polling overhead that scales poorly. Forgetting to call answerCallbackQuery leaves inline buttons spinning forever. Granting entitlements on the front-end callback instead of the server-side payment webhook loses paid features for users whose callback never fires. Hardcoding the bot token in source and pushing it to a public repo hands control of the bot to anyone who reads the repo. Ignoring 429 rate limits gets your bot temporarily blocked from sending. Not using a process manager means a single unhandled exception crashes the bot until you manually restart it. Storing user data keyed on the username instead of the user id silently breaks when a user renames themselves. Each of these is a one-line or one-decision fix at build time and a painful incident at 3am in production — handle them before launch, not after.
A launch checklist before your bot goes live
Before you point real users at your bot, run this checklist. Your bot token lives in an environment variable, never in source — check. You have switched from long polling to a webhook with a secret_token, or you have consciously decided polling is fine for your traffic — check. Your process runs under a process manager or managed host that restarts on crash — check. You have registered a command menu via setMyCommands so users see /start and /help shortcuts — check. Every callbackQuery handler calls answerCallbackQuery — check. Payment handlers grant entitlement on the server-side webhook, not the front-end callback, and acknowledge pre_checkout_query within 10 seconds — check. You log each update with user id, command, outcome, and duration, and you can derive active users, command mix, error rate, and latency from those logs — check. You have rate-limit awareness and your library handles 429 backoff — check. You have tested the full flow end to end on a real Telegram account, not just your own — check. If every box is ticked, your bot is ready for real users; if any are blank, fix them first, because the cost of fixing them after launch is always higher than the cost of fixing them now.
Where to go next: from a working bot to a monetized one
A bot that runs is the foundation, not the finish line. Once your bot reliably handles commands, buttons, webhooks, and payments, the work shifts from building to growing and earning. Read our guide to the bots that actually earn for a map of which bot business models pay, and our bot monetization guide for the revenue streams that fit a working bot — metered free tiers, Stars-priced unlocks, affiliate integrations, and done-for-you services billed in fiat. The pattern across every monetized bot is the same: ship a useful free experience first, instrument it, then introduce paid features at the value moment where a user has just felt the bot deliver. A bot you understand end to end — token, handlers, webhook, database, payments, logs — is a bot you can iterate on confidently, and that iteration is what turns a working bot into one that earns. Build it right once, and every feature after that is a small, safe addition rather than a rewrite.