telegraf vs node-telegram-bot-api
Building Telegram Bots in Node.js
telegrafnode-telegram-bot-apiSimilar Packages:

Building Telegram Bots in Node.js

node-telegram-bot-api and telegraf are both Node.js libraries designed to interact with the Telegram Bot API. They allow developers to receive updates from Telegram servers and send messages, photos, and other content back to users. While node-telegram-bot-api relies on an event emitter pattern similar to core Node.js modules, telegraf adopts a middleware-based architecture that resembles modern web frameworks like Express. Both libraries handle the low-level HTTP requests required to communicate with Telegram, but they differ significantly in how they structure bot logic and manage state.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
telegraf274,0999,198689 kB763 years agoMIT
node-telegram-bot-api198,1659,2101.28 MB12 months agoMIT

node-telegram-bot-api vs telegraf: Architecture, Maintenance, and DX Compared

Both node-telegram-bot-api and telegraf enable Node.js developers to build bots for the Telegram messaging platform, but they approach bot logic from different angles. One uses a classic event emitter style, while the other uses a middleware pipeline. Let's compare how they handle common engineering tasks.

πŸ—οΈ Architecture: Event Emitters vs Middleware

node-telegram-bot-api uses an event emitter pattern.

  • You listen for specific events like message or callback_query.
  • Logic is often nested inside callback functions or event handlers.
  • Simple to understand for developers familiar with core Node.js events.
// node-telegram-bot-api: Event-based
const TelegramBot = require('node-telegram-bot-api');
const bot = new TelegramBot(token, { polling: true });

bot.on('message', (msg) => {
  if (msg.text === '/start') {
    bot.sendMessage(msg.chat.id, 'Welcome!');
  }
});

telegraf uses a middleware framework.

  • You chain functions that process the update context.
  • Each middleware can modify the context or pass control to the next one.
  • Makes it easier to separate concerns like logging, authentication, and command handling.
// telegraf: Middleware-based
const { Telegraf } = require('telegraf');
const bot = new Telegraf(token);

bot.use((ctx, next) => {
  console.log('Update received');
  return next();
});

bot.start((ctx) => ctx.reply('Welcome!'));

πŸ“‘ Handling Updates: Polling and Webhooks

node-telegram-bot-api supports polling out of the box.

  • You enable it in the constructor options.
  • Webhooks require manual setup with an external server.
  • Good for local development without exposing a public URL.
// node-telegram-bot-api: Built-in polling
const bot = new TelegramBot(token, { polling: true });

// Webhooks require manual express integration
// bot.setWebHook('https://your-domain.com/bot');

telegraf supports both polling and webhooks easily.

  • You can switch between them by changing one method call.
  • Built-in helpers for Express and Koa webhook handling.
  • More flexible for production deployments behind load balancers.
// telegraf: Flexible launch modes
const bot = new Telegraf(token);

// For polling
bot.launch();

// For webhooks
// bot.launch({ webhook: { domain: 'https://your-domain.com' } });

πŸ’Ύ State Management: Manual vs Session Middleware

node-telegram-bot-api does not include session management.

  • You must store state in your own database or memory.
  • Requires manual mapping of chat IDs to user data.
  • More work but gives full control over storage logic.
// node-telegram-bot-api: Manual state
const userStates = {};

bot.on('message', (msg) => {
  const chatId = msg.chat.id;
  if (!userStates[chatId]) userStates[chatId] = { step: 0 };
  // Handle logic based on userStates[chatId].step
});

telegraf includes a session middleware.

  • Automatically attaches state to the context object.
  • Supports custom storage adapters like Redis or MongoDB.
  • Reduces boilerplate for multi-step conversations.
// telegraf: Session middleware
const { session } = require('telegraf/session');

bot.use(session());

bot.on('message', (ctx) => {
  if (!ctx.session.step) ctx.session.step = 0;
  // Access state directly via ctx.session
});

πŸ› οΈ Maintenance and API Coverage

node-telegram-bot-api has slower update cycles.

  • New Telegram API features may take time to be supported.
  • Community has raised concerns about long-term maintenance.
  • Suitable for stable projects that do not need cutting-edge features.
// node-telegram-bot-api: Basic method call
bot.sendMessage(chatId, 'Hello', {
  parse_mode: 'HTML'
});

telegraf is actively maintained.

  • Quickly adopts new Telegram Bot API versions.
  • Large ecosystem of plugins for payments, games, and more.
  • Recommended for projects requiring long-term support.
// telegraf: Context helper method
ctx.reply('Hello', {
  parse_mode: 'HTML'
});

🀝 Similarities: Shared Ground Between Libraries

While the architectures differ, both libraries share core capabilities for interacting with Telegram.

1. πŸ”‘ Authentication and Setup

  • Both require a Bot Token from @BotFather.
  • Both handle HTTPS requests to Telegram servers automatically.
