CommandHandler faster check (#1074)

Fixes #1073
This commit is contained in:
Wagner Macedo 2018-04-17 01:37:29 -03:00 committed by Noam Meltzer
parent cbfb7df643
commit 5efd5e2586
3 changed files with 26 additions and 3 deletions

View file

@ -66,6 +66,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `thodnev <https://github.com/thodnev>`_
- `Valentijn <https://github.com/Faalentijn>`_
- `voider1 <https://github.com/voider1>`_
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
- `wjt <https://github.com/wjt>`_
Please add yourself here alphabetically when you submit your first pull request.

View file

@ -140,6 +140,10 @@ class CommandHandler(Handler):
command.append(
message.bot.username) # in case the command was sent without a username
if not (command[0].lower() in self.command
and command[1].lower() == message.bot.username.lower()):
return False
if self.filters is None:
res = True
elif isinstance(self.filters, list):
@ -147,8 +151,7 @@ class CommandHandler(Handler):
else:
res = self.filters(message)
return res and (command[0].lower() in self.command
and command[1].lower() == message.bot.username.lower())
return res
return False

View file

@ -21,7 +21,7 @@ import pytest
from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import CommandHandler, Filters
from telegram.ext import CommandHandler, Filters, BaseFilter
message = Message(1, User(1, '', False), None, Chat(1, ''), text='test')
@ -246,3 +246,22 @@ class TestCommandHandler(object):
def test_other_update_types(self, false_update):
handler = CommandHandler('test', self.callback_basic)
assert not handler.check_update(false_update)
def test_filters_for_wrong_command(self, message):
"""Filters should not be executed if the command does not match the handler"""
class TestFilter(BaseFilter):
def __init__(self):
self.tested = False
def filter(self, message):
self.tested = True
test_filter = TestFilter()
handler = CommandHandler('foo', self.callback_basic, filters=test_filter)
message.text = '/bar'
handler.check_update(Update(0, message=message))
assert not test_filter.tested