Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Patterns and Deployment

Command Handler Architecture and Middleware

Structure a Discord and Telegram bot so commands share one core: a registry, a context object, middleware for cooldowns and permissions, and thin platform adapters.

The first version of a bot is usually one big if chain: if the text is /ping, do this; else if it is /roll, do that. It works for five commands and becomes painful at twenty. Permission checks get copy-pasted, one command forgets the cooldown, and supporting a second platform means rewriting everything.

The fix is an architecture with three layers. A platform adapter turns raw events into a neutral context. A dispatcher finds the command and runs middleware. Commands contain only the business logic. This lesson builds all three with plain JavaScript, and the same core will serve both Telegram and Discord.

flowchart LR
    TG["Telegram update"] --> A1["Telegram adapter"]
    DC["Discord interaction"] --> A2["Discord adapter"]
    A1 --> CTX["Context: user, chat, args, reply()"]
    A2 --> CTX
    CTX --> D["Dispatcher"]
    D --> MW["Middleware: errors, cooldown, permission"]
    MW --> CMD["Command.run(ctx)"]

Only the two adapters know about platform details. Everything to the right is shared.

The context object

A context is a small, platform-neutral view of "what just happened": who, where, what arguments, and how to answer. Commands receive a context and call ctx.reply(...). They never touch a Telegram or Discord payload.

JavaScript
// shape every adapter must produce
// {
//   platform: "telegram" | "discord",
//   userId: string, chatId: string, isAdmin: boolean,
//   name: string, args: string[],
//   reply: async (text) => void,
// }

Commands as data

Each command is an object with metadata and a function. A registry maps names (and aliases) to commands. The same metadata can produce the help text and the list of slash commands to register on Discord.

Node.js A registry and a dispatcher

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.

Three small details are worth copying. Duplicate names fail at startup, not at runtime. Unknown text is ignored. And /roll@MyBot is handled, because in Telegram groups the client appends the bot name when several bots are present. Notice also that random is injected, which makes the command deterministic in tests.

Middleware

Cross-cutting rules (errors, cooldowns, permissions, logging) belong around commands, not inside them. A middleware is a function that receives the context and a next function. It may stop the chain by not calling next.

Node.js Middleware: errors, cooldowns, permissions

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.

Read the order: errors outermost (so they catch everything), then authorization, then cooldown. Putting authorization before cooldown means a non-admin is not "using up" a cooldown on a command they cannot run. The same compose idea is behind Express, Koa and grammY middleware, so what you learn here transfers directly.

Adapters: the only platform-aware code

An adapter converts a payload into a context and defines reply. Here are both, side by side.

Node.js Telegram and Discord adapters feeding one core

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.

Real libraries (discord.js, grammY, python-telegram-bot, aiogram) give you ready-made versions of the adapter layer. Understanding the shape helps you read their docs and, when needed, write a thin layer of your own so your commands do not depend on a library's types. Libraries that need npm cannot run on this site; the code above shows the idea with plain objects.

File layout

A layout that scales:

TEXT
src/
  index.js            start-up, config, wiring
  core/dispatch.js    registry, compose, middleware
  commands/           one file per command, exporting a definition
  adapters/telegram.js
  adapters/discord.js
  services/           database, settings, rate limiter (no platform code)
test/

Load every file in commands/ at start-up with readdir and import(), register each, and fail fast on duplicates. Adding a command is then adding a file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which layer should contain platform-specific payload parsing?

    Adapters translate each platform's payload into the neutral context; everything else stays shared.
  2. 2. Why register duplicate command names as an error at startup?

    Failing fast makes mistakes visible while you are developing.
  3. 3. In the middleware order [catchErrors, requireAdmin, cooldown], why is cooldown last?

    Authorization failures return before the cooldown is recorded.
  4. 4. Why does the dispatcher strip @BotName from /roll@BotName?

    When several bots share a group, Telegram clients send commands as /command@botname.

Summary

  • Separate adapters (platform details), dispatcher and middleware (cross-cutting rules), and commands (business logic).
  • Commands are data objects in a registry; help text and slash-command registration can be generated from them.
  • Compose middleware so errors, authorization and cooldowns apply to every command consistently.
  • Inject clocks and random sources so commands are deterministic and testable.

Next: Testing bots with fakes