Skip to content

Commit 3c7b037

Browse files
committed
add additional arguments 'groups' and 'groupdict' for regex handlers
1 parent c15a1bc commit 3c7b037

File tree

2 files changed

+49
-35
lines changed

2 files changed

+49
-35
lines changed

telegram/dispatcher.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,16 @@ class Dispatcher:
9191
Example: '/add item1 item2 item3' -> ['item1', 'item2', 'item3']
9292
For other updates, args will be None
9393
94+
For regex-based handlers, you can also request information about the match.
95+
For all other handlers, these will be None
96+
97+
groups:
98+
A tuple that contains the result of
99+
re.match(matcher, ...).groups()
100+
groupdict:
101+
A dictionary that contains the result of
102+
re.match(matcher, ...).groupdict()
103+
94104
Attributes:
95105
96106
Args:
@@ -185,7 +195,7 @@ def processUpdate(self, update):
185195
self.dispatchStringCommand(update)
186196
handled = True
187197
elif type(update) is str:
188-
self.dispatchStringRegex(update)
198+
self.dispatchRegex(update)
189199
handled = True
190200

191201
# An error happened while polling
@@ -195,7 +205,7 @@ def processUpdate(self, update):
195205

196206
# Telegram update (regex)
197207
if isinstance(update, Update):
198-
self.dispatchTelegramRegex(update)
208+
self.dispatchRegex(update)
199209
handled = True
200210

201211
# Telegram update (command)
@@ -469,25 +479,30 @@ def dispatchTelegramCommand(self, update):
469479
else:
470480
self.dispatchTo(self.unknown_telegram_command_handlers, update)
471481

472-
def dispatchTelegramRegex(self, update):
482+
def dispatchRegex(self, update):
473483
"""
474-
Dispatches an update to all regex handlers that match the message
475-
string.
484+
Dispatches an update to all string or telegram regex handlers that
485+
match the string/message content.
476486
477487
Args:
478-
command (str): The command keyword
479-
update (telegram.Update): The Telegram update that contains the
480-
command
488+
update (str, Update): The update that should be checked for matches
481489
"""
482490

483-
matching_handlers = []
484-
485-
for matcher in self.telegram_regex_handlers:
486-
if match(matcher, update.message.text):
487-
for handler in self.telegram_regex_handlers[matcher]:
488-
matching_handlers.append(handler)
489-
490-
self.dispatchTo(matching_handlers, update)
491+
if isinstance(update, Update):
492+
handlers = self.telegram_regex_handlers
493+
to_match = update.message.text
494+
elif isinstance(update, str):
495+
handlers = self.string_regex_handlers
496+
to_match = update
497+
498+
for matcher in handlers:
499+
m = match(matcher, to_match)
500+
if m:
501+
for handler in handlers[matcher]:
502+
self.call_handler(handler,
503+
update,
504+
groups=m.groups(),
505+
groupdict=m.groupdict())
491506

492507
def dispatchStringCommand(self, update):
493508
"""
@@ -504,25 +519,6 @@ def dispatchStringCommand(self, update):
504519
else:
505520
self.dispatchTo(self.unknown_string_command_handlers, update)
506521

507-
def dispatchStringRegex(self, update):
508-
"""
509-
Dispatches an update to all string regex handlers that match the
510-
string.
511-
512-
Args:
513-
command (str): The command keyword
514-
update (str): The string that contains the command
515-
"""
516-
517-
matching_handlers = []
518-
519-
for matcher in self.string_regex_handlers:
520-
if match(matcher, update):
521-
for handler in self.string_regex_handlers[matcher]:
522-
matching_handlers.append(handler)
523-
524-
self.dispatchTo(matching_handlers, update)
525-
526522
def dispatchType(self, update):
527523
"""
528524
Dispatches an update of any type.

tests/test_updater.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,10 @@ def stringHandlerTest(self, bot, update):
8989
self.received_message = update
9090
self.message_count += 1
9191

92+
def regexGroupHandlerTest(self, bot, update, groups=None, groupdict=None):
93+
self.received_message = (groups, groupdict)
94+
self.message_count += 1
95+
9296
def additionalArgsTest(self, bot, update, update_queue, args):
9397
self.received_message = update
9498
self.message_count += 1
@@ -348,6 +352,20 @@ def test_additionalArgs(self):
348352
self.assertEqual(self.received_message, '/test5 noresend')
349353
self.assertEqual(self.message_count, 2)
350354

355+
def test_regexGroupHandler(self):
356+
print('Testing optional groups and groupdict parameters')
357+
bot = MockBot('', messages=0)
358+
self.updater.bot = bot
359+
d = self.updater.dispatcher
360+
d.addStringRegexHandler('^(This).*?(?P<testgroup>regex group).*',
361+
self.regexGroupHandlerTest)
362+
queue = self.updater.start_polling(0.01)
363+
queue.put('This is a test message for regex group matching.')
364+
sleep(.1)
365+
self.assertEqual(self.received_message, (('This', 'regex group'),
366+
{'testgroup': 'regex group'}))
367+
368+
351369
def test_runAsyncWithAdditionalArgs(self):
352370
print('Testing @run_async with additional parameters')
353371
bot = MockBot('Test6', messages=2)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy