Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-telegram-bot-api

> 编程语言
Open source

Telegram Bot API for NodeJS

9.2K stars0 likes2 views
WebsiteGitHub

About

Telegram Bot API for NodeJS

✨ A Modern Telegram Bot API Library ✨

v2 is a from-scratch redesign, no v1 compatibility. Coming from v1? See the v1 -> v2 migration guide in the changelog.

Install

bash
npm install node-telegram-bot-api

**Runs on Bun, modern Node.js, Deno, Cloudflare Workers and Vercel Functions λ

Usage

…

Calling the API directly

Api mirrors the wire API 1:1 - one method per Bot API method, each taking a single params object.

typescript
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" });
// the same client is also on bot.api and ctx.api

Middleware

koa-style middleware around every update; on/command/hears are filters in the same chain. Wrap downstream work with await next().

typescript
// ⏱️ time every update - and catch anything thrown downstream
bot.use(async (ctx, next) => {
  const start = Date.now();
  try {
    await next();
  } finally {
    console.log(`update took ${Date.now() - start}ms`);
  }
});

//  last-resort error handler
bot.catch((err, ctx) => console.error("handler failed", err));

⌨️ Keyboards & formatting

Structured fields are plain typed objects - pass a literal or use a fluent builder; the pipeline serializes either.

…

Uploads

A bare string is always a file_id or URL. Wrap raw bytes to upload them. Pass a filename with the right extension - the core does no content sniffing, so the name is what Telegram sees (fromPath uses the basename).

Uploads stream: bytes flow from their source straight into the request, so memory stays flat no matter the file size (fromPath re-opens a disk stream per 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 retrying. To keep retries for an arbitrary stream source, pass a factory that returns a fresh stream:

typescript
// 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" }),
});
…

Builders cover the other attach:// methods; each .build() returns the plain shape.

…

Webhooks

The web-standard callback is a pure (Request) => Promise<Response> - one function for every serverless runtime.

Cloudflare Workers / Bun.serve / Deno Deploy / Vercel Edge:

typescript
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 200. For slow handlers, opt into early-ACK:

typescript
export default {
  // ✅ return 200 immediately, then finish the handler in the background
  // waitUntil keeps the platform alive until it settles (fastAck: true = fire-and-forget)
  fetch: (req: Request, _env: unknown, ctx: { waitUntil(promise: Promise<unknown>): void }) =>
    webhookCallback(bot, { secretToken: SECRET, waitUntil: (p) => ctx.waitUntil(p) })(req),
};

Next.js App Router (app/api/bot/route.ts):

typescript
import { Bot, nextAppWebhook } from "node-telegram-bot-api";
const bot = new Bot(process.env.BOT_TOKEN!);
export const POST = nextAppWebhook(bot, { secretToken: process.env.SECRET });

Express (mount on an app you already have):

typescript
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);

Self-hosted Node server (node-telegram-bot-api/node):

typescript
import { Bot } from "node-telegram-bot-api";
import { createWebhookServer, startWebhook } from "node-telegram-bot-api/node";

// Low-level: you own the server and the port.
const server = createWebhookServer(new Bot(TOKEN), { path: "/telegram", secretToken: SECRET });
server.listen(8080);

// Or the managed one-liner (listen + graceful shutdown, the webhook peer of run()):
await startWebhook(new Bot(TOKEN), { port: 8080, path: "/telegram", secretToken: SECRET });

