1
0
mirror of https://github.com/eternnoir/pyTelegramBotAPI.git synced 2023-08-10 21:12:57 +03:00

Update custom filters readme and examples

This commit is contained in:
Badiboy 2021-09-12 19:36:23 +03:00
parent 239a90de14
commit 4ced4d29f5
7 changed files with 59 additions and 66 deletions

View File

@ -289,25 +289,25 @@ def start(message):
There are other examples using middleware handler in the [examples/middleware](examples/middleware) directory.
### Custom filters
#### Custom filters
Also, you can use built-in custom filters. Or, you can create your own filter.
[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters.py)
[Example of custom filter](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/general_custom_filters.py)
Also, we have examples on them. Check this links:
You can check some built-in filters in source [code](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/telebot/custom_filters.py)
Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/id_filter_example.py)
Example of [filtering by id](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/id_filter_example.py)
Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/text_filter_example.py)
Example of [filtering by text](https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/custom_filters/text_filter_example.py)
If you want to add some built-in filter, you are welcome to add it in custom_filters.py file.
Here is example of creating filter-class:
```python
class IsAdmin(util.SimpleCustomFilter):
class IsAdmin(telebot.custom_filters.SimpleCustomFilter):
# Class will check whether the user is admin or creator in group or not
key='is_admin'
@staticmethod

View File

@ -1,18 +1,17 @@
import telebot
from telebot import util
bot = telebot.TeleBot('TOKEN')
# AdvancedCustomFilter is for list, string filter values
class MainFilter(util.AdvancedCustomFilter):
class MainFilter(telebot.custom_filters.AdvancedCustomFilter):
key='text'
@staticmethod
def check(message, text):
return message.text in text
# SimpleCustomFilter is for boolean values, such as is_admin=True
class IsAdmin(util.SimpleCustomFilter):
class IsAdmin(telebot.custom_filters.SimpleCustomFilter):
key='is_admin'
@staticmethod
def check(message: telebot.types.Message):

View File

@ -15,7 +15,8 @@ def not_admin(message):
# Do not forget to register
bot.add_custom_filter(custom_filters.UserFilter())
bot.add_custom_filter(custom_filters.ChatFilter())
bot.polling(non_stop=True)
bot.polling(non_stop=True)

View File

@ -15,7 +15,7 @@ def text_filter(message):
bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name))
# Do not forget to register filters
bot.add_custom_filter(custom_filters.TextFilter())
bot.add_custom_filter(custom_filters.TextStarts())
bot.add_custom_filter(custom_filters.TextMatchFilter())
bot.add_custom_filter(custom_filters.TextStartsFilter())
bot.polling(non_stop=True)

View File

@ -12,7 +12,7 @@ from typing import Any, Callable, List, Optional, Union
# this imports are used to avoid circular import error
import telebot.util
import telebot.types
from custom_filters import SimpleCustomFilter, AdvancedCustomFilter
logger = logging.getLogger('TeleBot')
@ -3140,9 +3140,9 @@ class TeleBot:
filter_check = self.custom_filters.get(message_filter)
if not filter_check:
return False
elif isinstance(filter_check, util.SimpleCustomFilter):
elif isinstance(filter_check, SimpleCustomFilter):
return filter_value == filter_check.check(message)
elif isinstance(filter_check, util.AdvancedCustomFilter):
elif isinstance(filter_check, AdvancedCustomFilter):
return filter_check.check(message, filter_value)
else:
logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.")

View File

@ -1,8 +1,36 @@
from telebot import util
from abc import ABC
class SimpleCustomFilter(ABC):
"""
Simple Custom Filter base class.
Create child class with check() method.
Accepts only message, returns bool value, that is compared with given in handler.
"""
def check(self, message):
"""
Perform a check.
"""
pass
class AdvancedCustomFilter(ABC):
"""
Simple Custom Filter base class.
Create child class with check() method.
Accepts two parameters, returns bool: True - filter passed, False - filter failed.
message: Message class
text: Filter value given in handler
"""
class TextFilter(util.AdvancedCustomFilter):
def check(self, message, text):
"""
Perform a check.
"""
pass
class TextMatchFilter(AdvancedCustomFilter):
"""
Filter to check Text message.
key: text
@ -17,7 +45,7 @@ class TextFilter(util.AdvancedCustomFilter):
if type(text) is list:return message.text in text
else: return text == message.text
class TextContains(util.AdvancedCustomFilter):
class TextContainsFilter(AdvancedCustomFilter):
"""
Filter to check Text message.
key: text
@ -32,30 +60,27 @@ class TextContains(util.AdvancedCustomFilter):
def check(self, message, text):
return text in message.text
class UserFilter(util.AdvancedCustomFilter):
"""
Check whether chat_id corresponds to given chat_id.
Example:
@bot.message_handler(chat_id=[99999])
"""
key = 'chat_id'
def check(self, message, text):
return message.chat.id in text
class TextStarts(util.AdvancedCustomFilter):
class TextStartsFilter(AdvancedCustomFilter):
"""
Filter to check whether message starts with some text.
Example:
# Will work if message.text starts with 'Sir'.
@bot.message_handler(text_startswith='Sir')
"""
key = 'text_startswith'
def check(self, message, text):
return message.text.startswith(text)
class ChatFilter(AdvancedCustomFilter):
"""
Check whether chat_id corresponds to given chat_id.
Example:
@bot.message_handler(chat_id=[99999])
"""
key = 'chat_id'
def check(self, message, text):
return message.chat.id in text

View File

@ -5,7 +5,6 @@ import string
import threading
import traceback
from typing import Any, Callable, List, Dict, Optional, Union
from abc import ABC
# noinspection PyPep8Naming
import queue as Queue
@ -456,34 +455,3 @@ def webhook_google_functions(bot, request):
return 'Bot FAIL', 400
else:
return 'Bot ON'
class SimpleCustomFilter(ABC):
"""
Simple Custom Filter base class.
Create child class with check() method.
Accepts only bool.
"""
def check(self, message):
"""
Perform a check.
"""
pass
class AdvancedCustomFilter(ABC):
"""
Simple Custom Filter base class.
Create child class with check() method.
Can accept to parameters.
message: Message class
text: Filter value given in handler
"""
def check(self, message, text):
"""
Perform a check.
"""
pass