grammY: The Telegram Bot Framework

1.42.0 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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!');

view raw JSON →