node-telegram-bot-api v2: a middleware-driven Telegram bot library that drops v1 compatibility
Telegram Bot API for NodeJS
At a glance
- What is it?
- node-telegram-bot-api 2.x is a ground-up TypeScript rewrite with a koa-style middleware chain, a one-to-one Api client, streaming uploads and web-standard webhooks. Code written against v1 will not carry over unchanged.
- Who is it for?
- node-telegram-bot-api v2 fits new bots, especially ones deployed to Workers, Bun, Deno or Vercel, where one web-standard webhook function replaces per-platform glue. It is a poor fit for an existing v1 codebase you cannot afford to port, so read the migration notes in CHANGELOG.md before bumping the version.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 1 day ago.
- What is it written in?
- Mainly TypeScript, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 22, 2026, and from our analysis. They are not legal advice.
Star history
- yagop/node-telegram-bot-api9,217 ★ · +11
| Repository | 2026-09-22 | 2026-11-22 |
|---|---|---|
| yagop/node-telegram-bot-api | 9.2k | 9.2k |
11 Stars in the last 61 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
Version 2 is a from-scratch redesign, so v1 code does not upgrade in place
The first thing the project says about v2 is that it is a from-scratch redesign with no v1 compatibility. If you come from v1, the pointer is the v1 to v2 migration guide inside CHANGELOG.md. The package name on npm stays node-telegram-bot-api, and the current version in package.json is 2.2.0. The newest release in the list is v2.2.0, dated 2026-11-02, preceded by 2.2.0-rc2 and 2.2.0-rc1, both dated 2026-09-07.
The consequence is plain: running npm install on an existing v1 project and letting a caret range pull this version across is a rewrite job, not a patch bump. Pin your v1 range until you have gone through the migration notes.
npm install node-telegram-bot-apiThe stated runtimes are Bun, modern Node.js, Deno, Cloudflare Workers and Vercel Functions. The description in package.json calls it a runtime-agnostic TypeScript client, and the keywords include edge and cloudflare-workers. The project is MIT licensed and not archived.
Registration order decides which handler sees an update first
Everything in the Bot class is middleware. Commands, regex matches and update types are all registered into one chain, and the project spells out the rule directly: registration order wins. The helpers bot.on, bot.command and bot.hears are filters in that same chain, and downstream work is wrapped with await next().
The basic wiring pairs the core import with a managed runner from the node subpath, which connects Ctrl-C to bot.stop():
import { Bot, InlineKeyboardBuilder } from "node-telegram-bot-api";
import { run } from "node-telegram-bot-api/node"; // managed runner: wires Ctrl-C to bot.stop()
const bot = new Bot(process.env.BOT_TOKEN!);Handlers are then attached in the order you want them tried:
bot.command("start", (ctx) => ctx.reply("Hi! Send me anything."));
bot.hears(/echo (.+)/, (ctx) => ctx.reply(ctx.match![1]!));Because order is the only routing rule, a broad handler such as bot.on("message") placed above a specific command changes what that command does. Put narrow handlers first and the catch-all last.
A timing wrapper and a last-resort catch are the whole error story shown for middleware
A middleware that surrounds await next() sees everything thrown downstream, which is why the timing example puts next() inside a try block with a finally clause:
bot.use(async (ctx, next) => {
const start = Date.now();
try {
await next();
} finally {
console.log(`update took ${Date.now() - start}ms`);
}
});For anything that escapes, there is a last-resort handler that receives the error and the context:
bot.catch((err, ctx) => console.error("handler failed", err));The practical limit is that bot.catch is described as the last resort, so it is a place to log and move on, not a retry mechanism. If a handler fails halfway through a multi-step reply, nothing in these snippets undoes the steps that already ran. Put compensating logic in your own middleware around next() if you need it.
There is also an examples/10-resilience-ratelimit.ts file in the repository. Its name suggests retry and rate limiting patterns, but read it before assuming what it does.
Api mirrors the Bot API method for method and takes one params object
Api is the raw client. It mirrors the wire API one to one: there is one method per Bot API method, and each takes a single params object rather than positional arguments. You can build it standalone or reach the same client through bot.api and ctx.api.
import { Api } from "node-telegram-bot-api";
const api = new Api(process.env.BOT_TOKEN!);
const me = await api.getMe();
await api.sendMessage({ chat_id: 12345, text: "hello" });Two things follow. First, names and field names track Telegram's own documentation, so the official Bot API reference at core.telegram.org/bots/api doubles as your method reference. Second, there is no convenience layer at this level, so options such as reply_markup are fields in the same object as chat_id and text.
The flip side is that the Bot class, with its ctx.reply shortcut, is where the convenience lives. If you only need to fire messages from a script or a cron job, Api alone avoids the update loop altogether. The repository carries an examples/02-api-client.ts file for this style of use.
Keyboards are plain typed objects, and the builders only save you typing
Structured fields such as reply_markup are plain typed objects. You can pass a literal or use a fluent builder, and the request pipeline serializes either. The exported builders include InlineKeyboardBuilder, ReplyKeyboardBuilder and EntityBuilder. In the inline builder, text takes a label and callback data, url takes a label and a link, row starts a new line of buttons, and build returns the plain shape.
await bot.api.sendMessage({
chat_id,
text: "Choose:",
reply_markup: new InlineKeyboardBuilder()
.text("A", "a")
.url("Docs", "https://core.telegram.org/bots/api")
.row()
.text("B", "b")
.build(),
});The ReplyKeyboardBuilder follows the same chained style with .text("Yes") and .text("No") for a reply keyboard.
Since the builders return the same plain shape you could write by hand, there is no lock-in: a hand-written literal and a built value are interchangeable at call time. The cost of choosing literals is that you carry the nesting yourself, including where rows break. The repository has examples/06-keyboards.ts and examples/07-formatting.ts for fuller versions.
Uploads stream, and a ReadableStream gets exactly one attempt
A bare string in a file field is always treated as a file_id or a URL. To upload bytes you wrap them. Pass a filename with the right extension, because the core does no content sniffing and that name is what Telegram sees. The fromPath helper uses the basename of the path.
Uploads stream, so bytes go from their source straight into the request and memory stays flat regardless of file size. fromPath reopens a disk stream for every attempt. A Blob or Uint8Array upload is re-streamed if the transport retries. A ReadableStream is one-shot: it is sent once, and a failure surfaces immediately instead of being retried.
If you need retries for an arbitrary stream source, give InputFile a factory that returns a fresh stream each time:
// replayable streaming upload: the factory opens a new stream per attempt
await bot.api.sendVideo({
chat_id,
video: new InputFile(() => openVideoStream(), { filename: "video.mp4", contentType: "video/mp4" }),
});Disk uploads are Node only, while raw bytes work anywhere:
// upload from disk (Node only)
await bot.api.sendPhoto({ chat_id, photo: await fromPath("./cat.jpg") });
// upload raw bytes (web-standard, runs anywhere)
await bot.api.sendDocument({ chat_id, document: new InputFile(bytes, { filename: "report.pdf" }) });On Workers or Deno there is no disk to read, so fromPath from the node subpath is not available to you there. A raw InputFile nested inside a structure such as a media group is hoisted automatically to an attach:// part, and further builders (StickerSetBuilder, StaticProfilePhotoBuilder, PhotoStoryBuilder) cover the other attach:// methods.
One Request to Response function serves every webhook runtime, but it waits for your handler by default
The web-standard webhook callback is a pure function from Request to a promise of Response, shared by every serverless runtime. The same shape works for Cloudflare Workers, Bun.serve, Deno Deploy and Vercel Edge:
import { Bot, webhookCallback } from "node-telegram-bot-api";
const bot = new Bot(TOKEN);
bot.on("message", (ctx) => ctx.reply("hi from the edge"));
export default {
fetch: webhookCallback(bot, { secretToken: SECRET }),
};By default the callback awaits your handler before sending the 200 response. For slow handlers there is an opt-in early acknowledgement: pass waitUntil so the platform stays alive until the handler settles, or set fastAck: true for fire-and-forget. With early acknowledgement the 200 goes out first and the handler finishes in the background, so a failure after that point can no longer be reported through the HTTP response.
Framework adapters exist as well. Next.js App Router uses nextAppWebhook in app/api/bot/route.ts, Express uses registerExpressWebhook, and a self-hosted Node server uses createWebhookServer or the managed startWebhook from the node subpath:
import express from "express";
import { Bot, registerExpressWebhook } from "node-telegram-bot-api";
const app = express();
const bot = new Bot(TOKEN);
registerExpressWebhook(bot, app, { path: "/telegram", secretToken: SECRET });
app.listen(3000);Every example passes a secretToken. createWebhookServer leaves the server and the port to you, while startWebhook adds listening and graceful shutdown.
Four subpath exports and dual ESM and CJS builds shape what you can import where
package.json sets type to module and exposes four entry points. The root export is the core, node-telegram-bot-api/node holds Node-specific helpers such as run, fromPath, createWebhookServer and startWebhook, node-telegram-bot-api/types is a types entry, and node-telegram-bot-api/bun is a Bun entry. Each has an import condition and a require condition with matching type declarations, so both ESM and CommonJS consumers are covered. The main field points to dist/core/index.cjs and the module field to dist/core/index.js.
Only dist, README.md and LICENSE.md are published. The sideEffects field lists the node debug files, dist/node/debug.js and dist/node/debug.cjs, so bundlers may treat everything else as free of side effects.
For contributors, the build script runs zshy with tsconfig.build.json and a postbuild step fixes CJS source maps. The typecheck script is tsc --noEmit and the test script is bun test test/unit. The examples folder has eighteen numbered files, from 01-polling-bot.ts through 18-reply-tracking-lru.ts, including webhook variants for Workers, Express, Next.js and a Node server, plus 11-longpoll-stream.ts, 12-conversation.ts and 16-sessions.ts. Number 14 is absent from the list.
Editorial conclusion
node-telegram-bot-api v2 fits new bots, especially ones deployed to Workers, Bun, Deno or Vercel, where one web-standard webhook function replaces per-platform glue. It is a poor fit for an existing v1 codebase you cannot afford to port, so read the migration notes in CHANGELOG.md before bumping the version.
Frequently asked questions
Is node-telegram-bot-api v2 compatible with v1?
No. The project describes v2 as a from-scratch redesign with no v1 compatibility, and points to the v1 to v2 migration guide in CHANGELOG.md.
Which runtimes does node-telegram-bot-api support?
It lists Bun, modern Node.js, Deno, Cloudflare Workers and Vercel Functions. The package.json description calls it a runtime-agnostic TypeScript client.
How do I upload a file with node-telegram-bot-api?
Wrap raw bytes in InputFile with a filename, or use fromPath from node-telegram-bot-api/node on Node. A bare string is always treated as a file_id or URL.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/yagop-node-telegram-bot-api)Star history chart for your README
[](https://hysenlabs.com/projects/yagop-node-telegram-bot-api)Was this useful?