Registry / web-framework / grammy

grammy

JSON →
library1.0.0jsnpmunverified

grammY is a powerful, user-friendly, and highly efficient framework designed for creating Telegram bots using TypeScript or JavaScript. As of version 1.42.0, it offers robust support for the latest Telegram Bot API features, frequently releasing updates to keep pace with Telegram's evolving platform (e.g., Bot API 9.6 in recent releases). It distinguishes itself with comprehensive documentation, seamless integration with web frameworks (like Express, Koa, Bun, Cloudflare Workers) and databases, and a thriving ecosystem of plugins. The library emphasizes scalability and performance, making it suitable for both novice bot developers and large-scale applications. It runs on Node.js (requiring ^12.20.0 || >=14.13.1) and Deno.

npm install grammy
INSTALL
IMPORT
SIG · GRAMMY
G
grammy
web-frameworkjavascriptv1.0.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Bot
import { Bot } from 'grammy';
const { Bot } = require('grammy');
While CommonJS `require` works, ESM `import` is the recommended and modern approach for grammY applications, especially with TypeScript.
Context
import { Context } from 'grammy';
The `Context` object is fundamental, carrying all information about an incoming update. It's often extended with custom properties for specific bot logic.
Composer
import { Composer } from 'grammy';
import Composer from 'grammy';
Used for modularizing bot logic by combining multiple middleware stacks. It's a named export, not a default.
webhookCallback
import { webhookCallback } from 'grammy/webhooks';
import { webhookCallback } from 'grammy';
For deploying with webhooks, `webhookCallback` is imported from the dedicated `grammy/webhooks` submodule, not directly from `grammy`.

This quickstart initializes a grammY bot, registers handlers for text messages and the `/start` command, and starts it using long polling. It demonstrates basic message echoing and includes essential error handling for the bot token, ensuring the bot runs securely by advocating environment variables for sensitive data.

import { Bot } from 'grammy'; // Ensure your bot token is stored securely, e.g., in environment variables const BOT_TOKEN = process.env.BOT_TOKEN ?? ''; if (!BOT_TOKEN) { console.error('Error: BOT_TOKEN environment variable is not set.'); console.error('Please get your bot token from @BotFather on Telegram.'); process.exit(1); } // Create a bot object with the token const bot = new Bot(BOT_TOKEN); // Register listeners to handle text messages bot.on('message:text', async (ctx) => { console.log(`Received text message from ${ctx.from?.first_name}: ${ctx.message.text}`); await ctx.reply(`Echo: ${ctx.message.text}`); }); // Register listener for /start command bot.command('start', async (ctx) => { await ctx.reply('Hello! I am your grammY bot.'); }); // Catch all other messages bot.on('message', async (ctx) => { await ctx.reply('I only understand text messages and the /start command for now!'); }); // Start the bot using long polling bot.start(); console.log('Bot started via long polling. Send it a message!');
Debug
Known issues
gotchaHardcoding your bot token directly into source code is a significant security risk. Anyone with access to your code repository could use your bot's token.
fix
Always load your bot token from environment variables (`process.env.BOT_TOKEN`) or a secure configuration management system. Never commit tokens to version control.
affects: >=1.0.0
breakinggrammY frequently updates to support the latest Telegram Bot API versions. While this keeps the library current, it means that older grammY versions might not correctly handle new Bot API features or changes, potentially leading to unexpected behavior or `400 Bad Request` errors if your bot uses unsupported API methods.
fix
Regularly update grammY to its latest version to ensure compatibility with the Telegram Bot API. Monitor the grammY release notes for any migration guides or breaking changes, especially when new Bot API versions are released.
affects: >=1.0.0
gotchaWhile grammY supports both CommonJS (`require`) and ES Modules (`import`), the documentation and examples increasingly favor ESM. Mixing module systems within a single project can lead to `TypeError: require is not a function` or other module resolution issues.
fix
Standardize on ES Modules (`import`/`export`) for new projects and consider migrating existing CommonJS projects. Ensure your `package.json` specifies `"type": "module"` for ESM, or use a TypeScript compiler that targets ESM.
affects: >=1.0.0
gotchaWhen deploying with webhooks, ensure your server is correctly configured to listen on the specified port and is publicly accessible. Common errors include port conflicts, firewalls blocking incoming connections, or incorrect URL configurations for Telegram to send updates.
fix
Verify that your server's firewall allows traffic on the webhook port. Ensure the URL provided to Telegram via `bot.setWebhook()` is correct and resolves to your server. Use a service like `ngrok` for local development to test webhook functionality.
affects: >=1.0.0
Errors
Common errors & fixes
Error: Bot token is not provided!
The `Bot` constructor was called with an empty or undefined string for the bot token.
fix
Ensure the `BOT_TOKEN` environment variable is set before running your bot, or pass a valid token string to the `Bot` constructor. Example: `process.env.BOT_TOKEN`.
TypeError: Cannot read properties of undefined (reading 'on')
This usually indicates that the `bot` object was not correctly initialized or is `undefined` before attempting to call methods like `on` or `command`.
fix
Verify that `new Bot(BOT_TOKEN)` successfully created a bot instance and that `BOT_TOKEN` is a valid string. Check for typos or incorrect variable assignments.
Error: EACCES: permission denied, listen '0.0.0.0:80'
Commonly occurs when trying to run a webhook server on a privileged port (like 80 or 443) without sufficient user permissions (e.g., running as a non-root user).
fix
Use a non-privileged port (e.g., 3000, 8080) for your webhook server if running as a non-root user. If you must use a privileged port, configure your system to allow the bot's process to bind to it, or use a reverse proxy (like Nginx) to forward requests.
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
Asynchronous middleware functions or API calls within your bot's handlers are not properly `await`ed or do not have `.catch()` blocks, leading to unhandled errors.
fix
Always use `await` for asynchronous operations (e.g., `ctx.reply()`, API calls) inside your middleware. Implement proper error handling using `try...catch` blocks or `bot.catch()` middleware to gracefully manage errors.
Upgrade
Version history
1.0.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
21 hits · last 30 days
node
20
OpenAI (training)
1
Resources