Adding MultiRegexp filter

Adding filter to return multiple matches, instead of only first found
This commit is contained in:
Forden 2021-07-02 18:27:15 +03:00 committed by GitHub
parent e70a76ff63
commit d22a68ad0e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -463,6 +463,42 @@ class RegexpCommandsFilter(BoundFilter):
return False
class MultiRegexp(Filter):
"""
Regexp filter for messages and callback query returning multiple matches
"""
def __init__(self, regexp):
if not isinstance(regexp, typing.Pattern):
regexp = re.compile(regexp, flags=re.IGNORECASE | re.MULTILINE)
self.regexp = regexp
@classmethod
def validate(cls, full_config: typing.Dict[str, typing.Any]):
if 'regexp' in full_config:
return {'regexp': full_config.pop('regexp')}
async def check(self, obj: typing.Union[Message, CallbackQuery, InlineQuery, Poll]):
if isinstance(obj, Message):
content = obj.text or obj.caption or ''
if not content and obj.poll:
content = obj.poll.question
elif isinstance(obj, CallbackQuery) and obj.data:
content = obj.data
elif isinstance(obj, InlineQuery):
content = obj.query
elif isinstance(obj, Poll):
content = obj.question
else:
return False
matches = self.regexp.findall(content)
if matches:
return {'regexp': matches}
return False
class ContentTypeFilter(BoundFilter):
"""
Check message content type