Telegraf

Modern Telegram Bot Framework for Node.js

README

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


- Full Telegram Bot API 6.3 support
- [AWS λ](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)
  / Firebase
  / Glitch
  / Fly.io
  / Whatever ready
- http/https/fastify/Connect.js/express.js compatible webhooks
- Extensible

Example


  1. ``` js
  2. const { Telegraf } = require('telegraf');
  3. const { message } = require('telegraf/filters');

  4. const bot = new Telegraf(process.env.BOT_TOKEN);
  5. bot.start((ctx) => ctx.reply('Welcome'));
  6. bot.help((ctx) => ctx.reply('Send me a sticker'));
  7. bot.on(message('sticker'), (ctx) => ctx.reply('👍'));
  8. bot.hears('hi', (ctx) => ctx.reply('Hey there'));
  9. bot.launch();

  10. // Enable graceful stop
  11. process.once('SIGINT', () => bot.stop('SIGINT'));
  12. process.once('SIGTERM', () => bot.stop('SIGTERM'));
  13. ```

  1. ``` js
  2. const { Telegraf } = require('telegraf');

  3. const bot = new Telegraf(process.env.BOT_TOKEN);
  4. bot.command('oldschool', (ctx) => ctx.reply('Hello'));
  5. bot.command('hipster', Telegraf.reply('λ'));
  6. bot.launch();

  7. // Enable graceful stop
  8. process.once('SIGINT', () => bot.stop('SIGINT'));
  9. process.once('SIGTERM', () => bot.stop('SIGTERM'));
  10. ```

For additional bot examples see the new [docs repo](https://github.com/feathers-studio/telegraf-docs/).

Resources


- Telegram groups (sorted by number of members):
  Uzbek

Getting started


Telegram token


To use the Telegram Bot API,
you first have to get a bot account

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

Installation


  1. ``` shscript
  2. $ npm install telegraf
  3. ```
or
  1. ``` shscript
  2. $ yarn add telegraf
  3. ```
or
  1. ``` shscript
  2. $ pnpm add telegraf
  3. ```

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—simplifies selecting the right translation to use when responding to a user.
- Redis powered session—store session data using Redis.
- Local powered session (via lowdb)—store session data in a local file.
- Rate-limiting—apply rate limitting to chats or users.
- Bottleneck powered throttling—apply throttling to both incoming updates and outgoing API calls.
- Menus via inline keyboards—simplify creating interfaces based on menus.
- Stateless Questions—create stateless questions to Telegram users working in privacy mode.
- Multivariate and A/B testing—add experiments to see how different versions of a feature are used.
-->

Shorthand methods


  1. ``` js
  2. import { Telegraf } from 'telegraf';
  3. const { message } = require('telegraf/filters');

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

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

  8.   // Using context shortcut
  9.   await ctx.leaveChat();
  10. });

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

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

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

  20.   // Using context shortcut
  21.   await ctx.answerCbQuery();
  22. });

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

  27.   // Using context shortcut
  28.   await ctx.answerInlineQuery(result);
  29. });

  30. bot.launch();

  31. // Enable graceful stop
  32. process.once('SIGINT', () => bot.stop('SIGINT'));
  33. process.once('SIGTERM', () => bot.stop('SIGTERM'));
  34. ```

Production


Webhooks


  1. ```TS
  2. import { Telegraf } from "telegraf";
  3. const { message } = require('telegraf/filters');

  4. const bot = new Telegraf(token);

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

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

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

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

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

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



  1. ```TS
  2. const { createServer } from "http";

  3. createServer(await bot.createWebhook({ domain: "example.com" })).listen(3000);
  4. ```

  1. ```TS
  2. const { createServer } from "https";

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

- [express example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/express.ts)
- [fastify example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/fastify.ts)
- [koa example integration](https://github.com/feathers-studio/telegraf-docs/blob/master/examples/webhook/koa.ts)
- Use [bot.handleUpdate](https://telegraf.js.org/classes/Telegraf-1.html#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](https://www.npmjs.com/package/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.



  1. ``` js
  2. bot.on('message', async (ctx) => {
  3.   // resend existing file by file_id
  4.   await ctx.replyWithSticker('123123jkbhj6b');

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

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

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

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

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

Middleware


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

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

  1. ```TS
  2. import { Telegraf } from 'telegraf';
  3. const { message } = require('telegraf/filters');

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

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

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

  13. // Enable graceful stop
  14. process.once('SIGINT', () => bot.stop('SIGINT'));
  15. process.once('SIGTERM', () => bot.stop('SIGTERM'));
  16. ```

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 mutatingctx before await next(),
- do whatever you come up with!

[Telegraf]: https://telegraf.js.org/classes/Telegraf-1.html
[Composer]: https://telegraf.js.org/classes/Composer.html
[Context]: https://telegraf.js.org/classes/Context.html
[Router]: https://telegraf.js.org/classes/Router.html
[session]: https://telegraf.js.org/modules.html#session
[Scenes]: https://telegraf.js.org/modules/Scenes.html

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](https://github.com/KnorpelSenf/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:

  1. ```ts
  2. import { Context, Telegraf } from 'telegraf';

  3. // Define your own context type
  4. interface MyContext extends Context {
  5.   myProp?: string
  6.   myOtherProp?: number
  7. }

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

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