Skip to main content
Module

x/grammy/mod.ts>Composer#filter

The Telegram Bot Framework.
Very Popular
Go to Latest
method Composer.prototype.filter
import { Composer } from "https://deno.land/x/grammy@v1.14.0/mod.ts";

This is an advanced method of grammY.

Registers middleware behind a custom filter function that operates on the context object and decides whether or not to execute the middleware. In other words, the middleware will only be executed if the given predicate returns true for the given context object. Otherwise, it will be skipped and the next middleware will be executed.

This method has two signatures. The first one is straightforward, it is the one described above. Note that the predicate may be asynchronous, i.e. it can return a Promise of a boolean.

Alternatively, you can pass a function that has a type predicate as return type. This will allow you to narrow down the context object. The installed middleware is then able to operate on this constrained context object.

// NORMAL USAGE
// Only process every second update
bot.filter(ctx => ctx.update.update_id % 2 === 0, ctx => { ... })

// TYPE PREDICATE USAGE
function predicate(ctx): ctx is Context & { message: undefined } {
  return ctx.message === undefined
}
// Only process updates where `message` is `undefined`
bot.filter(predicate, ctx => {
  const m = ctx.message // inferred as always undefined!
  const m2 = ctx.update.message // also inferred as always undefined!
})

Type Parameters

D extends C

Parameters

predicate: (ctx: C) => ctx is D

The predicate to check

...middleware: Array<Middleware<D>>

The middleware to register

Parameters

predicate: (ctx: C) => MaybePromise<boolean>
...middleware: Array<Middleware<C>>