Skip to content

Commit 5efd5e2

Browse files
wagnerluis1982tsnoam
authored andcommitted
CommandHandler faster check (python-telegram-bot#1074)
Fixes python-telegram-bot#1073
1 parent cbfb7df commit 5efd5e2

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

AUTHORS.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ The following wonderful people contributed directly or indirectly to this projec
6666
- `thodnev <https://github.com/thodnev>`_
6767
- `Valentijn <https://github.com/Faalentijn>`_
6868
- `voider1 <https://github.com/voider1>`_
69+
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
6970
- `wjt <https://github.com/wjt>`_
7071

7172
Please add yourself here alphabetically when you submit your first pull request.

telegram/ext/commandhandler.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,15 +140,18 @@ def check_update(self, update):
140140
command.append(
141141
message.bot.username) # in case the command was sent without a username
142142

143+
if not (command[0].lower() in self.command
144+
and command[1].lower() == message.bot.username.lower()):
145+
return False
146+
143147
if self.filters is None:
144148
res = True
145149
elif isinstance(self.filters, list):
146150
res = any(func(message) for func in self.filters)
147151
else:
148152
res = self.filters(message)
149153

150-
return res and (command[0].lower() in self.command
151-
and command[1].lower() == message.bot.username.lower())
154+
return res
152155

153156
return False
154157

tests/test_commandhandler.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
2323
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
24-
from telegram.ext import CommandHandler, Filters
24+
from telegram.ext import CommandHandler, Filters, BaseFilter
2525

2626
message = Message(1, User(1, '', False), None, Chat(1, ''), text='test')
2727

@@ -246,3 +246,22 @@ def test_pass_job_or_update_queue(self, dp, message):
246246
def test_other_update_types(self, false_update):
247247
handler = CommandHandler('test', self.callback_basic)
248248
assert not handler.check_update(false_update)
249+
250+
def test_filters_for_wrong_command(self, message):
251+
"""Filters should not be executed if the command does not match the handler"""
252+
253+
class TestFilter(BaseFilter):
254+
def __init__(self):
255+
self.tested = False
256+
257+
def filter(self, message):
258+
self.tested = True
259+
260+
test_filter = TestFilter()
261+
262+
handler = CommandHandler('foo', self.callback_basic, filters=test_filter)
263+
message.text = '/bar'
264+
265+
handler.check_update(Update(0, message=message))
266+
267+
assert not test_filter.tested

0 commit comments

Comments
 (0)