{"id":12127,"library":"telegraf","title":"Telegraf.js","description":"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.","status":"active","version":"4.16.3","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/telegraf/telegraf","tags":["javascript","telegraf","telegram","telegram bot api","bot","botapi","bot framework","typescript"],"install":[{"cmd":"npm install telegraf","lang":"bash","label":"npm"},{"cmd":"yarn add telegraf","lang":"bash","label":"yarn"},{"cmd":"pnpm add telegraf","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While Telegraf can be destructured from require, the common pattern shown in documentation for CommonJS is `const { Telegraf } = require('telegraf')`. For ESM, use named import.","wrong":"const Telegraf = require('telegraf').Telegraf","symbol":"Telegraf","correct":"import { Telegraf } from 'telegraf'"},{"note":"Filters like `message` are imported from the dedicated `telegraf/filters` sub-path, not directly from the main `telegraf` package.","wrong":"import { message } from 'telegraf'","symbol":"message","correct":"import { message } from 'telegraf/filters'"},{"note":"Markup utilities are exported directly from the main `telegraf` package. It's often used for keyboard or inline keyboard generation.","wrong":"import { Markup } from 'telegraf/markup'","symbol":"Markup","correct":"import { Markup } from 'telegraf'"},{"note":"Composer is used for creating nested middleware and handling different update types. It's a named export from the main package.","wrong":"const Composer = require('telegraf').Composer","symbol":"Composer","correct":"import { Composer } from 'telegraf'"}],"quickstart":{"code":"import { Telegraf } from 'telegraf';\nimport { message } from 'telegraf/filters';\n\nconst botToken = process.env.BOT_TOKEN ?? ''; // Ensure BOT_TOKEN is set as an environment variable\n\nif (!botToken) {\n  console.error('BOT_TOKEN environment variable is not set. Please provide your Telegram bot token.');\n  process.exit(1);\n}\n\nconst bot = new Telegraf(botToken);\n\nbot.start((ctx) => ctx.reply('Welcome! Send me a message or a sticker.'));\nbot.help((ctx) => ctx.reply('I can echo your messages and react to stickers!'));\nbot.on(message('sticker'), (ctx) => ctx.reply('Nice sticker! 👍'));\nbot.hears('hi', (ctx) => ctx.reply('Hey there! How can I help you?'));\nbot.on(message('text'), (ctx) => ctx.reply(`You said: ${ctx.message.text}`));\n\nbot.launch();\n\nconsole.log('Bot launched. Press Ctrl+C to stop.');\n\n// Enable graceful stop\nprocess.once('SIGINT', () => bot.stop('SIGINT'));\nprocess.once('SIGTERM', () => bot.stop('SIGTERM'));","lang":"typescript","description":"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."},"warnings":[{"fix":"Refer to the v4.0.0 release notes and migration guide for specific changes. Update middleware registration, context access, and error handling patterns. Full TypeScript rewrite impacts type declarations.","message":"Telegraf v4.0.0 introduced significant breaking changes from the 3.x series, including a full rewrite with improved TypeScript support and a revised API for middleware and context handling. Code written for 3.x is not directly compatible with 4.x.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"Ensure all asynchronous middleware functions correctly `await` their operations. Enable `EXPERIMENTAL_SESSION_CHECKS=1` in development to catch these bugs proactively. Always return promises from async middleware if not explicitly `await`ing them.","message":"Session state persistence can be tricky with asynchronous operations. If `EXPERIMENTAL_SESSION_CHECKS` environment variable is enabled, Telegraf will throw errors if session is accessed/assigned after the middleware chain is thought to have exhausted, often due to missing `await`s in async code. This can lead to session data not being saved.","severity":"gotcha","affected_versions":">=4.15.1"},{"fix":"Upgrade to Telegraf v4.15.3 or newer to get fixes for media upload and thumbnail handling. Always validate file paths and ensure correct media object structures are provided to API methods.","message":"Prior to v4.15.3, there were known issues with media uploads (e.g., photos, documents) and `thumbnail` processing, where `sendPhoto` and similar methods might irrecoverably error or ignore thumbnails if passed invalid paths or due to internal bugs.","severity":"gotcha","affected_versions":"<4.15.3"},{"fix":"Update imports to use `import { filterName } from 'telegraf/filters'` (ESM) or `const { filterName } = require('telegraf/filters')` (CommonJS).","message":"Old patterns for importing `message` or other filters directly from 'telegraf' are incorrect. Filters are now explicitly located in the `telegraf/filters` sub-path.","severity":"deprecated","affected_versions":">=4.11.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you have integrated a session middleware (e.g., `telegraf-session-local` or a custom one) and added it to your bot's middleware chain (`bot.use(sessionMiddleware)`). Also, check for missing `await` keywords in async middleware functions interacting with `ctx.session`.","cause":"Attempting to access `ctx.session` when a session middleware has not been configured or when session data wasn't properly persisted due to an asynchronous issue (e.g., missing `await`).","error":"TypeError: Cannot read properties of undefined (reading 'session')"},{"fix":"For CommonJS, use `const { Telegraf } = require('telegraf')`. For ES Modules, use `import { Telegraf } from 'telegraf'`. Ensure your `package.json` `type` field is correctly set to 'module' for ESM or omitted/set to 'commonjs' for CJS.","cause":"Incorrectly importing Telegraf in a CommonJS environment or when mixing CJS `require` with ESM `import` syntax, leading to `Telegraf` being `undefined` or an object without the constructor.","error":"TypeError: Telegraf is not a constructor"},{"fix":"Double-check your `BOT_TOKEN` environment variable or hardcoded string. Ensure it's the exact token provided by BotFather. Generate a new token if you suspect the current one is compromised or invalid.","cause":"The provided Telegram bot token is invalid, expired, or incorrect. This is an API-level error from Telegram.","error":"Error: 401: Unauthorized"},{"fix":"Ensure the code accessing `ctx.reply` is within a middleware or handler function properly receiving a `Context` object from Telegraf. In TypeScript, verify `ctx` is typed as `Context` or a more specific `ComposerContext`.","cause":"Accessing `ctx.reply` or similar methods outside of a valid `Context` object, or within a middleware where `ctx` might be partially typed/defined without the full `TelegrafContext` methods.","error":"TypeError: ctx.reply is not a function"}],"ecosystem":"npm"}