Creating Filters

Pyrogram already provides lots of built-in Filters to work with, but in case you can’t find a specific one for your needs or want to build a custom filter by yourself (to be used in a different kind of handler, for example) you can use create().


At the moment, the built-in filters are intended to be used with the MessageHandler only.

Custom Filters

An example to demonstrate how custom filters work is to show how to create and use one for the CallbackQueryHandler. Note that callback queries updates are only received by bots as result of a user pressing an inline button attached to the bot’s message; create and authorize your bot, then send a message with an inline keyboard to yourself. This allows you to test your filter by pressing the inline button:

from pyrogram import InlineKeyboardMarkup, InlineKeyboardButton

    "username",  # Change this to your username or id
    "Pyrogram's custom filter test",
        [[InlineKeyboardButton("Press me", "pyrogram")]]

Basic Filters

For this basic filter we will be using only the first two parameters of create().

The code below creates a simple filter for hardcoded, static callback data. This filter will only allow callback queries containing “Pyrogram” as data, that is, the function func you pass returns True in case the callback query data equals to "Pyrogram".

static_data = Filters.create(
    func=lambda flt, query: == "Pyrogram"

The lambda operator in python is used to create small anonymous functions and is perfect for this example, the same could be achieved with a normal function, but we don’t really need it as it makes sense only inside the filter’s scope:

def func(flt, query):
    return == "Pyrogram"

static_data = Filters.create(

The filter usage remains the same:

def pyrogram_data(_, query):
    query.answer("it works!")

Filters with Arguments

A much cooler filter would be one that accepts “Pyrogram” or any other data as argument at usage time. A dynamic filter like this will make use of the third parameter of create().

This is how a dynamic custom filter looks like:

def dynamic_data(data):
    return Filters.create(
        func=lambda flt, query: ==,
        data=data  # "data" kwarg is accessed with ""

And its usage:

def pyrogram_data(_, query):
    query.answer("it works!")