Add msg_in filter (new) (#1570)

Closes #1144
This commit is contained in:
Bibo-Joshi 2019-10-27 00:12:54 +02:00 committed by Noam Meltzer
parent bbcff96804
commit 34bdbc632a
3 changed files with 44 additions and 0 deletions

View file

@ -26,6 +26,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `d-qoi <https://github.com/d-qoi>`_
- `daimajia <https://github.com/daimajia>`_
- `Daniel Reed <https://github.com/nmlorg>`_
- `Dmitry Grigoryev <https://github.com/icecom-dg>`_
- `Ehsan Online <https://github.com/ehsanonline>`_
- `Eli Gao <https://github.com/eligao>`_
- `Emilio Molinari <https://github.com/xates>`_

View file

@ -909,6 +909,39 @@ officedocument.wordprocessingml.document")``-
return message.from_user.language_code and any(
[message.from_user.language_code.startswith(x) for x in self.lang])
class msg_in(BaseFilter):
"""Filters messages to only allow those whose text/caption appears in a given list.
Examples:
A simple usecase is to allow only messages that were send by a custom
:class:`telegram.ReplyKeyboardMarkup`::
buttons = ['Start', 'Settings', 'Back']
markup = ReplyKeyboardMarkup.from_column(buttons)
...
MessageHandler(Filters.msg_in(buttons), callback_method)
Args:
list_ (List[:obj:`str`]): Which messages to allow through. Only exact matches
are allowed.
caption (:obj:`bool`): Optional. Whether the caption should be used instead of text.
Default is ``False``.
"""
def __init__(self, list_, caption=False):
self.list_ = list_
self.caption = caption
self.name = 'Filters.msg_in({!r}, caption={!r})'.format(self.list_, self.caption)
def filter(self, message):
if self.caption:
txt = message.caption
else:
txt = message.text
return txt in self.list_
class _UpdateType(BaseFilter):
update_filter = True

View file

@ -604,6 +604,16 @@ class TestFilters(object):
update.message.from_user.language_code = 'da'
assert f(update)
def test_msg_in_filter(self, update):
update.message.text = 'test'
update.message.caption = 'caption'
assert Filters.msg_in(['test'])(update)
assert Filters.msg_in(['caption'], caption=True)(update)
assert not Filters.msg_in(['test'], caption=True)(update)
assert not Filters.msg_in(['caption'])(update)
def test_and_filters(self, update):
update.message.text = 'test'
update.message.forward_date = datetime.datetime.now()