NPM Star
Collections
  1. Home
  2. Compare
  3. discord.js vs telegraf
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

Discord.js vs Telegraf: Chat Bot Framework Comparison

Both discord.js and telegraf are popular JavaScript libraries for creating chat bots, but for different platforms. Discord.js is used to build bots for Discord, the gaming-focused chat platform, while Telegraf helps create bots for Telegram messenger. These packages make it easier for developers to handle messages, commands, and interactions with users without dealing with complex platform APIs directly.

Chat Bot Developmentbot-frameworkchat-automationmessagingreal-timesocial-media

Unable to load comparison data. Please try again later.

Similar Packages

eris

90%

A lightweight Discord bot library that's faster and uses less memory than discord.js. It's designed to be simple but powerful, making it great for both small and large Discord bots.

Perfect for developers who want better performance than discord.js and don't mind a slightly simpler API. It uses less RAM and is faster, which is great for larger bots.

Discord Bot Framework

node-telegram-bot-api

90%

A simple yet powerful Telegram Bot API wrapper for Node.js. It provides straightforward methods to interact with Telegram's Bot API.

More straightforward than Telegraf with an easier learning curve. Good for beginners who want to create simple Telegram bots without complex features.

Telegram Bot Framework

oceanic.js

85%

A modern Discord API library that focuses on stability and performance. It's built with TypeScript and provides excellent type safety.

Great alternative to discord.js with built-in TypeScript support and similar features. It's newer but growing in popularity due to its modern approach and good documentation.

Discord Bot Framework

grammY

85%

A modern Telegram bot framework with full TypeScript support. It's designed to be simple to use while offering powerful features.

Newer alternative to Telegraf that's gaining popularity. It has excellent TypeScript support and more modern code patterns, making it easier to write clean bot code.

Telegram Bot Framework

slimbot

70%

A lightweight Telegram Bot API library focused on simplicity. Perfect for creating basic Telegram bots with minimal setup.

Good choice for simple bots where Telegraf might be overkill. It's easier to learn and has a smaller package size.

Telegram Bot Framework

No README available

<header> <div align="center"> <img src="docs/assets/logo.svg" alt="logo" height="90" align="center"> <h1 align="center">telegraf.js</h1> <p>Modern Telegram Bot API framework for Node.js</p> <a href="https://core.telegram.org/bots/api"> <img src="https://img.shields.io/badge/Bot%20API-v7.1-f36caf.svg?style=flat-square" alt="Bot API Version" /> </a> <a href="https://packagephobia.com/result?p=telegraf,node-telegram-bot-api"> <img src="https://flat.badgen.net/packagephobia/install/telegraf" alt="install size" /> </a> <a href="https://github.com/telegraf/telegraf"> <img src="https://img.shields.io/github/languages/top/telegraf/telegraf?style=flat-square&logo=github" alt="GitHub top language" /> </a> <a href="https://telegram.me/TelegrafJSChat"> <img src="https://img.shields.io/badge/English%20chat-grey?style=flat-square&logo=telegram" alt="English chat" /> </a> </div> </header>

For 3.x users

  • 3.x docs
  • 4.0 release notes

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

  • Full Telegram Bot API 7.1 support
  • Excellent TypeScript typings
  • Lightweight
  • AWS λ / Firebase / Glitch / Fly.io / Whatever ready
  • http/https/fastify/Connect.js/express.js compatible webhooks
  • Extensible

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
  • API reference
  • Telegram groups (sorted by number of members):
    • English
    • Russian
    • Uzbek
    • Ethiopian
  • GitHub Discussions
  • Dependent repositories

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.

<!-- TODO: Verify and update list Here is a list of #### Known middleware - [Internationalization](https://github.com/telegraf/telegraf-i18n)—simplifies selecting the right translation to use when responding to a user. - [Redis powered session](https://github.com/telegraf/telegraf-session-redis)—store session data using Redis. - [Local powered session (via lowdb)](https://github.com/RealSpeaker/telegraf-session-local)—store session data in a local file. - [Rate-limiting](https://github.com/telegraf/telegraf-ratelimit)—apply rate limitting to chats or users. - [Bottleneck powered throttling](https://github.com/KnightNiwrem/telegraf-throttler)—apply throttling to both incoming updates and outgoing API calls. - [Menus via inline keyboards](https://github.com/EdJoPaTo/telegraf-inline-menu)—simplify creating interfaces based on menus. - [Stateless Questions](https://github.com/EdJoPaTo/telegraf-stateless-question)—create stateless questions to Telegram users working in privacy mode. - [Natural language processing via wit.ai](https://github.com/telegraf/telegraf-wit) - [Natural language processing via recast.ai](https://github.com/telegraf/telegraf-recast) - [Multivariate and A/B testing](https://github.com/telegraf/telegraf-experiments)—add experiments to see how different versions of a feature are used. - [Powerfull bot stats via Mixpanel](https://github.com/telegraf/telegraf-mixpanel) - [statsd integration](https://github.com/telegraf/telegraf-statsd) - [and more...](https://www.npmjs.com/search?q=telegraf-) -->

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.

<!-- global bot, tlsOptions -->
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);
  • AWS Lambda example integration
  • Google Cloud Functions example integration
  • express example integration
  • fastify example integration
  • koa example integration
  • NestJS framework integration module
  • Cloudflare Workers integration module
  • Use bot.handleUpdate to write new integrations

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.

<!-- global bot, fs -->
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:

  • extract information from updates and then await next() to avoid disrupting other middleware,
  • like Composer and Router, await next() for updates you don't wish to handle,
  • like session and Scenes, extend the context by mutating ctx before await next(),
  • intercept API calls,
  • reuse other people's code,
  • do whatever you come up with!

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() }) // ...

Dependencies Comparison

discord.js

Dependencies

tslib^2.6.3
undici6.21.3
@discordjs/ws^1.2.3
magic-bytes.js^1.10.0
@discordjs/rest^2.6.0
@discordjs/util^1.1.1
fast-deep-equal3.1.3
lodash.snakecase4.1.1
discord-api-types^0.38.16
@discordjs/builders^1.11.2
@sapphire/snowflake3.5.3
@discordjs/collection1.5.3
@discordjs/formatters^0.6.1

Dev Dependencies

tsd^0.31.1
jest29.7.0
turbo^2.0.14
eslint^8.57.0
tslint6.1.3
dtslint4.2.1
prettier^3.3.3
cross-env^7.0.3
typescript~5.5.4
@types/node^16.18.105
@discordjs/docgen^0.12.1
@discordjs/scripts^0.1.0
@favware/cliff-jumper^4.1.0
eslint-formatter-pretty^5.0.0
@discordjs/api-extractor^7.38.1
@typescript-eslint/parser^8.2.0
@typescript-eslint/eslint-plugin^8.2.0

Peer Dependencies

telegraf

Dependencies

@telegraf/types^7.1.0
abort-controller^3.0.0
debug^4.3.4
mri^1.2.0
node-fetch^2.7.0
p-timeout^4.1.0
safe-compare^1.1.4
sandwich-stream^2.0.2

Dev Dependencies

@types/debug^4.1.8
@types/node^20.4.2
@types/node-fetch^2.6.2
@types/safe-compare^1.1.0
@typescript-eslint/eslint-plugin^6.1.0
@typescript-eslint/parser^6.1.0
ava^5.3.1
eslint^8.45.0
eslint-config-prettier^9.0.0
eslint-plugin-ava^14.0.0
eslint-plugin-import^2.27.5
eslint-plugin-node^11.1.0
eslint-plugin-prettier^5.0.0
eslint-plugin-promise^6.1.1
fast-check^3.12.0
prettier^3.0.3
tsx^4.7.1
typedoc^0.25.0
typescript^5.2.2

Peer Dependencies

Who's Using These Packages

discord.js

GPT-Shell
GPT-Shell

GPT-Shell is an OpenAI based chat-bot that is similar to OpenAI's ChatGPT. Also allows creating Dalle2 images.

rtbyte
rtbyte

An open-source modular multipurpose Discord bot built on the incredible Sapphire framework for discord.js

StroyCord
StroyCord

A discord bot used to play music on VC.

telegraf

mini-woo
mini-woo

Telegram mini app integration with WooCommerce

-strology
-strology
Telegrambottest
Telegrambottest
obnlbnk
obnlbnk