Skip to content

Commit 10e4aee

Browse files
committed
Extended autowiring example
1 parent cafd9f8 commit 10e4aee

File tree

1 file changed

+16
-5
lines changed

1 file changed

+16
-5
lines changed

examples/autowiring.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88
the explicit pass_* flags.
99
1010
Usage:
11-
Autowiring example: Try sending /start, "test", /data or something random.
11+
Autowiring example: Try sending /start, /data, "My name is Leandro", or some random text.
1212
Press Ctrl-C on the command line or send a signal to the process to stop the
1313
bot.
1414
"""
1515

1616
import logging
1717

18-
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
18+
from telegram.ext import Updater, CommandHandler, RegexHandler
1919

2020
# Enable logging
2121
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
@@ -39,7 +39,7 @@ def start(bot, update, args):
3939
def simple_update_only(update):
4040
"""
4141
A simple handler that only needs an `update` object.
42-
Useful e.g. for /help commands that need to do nothing but reply with some text.
42+
Useful e.g. for basic commands like /help that need to do nothing but reply with some text.
4343
"""
4444
update.message.reply_text("This should have produced an error "
4545
"for the MessageHandler in group=1.")
@@ -59,6 +59,11 @@ def callback_with_data(bot, update, chat_data, user_data):
5959
update.message.reply_text(msg, quote=True)
6060

6161

62+
def regex_with_groups(bot, update, groups, groupdict):
63+
update.message.reply_text("Nice, your {} is {}.".format(groups[0], groups[1]))
64+
update.message.reply_text('Groupdict: {}'.format(groupdict))
65+
66+
6267
def main():
6368
# Create the EventHandler and pass it your bot's token.
6469
updater = Updater("TOKEN")
@@ -69,10 +74,16 @@ def main():
6974
# Inject the `args` parameter automagically
7075
dp.add_handler(CommandHandler("start", start, autowire=True))
7176

77+
# A RegexHandler example where `groups` and `groupdict` are passed automagically
78+
# Examples: Send "My name is Leandro" or "My cat is blue".
79+
dp.add_handler(RegexHandler(r'[Mm]y (?P<object>.*) is (?P<value>.*)',
80+
regex_with_groups,
81+
autowire=True))
82+
7283
# This will raise an error because the bot argument is missing...
73-
dp.add_handler(MessageHandler(Filters.text, simple_update_only), group=1)
84+
dp.add_handler(CommandHandler('help', simple_update_only), group=1)
7485
# ... but with the autowiring capability, you can have callbacks with only an `update` argument.
75-
dp.add_handler(MessageHandler(Filters.text, simple_update_only, autowire=True), group=2)
86+
dp.add_handler(CommandHandler('help', simple_update_only, autowire=True), group=2)
7687

7788
# Passing `chat_data` and `user_data` explicitly...
7889
dp.add_handler(CommandHandler("data", callback_with_data,

0 commit comments

Comments
 (0)