// Both: Token initialization
// node-telegram-bot-api
const bot1 = new TelegramBot('TOKEN');

// telegraf
const bot2 = new Telegraf('TOKEN');

2. πŸ“€ Sending Content

  • Both support text, photos, documents, and stickers.
  • Both allow custom reply keyboards and inline buttons.
// node-telegram-bot-api: Send photo
bot.sendPhoto(chatId, 'path/to/image.jpg');

// telegraf: Send photo
ctx.replyWithPhoto({ source: 'path/to/image.jpg' });

3. πŸ”’ Error Handling

  • Both emit errors that developers must catch to prevent crashes.
  • Both support promise-based method calls for async flows.
// node-telegram-bot-api: Error event
bot.on('polling_error', (error) => console.log(error.code));

// telegraf: Catch middleware
bot.catch((err, ctx) => console.log('Oops', err));

4. 🌐 Community Support

  • Both have extensive documentation and Stack Overflow presence.
  • Both are widely used in production environments globally.
// Both: Common usage pattern
// Listening for specific commands
// Handling user input
// Managing bot state

πŸ“Š Summary: Key Similarities

FeatureShared by Both Libraries
Core ProtocolπŸ”’ Telegram Bot API HTTP
AuthπŸ”‘ Bot Token based
Content TypesπŸ“€ Text, Media, Files
Keyboards⌨️ Reply and Inline
Async Model⚑ Promise-based methods

πŸ†š Summary: Key Differences

Featurenode-telegram-bot-apitelegraf
ArchitectureπŸ“‘ Event Emitter🧩 Middleware Framework
SessionsπŸ—„οΈ Manual Implementation🧠 Built-in Middleware
WebhooksπŸ”Œ Manual SetupπŸš€ Built-in Helpers
Maintenance🐒 Slower UpdatesπŸš€ Active Development
ContextπŸ“¦ Raw Update Object🎯 Enriched Context Object
Recommendation⚠️ Legacy/Simple Scriptsβœ… New Production Projects

πŸ’‘ The Big Picture

node-telegram-bot-api is like a basic utility kit 🧰 β€” it gets the job done for simple tasks with minimal setup. It is best suited for legacy systems or quick scripts where adding a larger framework is unnecessary. However, teams should be aware of the slower maintenance cycle when planning long-term roadmaps.

telegraf is like a modern application framework πŸ—οΈ β€” it provides structure, tools, and patterns for building complex bots. It shines in projects that require sessions, multi-step conversations, or integration with other services. For any new development, it is the stronger architectural choice.

Final Thought: While both libraries can send messages and handle updates, telegraf offers a more sustainable path for growth. Choose based on whether you need a quick script or a scalable bot platform.

How to Choose: telegraf vs node-telegram-bot-api

  • telegraf:

    Choose telegraf for new projects that require a scalable architecture with support for middleware, sessions, and wizard-style conversations. It is the community standard for modern Telegram bot development in Node.js and receives regular updates to support new Telegram API features. The middleware system makes it easier to organize complex logic into reusable components. This package is ideal for production-grade bots that need long-term maintainability and robust error handling.

  • node-telegram-bot-api:

    Choose node-telegram-bot-api if you are maintaining a legacy project that already depends on it or if you need a very simple script with minimal dependencies. It is suitable for straightforward bots that do not require complex state management or middleware chains. However, be aware that active feature development has slowed compared to newer alternatives. It works well for basic notifications or simple command-response bots where architectural flexibility is not a priority.

README for telegraf

logo

telegraf.js

Modern Telegram Bot API framework for Node.js

Bot API Version install size GitHub top language English chat

For 3.x users

Introduction

Bots are special Telegram accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.

Telegraf is a library that makes it simple for you to develop your own Telegram bots using JavaScript or TypeScript.

Features

Example

const { Telegraf } = require('telegraf')
const { message } = require('telegraf/filters')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on(message('sticker'), (ctx) => ctx.reply('πŸ‘'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))
const { Telegraf } = require('telegraf')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('oldschool', (ctx) => ctx.reply('Hello'))
bot.command('hipster', Telegraf.reply('Ξ»'))
bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

For additional bot examples see the new docs repo.

Resources

Getting started

Telegram token

To use the Telegram Bot API, you first have to get a bot account by chatting with BotFather.

BotFather will give you a token, something like 123456789:AbCdefGhIJKlmNoPQRsTUVwxyZ.

Installation

$ npm install telegraf

or

$ yarn add telegraf

or

$ pnpm add telegraf

Telegraf class

Telegraf instance represents your bot. It's responsible for obtaining updates and passing them to your handlers.

Start by listening to commands and launching your bot.

Context class

