Telegraf.js

4.16.3 · active · verified Sun Apr 19

Telegraf.js is a modern, lightweight, and extensible framework for developing Telegram bots using Node.js. It provides full support for the Telegram Bot API, currently at version 7.1 (as of v4.16.0), offering a comprehensive set of tools for handling messages, commands, and various update types. The library is actively maintained, with frequent minor releases incorporating new Bot API features and bug fixes, ensuring compatibility with the latest Telegram platform capabilities. Key differentiators include excellent TypeScript typings, compatibility with serverless environments like AWS Lambda and Firebase Functions, and support for various webhook setups (HTTP/HTTPS, Fastify, Express). It aims for simplicity and extensibility, allowing developers to build complex bot logic efficiently. The current stable version is 4.16.3.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a Telegraf bot with a token from environment variables, sets up basic command handlers for /start and /help, reacts to stickers, and echoes text messages. It demonstrates event listeners and graceful shutdown.

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

const botToken = process.env.BOT_TOKEN ?? ''; // Ensure BOT_TOKEN is set as an environment variable

if (!botToken) {
  console.error('BOT_TOKEN environment variable is not set. Please provide your Telegram bot token.');
  process.exit(1);
}

const bot = new Telegraf(botToken);

bot.start((ctx) => ctx.reply('Welcome! Send me a message or a sticker.'));
bot.help((ctx) => ctx.reply('I can echo your messages and react to stickers!'));
bot.on(message('sticker'), (ctx) => ctx.reply('Nice sticker! 👍'));
bot.hears('hi', (ctx) => ctx.reply('Hey there! How can I help you?'));
bot.on(message('text'), (ctx) => ctx.reply(`You said: ${ctx.message.text}`));

bot.launch();

console.log('Bot launched. Press Ctrl+C to stop.');

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

view raw JSON →