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

Merge pull request #1303 from Badiboy/master

Update custom filters readme and examples
This commit is contained in:
Badiboy 2021-09-12 19:42:36 +03:00 committed by GitHub
commit 74835c40ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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. 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. 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: 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) 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. 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: Here is example of creating filter-class:
```python ```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 # Class will check whether the user is admin or creator in group or not
key='is_admin' key='is_admin'
@staticmethod @staticmethod

View File

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

View File

@ -15,7 +15,8 @@ def not_admin(message):
# Do not forget to register # 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)) bot.send_message(message.chat.id, "Hi, {name}!".format(name=message.from_user.first_name))
# Do not forget to register filters # Do not forget to register filters
bot.add_custom_filter(custom_filters.TextFilter()) bot.add_custom_filter(custom_filters.TextMatchFilter())
bot.add_custom_filter(custom_filters.TextStarts()) bot.add_custom_filter(custom_filters.TextStartsFilter())
bot.polling(non_stop=True) 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 # this imports are used to avoid circular import error
import telebot.util import telebot.util
import telebot.types import telebot.types
from telebot.custom_filters import SimpleCustomFilter, AdvancedCustomFilter
logger = logging.getLogger('TeleBot') logger = logging.getLogger('TeleBot')
@ -3140,9 +3140,9 @@ class TeleBot:
filter_check = self.custom_filters.get(message_filter) filter_check = self.custom_filters.get(message_filter)
if not filter_check: if not filter_check:
return False return False
elif isinstance(filter_check, util.SimpleCustomFilter): elif isinstance(filter_check, SimpleCustomFilter):
return filter_value == filter_check.check(message) 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) return filter_check.check(message, filter_value)
else: else:
logger.error("Custom filter: wrong type. Should be SimpleCustomFilter or AdvancedCustomFilter.") 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. Filter to check Text message.
key: text key: text
@ -17,7 +45,7 @@ class TextFilter(util.AdvancedCustomFilter):
if type(text) is list:return message.text in text if type(text) is list:return message.text in text
else: return text == message.text else: return text == message.text
class TextContains(util.AdvancedCustomFilter): class TextContainsFilter(AdvancedCustomFilter):
""" """
Filter to check Text message. Filter to check Text message.
key: text key: text
@ -32,30 +60,27 @@ class TextContains(util.AdvancedCustomFilter):
def check(self, message, text): def check(self, message, text):
return text in message.text return text in message.text
class UserFilter(util.AdvancedCustomFilter): class TextStartsFilter(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):
""" """
Filter to check whether message starts with some text. Filter to check whether message starts with some text.
Example: Example:
# Will work if message.text starts with 'Sir'. # Will work if message.text starts with 'Sir'.
@bot.message_handler(text_startswith='Sir') @bot.message_handler(text_startswith='Sir')
""" """
key = 'text_startswith' key = 'text_startswith'
def check(self, message, text): def check(self, message, text):
return message.text.startswith(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 threading
import traceback import traceback
from typing import Any, Callable, List, Dict, Optional, Union from typing import Any, Callable, List, Dict, Optional, Union
from abc import ABC
# noinspection PyPep8Naming # noinspection PyPep8Naming
import queue as Queue import queue as Queue
@ -456,34 +455,3 @@ def webhook_google_functions(bot, request):
return 'Bot FAIL', 400 return 'Bot FAIL', 400
else: else:
return 'Bot ON' 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