Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Commands and Events

Telegram Handlers and Routing

Build a small update router for Telegram bots - command, text, regex and callback handlers, a context object with reply helpers, chat-type filters and fake-API tests - and see the same ideas in grammY.

A bot that handles a single command can live in one if. A bot with thirty commands, buttons, free-text answers and group rules needs routing: a systematic way to send each update to the right handler. Every bot framework (grammY, Telegraf, python-telegram-bot, discord.js) is, at heart, a router plus a context object. In this lesson you build both in about sixty lines, so a framework's API will feel familiar.

Handlers and the context object

A handler is a function that receives a context (ctx): the update plus helpers bound to it. Instead of every handler calling sendMessage({ chat_id: update.message.chat.id, ... }), the context knows the chat and offers ctx.reply('text').

A router maps matchers to handlers:

  • command('start', handler) matches /start.
  • hears(/hello/i, handler) matches text by pattern.
  • callback('like:', handler) matches button data by prefix.
  • on('text', handler) matches any text message.
  • A fallback runs when nothing matched.

The first match wins, in registration order, so you register specific handlers first and general ones last.

Node.js A tiny Telegram router with a context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the order of registration. The on('text') catch-all comes after the specific handlers, so it only sees text that no command or pattern claimed. An update of an unhandled kind (poll) reaches the fallback, which does nothing.

Filtering by chat type and sender

Group chats and private chats call for different behaviour. Instead of if (chat.type !== 'private') return; in every handler, add filters around handlers. A filter is a function that returns a new handler guarded by a condition, a pattern you will reuse for permissions, language and cooldowns.

Node.js Guards: private-only and admin-only handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

compose applies the guards from left to right: first check the chat type, then check the user. Because each guard is just a function, you can unit-test it without any bot at all.

Testing handlers without Telegram

The whole point of routing everything through ctx.reply and a single api.call is that tests need no network. A test creates a router with a fake api (like the sent array above), feeds it updates and asserts on what was sent. Node's built-in runner is enough:

JavaScript
import { test } from 'node:test';
import assert from 'node:assert/strict';

test('/echo repeats the argument', async () => {
  const sent = [];
  const bot = buildBot({ call: async (m, p) => sent.push({ m, ...p }) });
  await bot.handle(msg('/echo hi'));
  assert.equal(sent[0].text, 'hi');
});

This listing is read-only (node --test is not part of the runner). The shape matters more than the code: build the bot from an injected API object, feed it fixed updates, check the recorded calls.

The same thing in grammY

grammY is a popular Telegram framework for Node. Its router has the same concepts you just built. This is read-only code because it needs npm install grammy and a token:

JavaScript
import { Bot } from 'grammy';

const bot = new Bot(process.env.TELEGRAM_TOKEN);

bot.command('start', (ctx) => ctx.reply(`Welcome, ${ctx.from.first_name}!`));
bot.hears(/hello|hi/i, (ctx) => ctx.reply('Hello to you too'));
bot.callbackQuery(/^like:(\d+)$/, async (ctx) => {
  await ctx.answerCallbackQuery({ text: 'Liked!' });
  await ctx.reply(`You liked item ${ctx.match[1]}`);
});
bot.on('message:text', (ctx) => ctx.reply('I only understand commands.'));

bot.start(); // long polling

Every line maps to a method you wrote: command, hears, callbackQuery (our callback), on. A framework adds the parts that are tedious to hand-write: all update types, middleware, sessions, retries and webhooks. Middleware and Error Handling covers the middleware idea next.

Handlers should be short. If a handler grows past a screenful, move the decision logic into a pure function (text in, reply object out) and keep the handler as glue: read the update, call the function, send the result.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do specific handlers go before a catch-all text handler?

    Routers try routes in registration order and stop at the first match. A catch-all registered early would swallow every message.
  2. 2. What is the main benefit of a ctx.reply helper?

    The context is bound to the update, so handlers just say what to reply.
  3. 3. How do you test a handler without Telegram?

    Because all network access goes through one injected object, tests can record calls and never touch the network.
  4. 4. What does a guard (filter) like privateOnly do?

    A guard returns a new handler that checks a predicate first, and otherwise runs an optional denied handler.

Summary

  • A router matches updates to handlers in order; the first match wins, and a fallback catches the rest.
  • A context object bundles the update with helpers such as reply and answerCallback.
  • Guards wrap handlers for chat-type and permission checks, and compose cleanly.
  • Inject the API object so tests can use fakes; keep decision logic in pure functions.
  • Frameworks such as grammY offer the same concepts plus middleware, sessions and webhooks.

Next: Middleware and Error Handling