1717# You should have received a copy of the GNU Lesser Public License
1818# along with this program. If not, see [http://www.gnu.org/licenses/].
1919""" This module contains the CommandHandler class """
20+ import warnings
2021
2122from .handler import Handler
2223from telegram import Update
@@ -34,6 +35,10 @@ class CommandHandler(Handler):
3435 callback (function): A function that takes ``bot, update`` as
3536 positional arguments. It will be called when the ``check_update``
3637 has determined that an update should be processed by this handler.
38+ filters (telegram.ext.BaseFilter): A filter inheriting from
39+ :class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in
40+ :class:`telegram.ext.filters.Filters`. Filters can be combined using bitwise
41+ operators (& for and, | for or).
3742 allow_edited (Optional[bool]): If the handler should also accept edited messages.
3843 Default is ``False``
3944 pass_args (optional[bool]): If the handler should be passed the
@@ -62,6 +67,7 @@ class CommandHandler(Handler):
6267 def __init__ (self ,
6368 command ,
6469 callback ,
70+ filters = None ,
6571 allow_edited = False ,
6672 pass_args = False ,
6773 pass_update_queue = False ,
@@ -75,9 +81,17 @@ def __init__(self,
7581 pass_user_data = pass_user_data ,
7682 pass_chat_data = pass_chat_data )
7783 self .command = command
84+ self .filters = filters
7885 self .allow_edited = allow_edited
7986 self .pass_args = pass_args
8087
88+ # We put this up here instead of with the rest of checking code
89+ # in check_update since we don't wanna spam a ton
90+ if isinstance (self .filters , list ):
91+ warnings .warn ('Using a list of filters in MessageHandler is getting '
92+ 'deprecated, please use bitwise operators (& and |) '
93+ 'instead. More info: https://git.io/vPTbc.' )
94+
8195 def check_update (self , update ):
8296 if (isinstance (update , Update )
8397 and (update .message or update .edited_message and self .allow_edited )):
@@ -87,8 +101,16 @@ def check_update(self, update):
87101 command = message .text [1 :].split (' ' )[0 ].split ('@' )
88102 command .append (
89103 update .message .bot .username ) # in case the command was send without a username
90- return (message .text .startswith ('/' ) and command [0 ] == self .command
91- and command [1 ] == update .message .bot .username )
104+
105+ if self .filters is None :
106+ res = True
107+ elif isinstance (self .filters , list ):
108+ res = any (func (message ) for func in self .filters )
109+ else :
110+ res = self .filters (message )
111+
112+ return res and (message .text .startswith ('/' ) and command [0 ] == self .command
113+ and command [1 ] == update .message .bot .username )
92114 else :
93115 return False
94116
0 commit comments