Gathering detailed insights and metrics for telegraf
Gathering detailed insights and metrics for telegraf
Gathering detailed insights and metrics for telegraf
Gathering detailed insights and metrics for telegraf
npm install telegraf
Typescript
Module System
Min. Node Version
Node Version
NPM Version
97.2
Supply Chain
99.1
Quality
79.2
Maintenance
100
Vulnerability
100
License
TypeScript (80.51%)
JavaScript (19.49%)
Built with Next.js • Fully responsive • SEO optimized • Open source ready
Total Downloads
11,720,876
Last Day
12,244
Last Week
114,872
Last Month
514,751
Last Year
4,577,122
MIT License
8,855 Stars
1,699 Commits
951 Forks
113 Watchers
10 Branches
137 Contributors
Updated on Sep 04, 2025
Latest Version
4.16.3
Package Id
telegraf@4.16.3
Unpacked Size
673.06 kB
Size
134.05 kB
File Count
168
NPM Version
10.2.4
Node Version
18.19.1
Published on
Feb 29, 2024
Cumulative downloads
Total Downloads
Last Day
3.8%
12,244
Compared to previous day
Last Week
-8.8%
114,872
Compared to previous week
Last Month
13.4%
514,751
Compared to previous month
Last Year
113.8%
4,577,122
Compared to previous year
19
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.
http/https/fastify/Connect.js/express.js
compatible webhooks1const { Telegraf } = require('telegraf') 2const { message } = require('telegraf/filters') 3 4const bot = new Telegraf(process.env.BOT_TOKEN) 5bot.start((ctx) => ctx.reply('Welcome')) 6bot.help((ctx) => ctx.reply('Send me a sticker')) 7bot.on(message('sticker'), (ctx) => ctx.reply('👍')) 8bot.hears('hi', (ctx) => ctx.reply('Hey there')) 9bot.launch() 10 11// Enable graceful stop 12process.once('SIGINT', () => bot.stop('SIGINT')) 13process.once('SIGTERM', () => bot.stop('SIGTERM'))
1const { Telegraf } = require('telegraf') 2 3const bot = new Telegraf(process.env.BOT_TOKEN) 4bot.command('oldschool', (ctx) => ctx.reply('Hello')) 5bot.command('hipster', Telegraf.reply('λ')) 6bot.launch() 7 8// Enable graceful stop 9process.once('SIGINT', () => bot.stop('SIGINT')) 10process.once('SIGTERM', () => bot.stop('SIGTERM'))
For additional bot examples see the new docs repo
.
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
.
1$ npm install telegraf
or
1$ yarn add telegraf
or
1$ pnpm add telegraf
Telegraf
classTelegraf
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
classctx
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.
1import { Telegraf } from 'telegraf' 2import { message } from 'telegraf/filters' 3 4const bot = new Telegraf(process.env.BOT_TOKEN) 5 6bot.command('quit', async (ctx) => { 7 // Explicit usage 8 await ctx.telegram.leaveChat(ctx.message.chat.id) 9 10 // Using context shortcut 11 await ctx.leaveChat() 12}) 13 14bot.on(message('text'), async (ctx) => { 15 // Explicit usage 16 await ctx.telegram.sendMessage(ctx.message.chat.id, `Hello ${ctx.state.role}`) 17 18 // Using context shortcut 19 await ctx.reply(`Hello ${ctx.state.role}`) 20}) 21 22bot.on('callback_query', async (ctx) => { 23 // Explicit usage 24 await ctx.telegram.answerCbQuery(ctx.callbackQuery.id) 25 26 // Using context shortcut 27 await ctx.answerCbQuery() 28}) 29 30bot.on('inline_query', async (ctx) => { 31 const result = [] 32 // Explicit usage 33 await ctx.telegram.answerInlineQuery(ctx.inlineQuery.id, result) 34 35 // Using context shortcut 36 await ctx.answerInlineQuery(result) 37}) 38 39bot.launch() 40 41// Enable graceful stop 42process.once('SIGINT', () => bot.stop('SIGINT')) 43process.once('SIGTERM', () => bot.stop('SIGTERM'))
1import { Telegraf } from "telegraf"; 2import { message } from 'telegraf/filters'; 3 4const bot = new Telegraf(token); 5 6bot.on(message("text"), ctx => ctx.reply("Hello")); 7 8// Start webhook via launch method (preferred) 9bot.launch({ 10 webhook: { 11 // Public domain for webhook; e.g.: example.com 12 domain: webhookDomain, 13 14 // Port to listen on; e.g.: 8080 15 port: port, 16 17 // Optional path to listen for. 18 // `bot.secretPathComponent()` will be used by default 19 path: webhookPath, 20 21 // Optional secret to be sent back in a header for security. 22 // e.g.: `crypto.randomBytes(64).toString("hex")` 23 secretToken: randomAlphaNumericString, 24 }, 25});
Use createWebhook()
if you want to attach Telegraf to an existing http server.
1import { createServer } from "http"; 2 3createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
1import { createServer } from "https";
2
3createServer(tlsOptions, await bot.createWebhook({ domain: "example.com" })).listen(8443);
express
example integrationfastify
example integrationkoa
example integrationbot.handleUpdate
to write new integrationsIf 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.
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.
1bot.on('message', async (ctx) => {
2 // resend existing file by file_id
3 await ctx.replyWithSticker('123123jkbhj6b')
4
5 // send file
6 await ctx.replyWithVideo(Input.fromLocalFile('/path/to/video.mp4'))
7
8 // send stream
9 await ctx.replyWithVideo(
10 Input.fromReadableStream(fs.createReadStream('/path/to/video.mp4'))
11 )
12
13 // send buffer
14 await ctx.replyWithVoice(Input.fromBuffer(Buffer.alloc()))
15
16 // send url via Telegram server
17 await ctx.replyWithPhoto(Input.fromURL('https://picsum.photos/200/300/'))
18
19 // pipe url content
20 await ctx.replyWithPhoto(
21 Input.fromURLStream('https://picsum.photos/200/300/?random', 'kitten.jpg')
22 )
23})
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:
1import { Telegraf } from 'telegraf'; 2import { message } from 'telegraf/filters'; 3 4const bot = new Telegraf(process.env.BOT_TOKEN); 5 6bot.use(async (ctx, next) => { 7 console.time(`Processing update ${ctx.update.update_id}`); 8 await next() // runs next middleware 9 // runs after next middleware finishes 10 console.timeEnd(`Processing update ${ctx.update.update_id}`); 11}) 12 13bot.on(message('text'), (ctx) => ctx.reply('Hello World')); 14bot.launch(); 15 16// Enable graceful stop 17process.once('SIGINT', () => bot.stop('SIGINT')); 18process.once('SIGTERM', () => bot.stop('SIGTERM'));
With this simple ability, you can:
await next()
to avoid disrupting other middleware,Composer
and Router
, await next()
for updates you don't wish to handle,session
and Scenes
, extend the context by mutating ctx
before await next()
,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.
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:
1import { Context, Telegraf } from 'telegraf' 2 3// Define your own context type 4interface MyContext extends Context { 5 myProp?: string 6 myOtherProp?: number 7} 8 9// Create your bot and tell it about your context type 10const bot = new Telegraf<MyContext>('SECRET TOKEN') 11 12// Register middleware and launch your bot as usual 13bot.use((ctx, next) => { 14 // Yay, `myProp` is now available here as `string | undefined`! 15 ctx.myProp = ctx.chat?.first_name?.toUpperCase() 16 return next() 17}) 18// ...
No vulnerabilities found.