mirror of
https://github.com/aiogram/aiogram.git
synced 2026-04-08 16:37:47 +00:00
Merge pull request #5 from Kylmakalle/patch-1
Regexp Commands Filter with usage example
This commit is contained in:
commit
7851dd65bf
2 changed files with 42 additions and 0 deletions
|
|
@ -132,6 +132,32 @@ class RegexpFilter(Filter):
|
|||
return bool(self.regexp.search(message.text))
|
||||
|
||||
|
||||
class RegexpCommandsFilter(AsyncFilter):
|
||||
"""
|
||||
Check commands by regexp in message
|
||||
"""
|
||||
|
||||
def __init__(self, regexp_commands):
|
||||
self.regexp_commands = [re.compile(command, flags=re.IGNORECASE | re.MULTILINE) for command in regexp_commands]
|
||||
|
||||
async def check(self, message):
|
||||
if not message.is_command():
|
||||
return False
|
||||
|
||||
command = message.text.split()[0][1:]
|
||||
command, _, mention = command.partition('@')
|
||||
|
||||
if mention and mention != (await message.bot.me).username:
|
||||
return False
|
||||
|
||||
for command in self.regexp_commands:
|
||||
search = command.search(message.text)
|
||||
if search:
|
||||
message.conf['regexp_command'] = search
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class ContentTypeFilter(Filter):
|
||||
"""
|
||||
Check message content type
|
||||
|
|
|
|||
16
examples/regexp_commands_filter_example.py
Normal file
16
examples/regexp_commands_filter_example.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from aiogram import Bot, types
|
||||
from aiogram.dispatcher import Dispatcher, filters
|
||||
from aiogram.utils import executor
|
||||
|
||||
bot = Bot(token='TOKEN')
|
||||
dp = Dispatcher(bot)
|
||||
|
||||
|
||||
@dp.message_handler(filters.RegexpCommandsFilter(regexp_commands=['item_([0-9]*)']))
|
||||
async def send_welcome(message: types.Message):
|
||||
regexp_command = message.conf['regexp_command']
|
||||
await message.reply("You have requested an item with number: {}".format(regexp_command.group(1)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
executor.start_polling(dp)
|
||||
Loading…
Add table
Add a link
Reference in a new issue