-
Notifications
You must be signed in to change notification settings - Fork 0
Types of Handlers
A Handler
is an instance derived from the base class telegram.ext.Handler which is responsible for the routing of different kinds of updates (text, audio, inlinequery, button presses, ...) to their corresponding callback function in your code.
For example, if you want your bot to respond to the command /start
, you can use a CommandHandler that maps this user input to a callback named start_callback
:
def start_callback(bot, update):
update.message.reply_text("Welcome to my awesome bot!")
...
dispatcher.add_handler(CommandHandler("start", start_callback))
It is also possible to work with parameters for commands offered by your bot. Let's extend the start_callback
with some arguments so that the user can provide additional information in the same step:
def start_callback(bot, update, args):
user_says = " ".join(args)
update.message.reply_text("You said: " + user_says)
...
dispatcher.add_handler(CommandHandler("start", start_callback, pass_args=True))
Sending "/start Hello World!" to your bot will now split everything after /start separated by the space character into a list of words and pass it on to the args
parameter of start_callback
: ["Hello", "World!"]
. We join these chunks together by calling " ".join(args)
and echo the resulting string back to the user.
The argument passing described above works exactly the same when the user clicks on a deeply linked start URL, like this one:
https://t.me/roolsbot?start=Hello%20World!
Clicking this link will open your Telegram Client and show a big START button. When it is pressed, the URL parameters "Hello World!" will be passed on to the args
of your /start callback.
For more complex inputs you can employ the telegram.ext.RegexHandler, which internally uses the re
-module to match textual user input with a supplied pattern.
A quick example:
Keep in mind that for extracting URLs, #Hashtags, @Mentions, and other Telegram entities, there's no need to parse them with a RegexHandler
because the Bot API already sends them to us with every update. Refer to this snippet to learn how to work with entities instead.
To learn about all
- Wiki of
python-telegram-bot
© Copyright 2015-2025 – Licensed by Creative Commons
- Architecture Overview
- Builder Pattern for
Application
- Types of Handlers
- Working with Files and Media
- Exceptions, Warnings and Logging
- Concurrency in PTB
- Advanced Filters
- Storing data
- Making your bot persistent
- Adding Defaults
- Job Queue
- Arbitrary
callback_data
- Avoiding flood limits
- Webhooks
- Bot API Forward Compatiblity
- Frequently requested design patterns
- Code snippets
- Performance Optimizations
- Telegram Passport
- Bots built with PTB
- Automated Bot Tests