ctx you can see in every example is a Context instance. Telegraf creates one for each incoming update and passes it to your middleware. It contains the update, botInfo, and telegram for making arbitrary Bot API requests, as well as shorthand methods and getters.

This is probably the class you'll be using the most.

Shorthand methods

import { Telegraf } from 'telegraf'
import { message } from 'telegraf/filters'

const bot = new Telegraf(process.env.BOT_TOKEN)

bot.command('quit', async (ctx) => {
  // Explicit usage
  await ctx.telegram.leaveChat(ctx.message.chat.id)

  // Using context shortcut
  await ctx.leaveChat()
})

bot.on(message('text'), async (ctx) => {
  // Explicit usage
  await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`)

  // Using context shortcut
  await ctx.reply(`Hello ${ctx.state.role}`)
})

bot.on('callback_query', async (ctx) => {
  // Explicit usage
  await ctx.telegram.answerCbQuery(ctx.callbackQuery.id)

  // Using context shortcut
  await ctx.answerCbQuery()
})

bot.on('inline_query', async (ctx) => {
  const result = []
  // Explicit usage
  await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result)

  // Using context shortcut
  await ctx.answerInlineQuery(result)
})

bot.launch()

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'))
process.once('SIGTERM', () => bot.stop('SIGTERM'))

Production

Webhooks

import { Telegraf } from "telegraf";
import { message } from 'telegraf/filters';

const bot = new Telegraf(token);

bot.on(message("text"), ctx => ctx.reply("Hello"));

// Start webhook via launch method (preferred)
bot.launch({
  webhook: {
    // Public domain for webhook; e.g.: example.com
    domain: webhookDomain,

    // Port to listen on; e.g.: 8080
    port: port,

    // Optional path to listen for.
    // `bot.secretPathComponent()` will be used by default
    path: webhookPath,

    // Optional secret to be sent back in a header for security.
    // e.g.: `crypto.randomBytes(64).toString("hex")`
    secretToken: randomAlphaNumericString,
  },
});

Use createWebhook() if you want to attach Telegraf to an existing http server.

import { createServer } from "http";

createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
import { createServer } from "https";

createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);

Error handling

If middleware throws an error or times out, Telegraf calls bot.handleError. If it rethrows, update source closes, and then the error is printed to console and process terminates. If it does not rethrow, the error is swallowed.

Default bot.handleError always rethrows. You can overwrite it using bot.catch if you need to.

⚠️ Swallowing unknown errors might leave the process in invalid state!

ℹ️ In production, systemd or pm2 can restart your bot if it exits for any reason.

Advanced topics

Working with files

Supported file sources:

  • Existing file_id
  • File path
  • Url
  • Buffer
  • ReadStream

Also, you can provide an optional name of a file as filename when you send the file.

bot.on('message', async (ctx) => {
  // resend existing file by file_id
  await ctx.replyWithSticker('123123jkbhj6b')

  // send file
  await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))

  // send stream
  await ctx.replyWithVideo(
    Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
  )

  // send buffer
  await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))

  // send url via Telegram server
  await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))

  // pipe url content
  await ctx.replyWithPhoto(
    Input.fromURLStream('https://picsum.photos/200/300/?random', 'kitten.jpg')
  )
})

Middleware

In addition to ctx: Context, each middleware receives next: () => Promise<void>.

As in Koa and some other middleware-based libraries, await next() will call next middleware and wait for it to finish:

import { Telegraf } from 'telegraf';
import { message } from 'telegraf/filters';

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.use(async (ctx, next) => {
  console.time(`Processing update ${ctx.update.update_id}`);
  await next() // runs next middleware
  // runs after next middleware finishes
  console.timeEnd(`Processing update ${ctx.update.update_id}`);
})

bot.on(message('text'), (ctx) => ctx.reply('Hello World'));
bot.launch();

// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));

With this simple ability, you can:

Usage with TypeScript

Telegraf is written in TypeScript and therefore ships with declaration files for the entire library. Moreover, it includes types for the complete Telegram API via the typegram package. While most types of Telegraf's API surface are self-explanatory, there's some notable things to keep in mind.

Extending Context

The exact shape of ctx can vary based on the installed middleware. Some custom middleware might register properties on the context object that Telegraf is not aware of. Consequently, you can change the type of ctx to fit your needs in order for you to have proper TypeScript types for your data. This is done through Generics:

import { Context, Telegraf } from 'telegraf'

// Define your own context type
interface MyContext extends Context {
  myProp?: string
  myOtherProp?: number
}

// Create your bot and tell it about your context type
const bot = new Telegraf<MyContext>('SECRET TOKEN')

// Register middleware and launch your bot as usual
bot.use((ctx, next) => {
  // Yay, `myProp` is now available here as `string | undefined`!
  ctx.myProp = ctx.chat?.first_name?.toUpperCase()
  return next()
})
// ...