Register the URL once: api.setWebhook({ url, secret_token }). The secret_token is the only thing authenticating callers (payloads aren't signed) - treat it as required in production, and terminate TLS at your proxy.

Sessions

Opt-in session middleware adds a persistent, per-chat bag, reached from the context with ctx.getSession<T>(). The store is required - no implicit default, so the durability choice is always explicit. Nothing lives in process memory between updates (only what the store persists), so the same code works under one-invocation-per-update serverless and under long-polling.

typescript
import { Bot, createSession, MemorySessionStorage } from "node-telegram-bot-api";

type Session = { count: number };

const bot = new Bot(process.env.BOT_TOKEN!);
bot.use(createSession<Session>({ store: new MemorySessionStorage(), initial: () => ({ count: 0 }) }));

bot.command("count", async (ctx) => {
  const s = ctx.getSession<Session>();
  s.data.count++; // mutate in place, or reassign: s.data = { count: 0 }
  await ctx.reply(`Seen ${s.data.count} times`);
});

Tired of repeating <Session>? Keep the middleware and use its own accessor, typed once at construction - createSession<Session>() returns a middleware carrying .get(ctx) and .find(ctx) (the latter returns undefined instead of throwing when the update had no session key):

typescript
const session = createSession<Session>({ store: new MemorySessionStorage(), initial: () => ({ count: 0 }) });
bot.use(session);
bot.command("count", (ctx) => ctx.reply(`Seen ${++session.get(ctx).data.count} times`));

Both return the same handle, which is also where the non-bag members live: .ext() for layers built on sessions, and .delete(), which evicts the whole key on flush - an explicit end-of-conversation / /forget / erasure hook. ctx.getSession() and session.get(ctx) throw when the middleware did not run for this update (not registered, or no derivable key).

For a conversation with several steps, use a discriminated union as the session type. Each step can require different data: picking a destination requires a ship name, and launch requires both. See examples/12-conversation.ts to name a spaceship, pick a planet, and launch, with /start and /cancel.

Reply tracking

Reply tracking is a layer on top of the session (it stores its table in the envelope's ext.reply, so a bot that never uses it persists nothing extra). It records "awaiting a reply to a specific message" as plain data matched on reply_to_message.message_id - never a live promise - so it survives a restart and works on serverless.

You tag the message you sent; when its reply arrives, you read the tag back, so you know which prompt is being answered - the reason it exists is that a chat can have several prompts outstanding at once. taggedReplies<Tag>(ctx) wraps both ends for a plain string tag, tying expect and match to one type. Below, the step tag drives a two-question flow through a single message handler:

…

taggedReplies is sugar over the primitives expectReply(ctx, id, marker?, { ttlSeconds? }) (stores any JSON marker object), matchReply<M>(ctx) (returns it typed as M) and forgetReply(ctx, id) (cancels a pending expectation). With a single prompt in flight you can drop the marker entirely - its presence alone is the signal.

Nothing expires on its own: a prompt answered tomorrow is normal, so a marker stays pending until it matches or you forget it. Pass ttlSeconds for prompts that go stale (a confirmation, a one-time code) - expired entries are pruned the next time the layer touches the session, which is what keeps a chat that ignores every prompt from growing its envelope forever.

TTL bounds a marker's age, not the table's size - a chat that fires many short-lived keyboards can still balloon between prunes. For a hard per-chat cap, pass replyTracking to createSession:

typescript
createSession<Session>({
  store: new MemorySessionStorage(),
  replyTracking: {
    maxEntriesPerChat: 50, // cap the live markers per chat...
    maxBytesPerChat: 8192, // ...and their serialized size
    defaultTtlSeconds: 3600, // a TTL for every expectation that sets none
    slidingTtl: true, // ...refreshed each time the marker is used
  },
});

Over budget, the least-recently-used markers are evicted - recency, not age, so an actively-pressed old keyboard outlives an idle newer one (a match stamps recency too, not just a record). All four fields are optional; with no replyTracking the tables stay unbounded, as before.

The default session key is per chat, so in a group the marker belongs to the group and any member's reply or press matches it. Put the asker's id in the marker and check it when that matters.

Button presses

expectCallback(ctx, id, marker?, { ttlSeconds? }) / matchCallback<M>(ctx, { once? }) are the callback-query peers, keyed on callback_query.message.message_id (taggedReplies(ctx).expectPress / .matchPress for string tags). Replies and presses live in separate tables, so a quoted reply to a message that also carries a keyboard cannot consume the button's marker; register both if a message can be answered either way.

Reach for them only when callback_data is not enough. A button already carries 64 bytes you chose, round-tripped by Telegram for free - that is the idiomatic way to route a press, and it needs no session at all:

typescript
bot.on("callback_query", (ctx) => {
  if (ctx.callbackQuery?.data === "confirm") { /* ... */ }
});

The session-backed version earns its keep for a marker that does not fit in 64 bytes, one the client must not read (callback_data is plain text in the app), or a button that must fire at most once:

typescript
const sent = await ctx.reply("Delete everything?", { reply_markup: { inline_keyboard: [[{ text: "Yes", callback_data: "y" }]] } });
expectCallback(ctx, sent.message_id, { op: "delete", by: ctx.from?.id }, { ttlSeconds: 3600 });

bot.on("callback_query", async (ctx, next) => {
  const hit = matchCallback<{ op: string; by?: number }>(ctx, { once: true });
  if (!hit) return next();
  if (ctx.from?.id !== hit.by) return ctx.answerCallbackQuery({ text: "Not your button." });
  await ctx.answerCallbackQuery({ text: `Running ${hit.op}` });
});

Unlike a reply, matching a press does not consume the marker by default - an inline keyboard usually stays live for several presses (paging, a toggle), and consuming would break every press after the first. Pass { once: true } for a one-shot button.

Three things worth knowing about that "once":

  • It consumes only that message's marker. Send two confirmations and both stay armed - forgetCallback(ctx, previousId) the older one if only the newest may act.
  • It is at most once, not exactly once: the marker is consumed before your handler runs, and the flush persists that even if the handler throws.
  • A press on an inline-mode message carries no message, so there is nothing to key on; route those by callback_data.

examples/17-callback-tracking.ts puts both routes in one bot: callback_data paging next to a one-shot, requester-checked confirmation.

Storage backends

Every backend implements the same SessionStore: a string key/value contract - read(key), write(key, value, { ttlSeconds }), delete(key), plus optional init / close and, for backends with a TTL, touch(key, ttlSeconds) (the middleware calls it when

Issues· 1 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptapibotbot-frameworkchatbot

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 2, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言