Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/grammy/mod.ts>Middleware

The Telegram Bot Framework.
Very Popular
Latest
type alias Middleware
import { type Middleware } from "https://deno.land/x/grammy@v1.32.0/mod.ts";

Middleware for grammY, either as a function or as a container for a function.

Simply put, middleware is just a fancy term for a listener. You can register middleware on a bot to listen for updates. Example:

bot.on('message', ctx => ctx.reply('I got your message!'))
//                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                ^
//                |
//               This is middleware!

Middleware receives one object that we call the context object. This is another fancy term for a simple object that holds information about the update you're processing. For instance, the context object gives you access to the message that was sent to your bot (ctx.message), including the text (or photo or whatever message the user has sent). The context object is commonly named ctx.

It also provides you with the ctx.api object that you also find on bot.api. As a result, you can call ctx.api.sendMessage instead of bot.api.sendMessage. This prevents you from having to pass around your bot instance all over your code.

Most importantly, the context object gives you a handful of really useful shortcuts, such as a reply method (see above). This method is nothing else than a wrapper around ctx.api.sendMessage—but with some arguments pre-filled for you. As you can see above, you no longer have to specify a chat_id or anything; the context object knows which chat it belongs to, so when you call reply, the context will call sendMessage with the correct chat_id, namely the one for the same chat that the incoming message originates from. This makes it very convenient to reply to a message.

Middleware is an extremely powerful concept and this short explanation only scratched the surface of what is possible with grammY. If you want to know more advanced things about middleware, check out the documentation on the website.

Type Parameters

optional
C extends Context = Context
definition: MiddlewareFn<C> | MiddlewareObj<C>