Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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>`_
Expand Down
33 changes: 33 additions & 0 deletions telegram/ext/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -909,6 +909,39 @@ def filter(self, message):
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

Expand Down
10 changes: 10 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,16 @@ def test_language_filter_multiple(self, update):
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()
Expand Down