Middleware
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
), 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
object that you also find on bot
. As a result, you can call ctx
instead of bot
. 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
—but with some arguments pre-filled for you. As you can see above, you no longer have to specify a chat
or anything; the context object knows which chat it belongs to, so when you call reply
, the context will call send
with the correct chat
, 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
C
Type
MiddlewareFn<C> | MiddlewareObj<C>