|
17 | 17 | # You should have received a copy of the GNU Lesser Public License |
18 | 18 | # along with this program. If not, see [http://www.gnu.org/licenses/]. |
19 | 19 | """This module contains the Filters for use with the MessageHandler class.""" |
| 20 | + |
| 21 | +import re |
20 | 22 | from telegram import Chat |
21 | 23 | from future.utils import string_types |
22 | 24 |
|
@@ -171,6 +173,33 @@ def filter(self, message): |
171 | 173 | command = _Command() |
172 | 174 | """:obj:`Filter`: Messages starting with ``/``.""" |
173 | 175 |
|
| 176 | + class regex(BaseFilter): |
| 177 | + """ |
| 178 | + Filters updates by searching for an occurence of ``pattern`` in the message text. |
| 179 | + The ``re.search`` function is used to determine whether an update should be filtered. |
| 180 | + Refer to the documentation of the ``re`` module for more information. |
| 181 | +
|
| 182 | + Note: Does not allow passing groups or a groupdict like the ``RegexHandler`` yet, |
| 183 | + but this will probably be implemented in a future update, gradually phasing out the |
| 184 | + RegexHandler (see https://github.com/python-telegram-bot/python-telegram-bot/issues/835). |
| 185 | +
|
| 186 | + Examples: |
| 187 | + Example ``CommandHandler("start", deep_linked_callback, Filters.regex('parameter'))`` |
| 188 | +
|
| 189 | + Args: |
| 190 | + pattern (:obj:`str` | :obj:`Pattern`): The regex pattern. |
| 191 | + """ |
| 192 | + |
| 193 | + def __init__(self, pattern): |
| 194 | + self.pattern = re.compile(pattern) |
| 195 | + self.name = 'Filters.regex({})'.format(self.pattern) |
| 196 | + |
| 197 | + # TODO: Once the callback revamp (#1026) is done, the regex filter should be able to pass |
| 198 | + # the matched groups and groupdict to the context object. |
| 199 | + |
| 200 | + def filter(self, message): |
| 201 | + return bool(self.pattern.search(message.text)) |
| 202 | + |
174 | 203 | class _Reply(BaseFilter): |
175 | 204 | name = 'Filters.reply' |
176 | 205 |
|
|
0 commit comments