-
Notifications
You must be signed in to change notification settings - Fork 5
Extensions – Advanced Filters
This page describes advanced use cases for the filters used with MessageHandler from telegram.ext.
When using MessageHandler it is sometimes useful to have more than one filter. This can be done using so called bit-wise operators. In python those operators are &, | and ~ meaning AND, OR and NOT respectively.
from telegram.ext import MessageHandler, Filters
handler = MessageHandler(Filters.video | Filters.photo | Filters.document,
callback)handler = MessageHandler(Filters.forwarded & Filters.photo, callback)from telegram import MessageEntity
handler = MessageHandler(
Filters.text & (Filters.entity(MessageEntity.URL) |
Filters.entity(MessageEntity.TEXT_LINK)),
callback)handler = MessageHandler(Filters.photo & (~ Filters.forwarded), callback)It is also possible to write our own filters. In essence, a filter is simply a function that receives either a Message instance or a Update instance and returns either True or False. This function has to be implemented in a new class that inherits from either MessageFilter or UpdateFilter, which allows it to be combined with other filters. If the combination of all filters evaluates to True, the message will be handled.
The difference between UpdateFilter and MessageFilter is that the filter function of the former will receive the update, allowing e.g. to differentiate between channel post updates and message updates, while the filter function of the latter will receive the update.effective_message.
Say we wanted to allow only those messages that contain the text "python-telegram-bot is awesome", we could write a custom filter as so:
from telegram.ext import MessageFilter
class FilterAwesome(MessageFilter):
def filter(self, message):
return 'python-telegram-bot is awesome' in message.text
# Remember to initialize the class.
filter_awesome = FilterAwesome()The class can of course be named however you want, the only important things are:
- The class has to inherit from
MessageFilterorUpdateFilter - It has to implement a
filtermethod - You have to create an instance of the class
The filter can then be used as:
awesome_handler = MessageHandler(filter_awesome, callback)Wiki of python-telegram-bot © Copyright 2015-2022 – Licensed by Creative Commons
- Types of Handlers
- Advanced Filters
- Storing data
- Making your bot persistent
- Adding Defaults
- Exception Handling
- Job Queue
- Arbitrary
callback_data - Avoiding flood limits
- Frequently requested design patterns
- Code snippets
- Performance Optimizations
- Webhooks
- Telegram Passport
- Bots built with PTB
- Automated Bot Tests