Application¶
- class telegram.ext.Application(*, bot, update_queue, updater, job_queue, update_processor, persistence, context_types, post_init, post_shutdown, post_stop)[source]¶
Bases:
typing.Generic
,typing.AsyncContextManager
This class dispatches all kinds of updates to its registered handlers, and is the entry point to a PTB application.
Tip
This class may not be initialized directly. Use
telegram.ext.ApplicationBuilder
orbuilder()
(for convenience).Instances of this class can be used as asyncio context managers, where
async with application: # code
is roughly equivalent to
try: await application.initialize() # code finally: await application.shutdown()
Returned In
See also
__aenter__()
and__aexit__()
.This class is a
Generic
class and accepts six type variables:The type of
bot
. Must betelegram.Bot
or a subclass of that class.The type of the argument
context
of callback functions for (error) handlers and jobs. Must betelegram.ext.CallbackContext
or a subclass of that class. This must be consistent with the following types.The type of the values of
user_data
.The type of the values of
chat_data
.The type of
bot_data
.The type of
job_queue
. Must either betelegram.ext.JobQueue
or a subclass of that orNone
.
Examples
See also
Changed in version 20.0:
Initialization is now done through the
telegram.ext.ApplicationBuilder
.Removed the attribute
groups
.
- chat_data[source]¶
A dictionary handlers can use to store data for the chat. For each integer chat id, the corresponding value of this mapping is available as
telegram.ext.CallbackContext.chat_data
in handler callbacks for updates from that chat.Changed in version 20.0:
chat_data
is now read-only. Note that the values of the mapping are still mutable, i.e. editingcontext.chat_data
within a handler callback is possible (and encouraged), but editing the mappingapplication.chat_data
itself is not.Tip
Manually modifying
chat_data
is almost never needed and unadvisable.Entries are never deleted automatically from this mapping. If you want to delete the data associated with a specific chat, e.g. if the bot got removed from that chat, please use
drop_chat_data()
.
- Type:
- user_data[source]¶
A dictionary handlers can use to store data for the user. For each integer user id, the corresponding value of this mapping is available as
telegram.ext.CallbackContext.user_data
in handler callbacks for updates from that user.Changed in version 20.0:
user_data
is now read-only. Note that the values of the mapping are still mutable, i.e. editingcontext.user_data
within a handler callback is possible (and encouraged), but editing the mappingapplication.user_data
itself is not.Tip
Manually modifying
user_data
is almost never needed and unadvisable.Entries are never deleted automatically from this mapping. If you want to delete the data associated with a specific user, e.g. if that user blocked the bot, please use
drop_user_data()
.
- Type:
- handlers[source]¶
A dictionary mapping each handler group to the list of handlers registered to that group.
See also
- Type:
Dict[
int
, List[telegram.ext.BaseHandler
]]
- error_handlers[source]¶
A dictionary where the keys are error handlers and the values indicate whether they are to be run blocking.
See also
- Type:
Dict[coroutine function,
bool
]
- context_types[source]¶
Specifies the types used by this dispatcher for the
context
argument of handler and job callbacks.
- post_init[source]¶
Optional. A callback that will be executed by
Application.run_polling()
andApplication.run_webhook()
after initializing the application viainitialize()
.- Type:
- post_shutdown[source]¶
Optional. A callback that will be executed by
Application.run_polling()
andApplication.run_webhook()
after shutting down the application viashutdown()
.- Type:
- post_stop[source]¶
Optional. A callback that will be executed by
Application.run_polling()
andApplication.run_webhook()
after stopping the application viastop()
.Added in version 20.1.
- Type:
- async __aenter__()[source]¶
Asynchronous context manager which
initializes
the App.- Returns:
The initialized App instance.
- Raises:
Exception – If an exception is raised during initialization,
shutdown()
is called in this case.
- async __aexit__(exc_type, exc_val, exc_tb)[source]¶
Asynchronous context manager which
shuts down
the App.
- __repr__()[source]¶
Give a string representation of the application in the form
Application[bot=...]
.As this class doesn’t implement
object.__str__()
, the default implementation will be used, which is equivalent to__repr__()
.- Returns:
- add_error_handler(callback, block=True)[source]¶
Registers an error handler in the Application. This handler will receive every error which happens in your bot. See the docs of
process_error()
for more details on how errors are handled.Note
Attempts to add the same callback multiple times will be ignored.
Examples
See also
- Parameters:
callback (coroutine function) –
The callback function for this error handler. Will be called when an error is raised. Callback signature:
async def callback(update: Optional[object], context: CallbackContext)
The error that happened will be present in
telegram.ext.CallbackContext.error
.block (
bool
, optional) – Determines whether the return value of the callback should be awaited before processing the next error handler inprocess_error()
. Defaults toTrue
.
- add_handler(handler, group=0)[source]¶
Register a handler.
TL;DR: Order and priority counts. 0 or 1 handlers per group will be used. End handling of update with
telegram.ext.ApplicationHandlerStop
.A handler must be an instance of a subclass of
telegram.ext.BaseHandler
. All handlers are organized in groups with a numeric value. The default group is 0. All groups will be evaluated for handling an update, but only 0 or 1 handler per group will be used. Iftelegram.ext.ApplicationHandlerStop
is raised from one of the handlers, no further handlers (regardless of the group) will be called.The priority/order of handlers is determined as follows:
Priority of the group (lower group number == higher priority)
The first handler in a group which can handle an update (see
telegram.ext.BaseHandler.check_update
) will be used. Other handlers from the group will not be used. The order in which handlers were added to the group defines the priority.
Warning
Adding persistent
telegram.ext.ConversationHandler
after the application has been initialized is discouraged. This is because the persisted conversation states need to be loaded into memory while the application is already processing updates, which might lead to race conditions and undesired behavior. In particular, current conversation states may be overridden by the loaded data.- Parameters:
handler (
telegram.ext.BaseHandler
) – A BaseHandler instance.
- add_handlers(handlers, group=0)[source]¶
Registers multiple handlers at once. The order of the handlers in the passed sequence(s) matters. See
add_handler()
for details.Added in version 20.0.
- Parameters:
handlers (List[
telegram.ext.BaseHandler
] | Dict[int, List[telegram.ext.BaseHandler
]]) – Specify a sequence of handlers or a dictionary where the keys are groups and values are handlers.group (
int
, optional) – Specify which group the sequence ofhandlers
should be added to. Defaults to0
.
Example:
app.add_handlers(handlers={ -1: [MessageHandler(...)], 1: [CallbackQueryHandler(...), CommandHandler(...)] }
- Raises:
TypeError – If the combination of arguments is invalid.
- static builder()[source]¶
Convenience method. Returns a new
telegram.ext.ApplicationBuilder
.Added in version 20.0.
- property concurrent_updates[source]¶
The number of concurrent updates that will be processed in parallel. A value of
0
indicates updates are not being processed concurrently.Changed in version 20.4: This is now just a shortcut to
update_processor.max_concurrent_updates
.See also
- Type:
- create_task(coroutine, update=None, *, name=None)[source]¶
Thin wrapper around
asyncio.create_task()
that handles exceptions raised by thecoroutine
withprocess_error()
.Note
If
coroutine
raises an exception, it will be set on the task created by this method even though it’s handled byprocess_error()
.If the application is currently running, tasks created by this method will be awaited with
stop()
.
See also
- Parameters:
The awaitable to run as task.
Changed in version 20.2: Accepts
asyncio.Future
and generator-based coroutine functions.Deprecated since version 20.4: Since Python 3.12, generator-based coroutine functions are no longer accepted.
update (
object
, optional) – If set, will be passed toprocess_error()
as additional information for the error handlers. Moreover, the correspondingchat_data
anduser_data
entries will be updated in the next run ofupdate_persistence()
after thecoroutine
is finished.
- Keyword Arguments:
The name of the task.
Added in version 20.4.
- Returns:
The created task.
- Return type:
- drop_chat_data(chat_id)[source]¶
Drops the corresponding entry from the
chat_data
. Will also be deleted from the persistence on the next run ofupdate_persistence()
, if applicable.Warning
When using
concurrent_updates
or thejob_queue
,process_update()
ortelegram.ext.Job.run()
may re-create this entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.Added in version 20.0.
- drop_user_data(user_id)[source]¶
Drops the corresponding entry from the
user_data
. Will also be deleted from the persistence on the next run ofupdate_persistence()
, if applicable.Warning
When using
concurrent_updates
or thejob_queue
,process_update()
ortelegram.ext.Job.run()
may re-create this entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.Added in version 20.0.
- async initialize()[source]¶
Initializes the Application by initializing:
The
bot
, by callingtelegram.Bot.initialize()
.The
updater
, by callingtelegram.ext.Updater.initialize()
.The
persistence
, by loading persistent conversations and data.The
update_processor
by callingtelegram.ext.BaseUpdateProcessor.initialize()
.
Does not call
post_init
- that is only done byrun_polling()
andrun_webhook()
.See also
- mark_data_for_update_persistence(chat_ids=None, user_ids=None)[source]¶
Mark entries of
chat_data
anduser_data
to be updated on the next run ofupdate_persistence()
.Tip
Use this method sparingly. If you have to use this method, it likely means that you access and modify
context.application.chat/user_data[some_id]
within a callback. Note that for data which should be available globally in all handler callbacks independent of the chat/user, it is recommended to usebot_data
instead.Added in version 20.3.
- migrate_chat_data(message=None, old_chat_id=None, new_chat_id=None)[source]¶
Moves the contents of
chat_data
at keyold_chat_id
to the keynew_chat_id
. Also marks the entries to be updated accordingly in the next run ofupdate_persistence()
.Warning
Any data stored in
chat_data
at keynew_chat_id
will be overriddenThe key
old_chat_id
ofchat_data
will be deletedThis does not update the
chat_id
attribute of any scheduledtelegram.ext.Job
.
When using
concurrent_updates
or thejob_queue
,process_update()
ortelegram.ext.Job.run()
may re-create the old entry due to the asynchronous nature of these features. Please make sure that your program can avoid or handle such situations.- Parameters:
message (
telegram.Message
, optional) –A message with either
migrate_from_chat_id
ormigrate_to_chat_id
. Mutually exclusive with passingold_chat_id
andnew_chat_id
.old_chat_id (
int
, optional) – The old chat ID. Mutually exclusive with passingmessage
new_chat_id (
int
, optional) – The new chat ID. Mutually exclusive with passingmessage
- Raises:
ValueError – Raised if the input is invalid.
- async process_error(update, error, job=None, coroutine=None)[source]¶
Processes an error by passing it to all error handlers registered with
add_error_handler()
. If one of the error handlers raisestelegram.ext.ApplicationHandlerStop
, the error will not be handled by other error handlers. Raisingtelegram.ext.ApplicationHandlerStop
also stops processing of the update when this method is called byprocess_update()
, i.e. no further handlers (even in other groups) will handle the update. All other exceptions raised by an error handler will just be logged.Changed in version 20.0:
dispatch_error
was renamed toprocess_error()
.Exceptions raised by error handlers are now properly logged.
telegram.ext.ApplicationHandlerStop
is no longer reraised but converted into the return value.
- Parameters:
update (
object
|telegram.Update
) – The update that caused the error.job (
telegram.ext.Job
, optional) –The job that caused the error.
Added in version 20.0.
coroutine (coroutine function, optional) – The coroutine that caused the error.
- Returns:
True
, if one of the error handlers raisedtelegram.ext.ApplicationHandlerStop
.False
, otherwise.- Return type:
- async process_update(update)[source]¶
Processes a single update and marks the update to be updated by the persistence later. Exceptions raised by handler callbacks will be processed by
process_error()
.See also
Changed in version 20.0: Persistence is now updated in an interval set by
telegram.ext.BasePersistence.update_interval
.- Parameters:
update (
telegram.Update
|object
|telegram.error.TelegramError
) – The update to process.- Raises:
RuntimeError – If the application was not initialized.
- remove_error_handler(callback)[source]¶
Removes an error handler.
- Parameters:
callback (coroutine function) – The error handler to remove.
- remove_handler(handler, group=0)[source]¶
Remove a handler from the specified group.
- Parameters:
handler (
telegram.ext.BaseHandler
) – Atelegram.ext.BaseHandler
instance.group (
object
, optional) – The group identifier. Default is0
.
- run_polling(poll_interval=0.0, timeout=10, bootstrap_retries=-1, read_timeout=None, write_timeout=None, connect_timeout=None, pool_timeout=None, allowed_updates=None, drop_pending_updates=None, close_loop=True, stop_signals=None)[source]¶
Convenience method that takes care of initializing and starting the app, polling updates from Telegram using
telegram.ext.Updater.start_polling()
and a graceful shutdown of the app on exit.The app will shut down when
KeyboardInterrupt
orSystemExit
is raised. This also works from within handlers, error handlers and jobs. However, usingstop_running()
will give a somewhat cleaner shutdown behavior than manually raising those exceptions. On unix, the app will also shut down on receiving the signals specified bystop_signals
.The order of execution by
run_polling()
is roughly as follows:Run the application until the users stops it
A small wrapper is passed to
telegram.ext.Updater.start_polling.error_callback
which forwards errors occurring during polling toregistered error handlers
. The update parameter of the callback will be set toNone
.Tip
When combining
python-telegram-bot
with otherasyncio
based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and theupdater
. Keeping the event loop running and listening for a stop signal is then up to you.To gracefully stop the execution of this method from within a handler, job or error callback, use
stop_running()
.
- Parameters:
poll_interval (
float
, optional) – Time to wait between polling updates from Telegram in seconds. Default is0.0
.timeout (
int
, optional) – Passed totelegram.Bot.get_updates.timeout
. Default is10
seconds.bootstrap_retries (
int
, optional) –Whether the bootstrapping phase of the
telegram.ext.Updater
will retry on failures on the Telegram server.< 0 - retry indefinitely (default)
0 - no retries
> 0 - retry up to X times
read_timeout (
float
, optional) –Value to pass to
telegram.Bot.get_updates.read_timeout
. Defaults toDEFAULT_NONE
.Changed in version 20.7: Defaults to
DEFAULT_NONE
instead of2
.Deprecated since version 20.7: Deprecated in favor of setting the timeout via
telegram.ext.ApplicationBuilder.get_updates_read_timeout()
.write_timeout (
float
|None
, optional) –Value to pass to
telegram.Bot.get_updates.write_timeout
. Defaults toDEFAULT_NONE
.Deprecated since version 20.7: Deprecated in favor of setting the timeout via
telegram.ext.ApplicationBuilder.get_updates_write_timeout()
.connect_timeout (
float
|None
, optional) –Value to pass to
telegram.Bot.get_updates.connect_timeout
. Defaults toDEFAULT_NONE
.Deprecated since version 20.7: Deprecated in favor of setting the timeout via
telegram.ext.ApplicationBuilder.get_updates_connect_timeout()
.pool_timeout (
float
|None
, optional) –Value to pass to
telegram.Bot.get_updates.pool_timeout
. Defaults toDEFAULT_NONE
.Deprecated since version 20.7: Deprecated in favor of setting the timeout via
telegram.ext.ApplicationBuilder.get_updates_pool_timeout()
.drop_pending_updates (
bool
, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default isFalse
.allowed_updates (List[
str
], optional) – Passed totelegram.Bot.get_updates()
.close_loop (
bool
, optional) –If
True
, the current event loop will be closed upon shutdown. Defaults toTrue
.See also
stop_signals (Sequence[
int
] |None
, optional) –Signals that will shut down the app. Pass
None
to not use stop signals. Defaults tosignal.SIGINT
,signal.SIGTERM
andsignal.SIGABRT
on non Windows platforms.Caution
Not every
asyncio.AbstractEventLoop
implementsasyncio.loop.add_signal_handler()
. Most notably, the standard event loop on Windows,asyncio.ProactorEventLoop
, does not implement this method. If this method is not available, stop signals can not be set.
- Raises:
RuntimeError – If the Application does not have an
telegram.ext.Updater
.
- run_webhook(listen='127.0.0.1', port=80, url_path='', cert=None, key=None, bootstrap_retries=0, webhook_url=None, allowed_updates=None, drop_pending_updates=None, ip_address=None, max_connections=40, close_loop=True, stop_signals=None, secret_token=None, unix=None)[source]¶
Convenience method that takes care of initializing and starting the app, listening for updates from Telegram using
telegram.ext.Updater.start_webhook()
and a graceful shutdown of the app on exit.The app will shut down when
KeyboardInterrupt
orSystemExit
is raised. This also works from within handlers, error handlers and jobs. However, usingstop_running()
will give a somewhat cleaner shutdown behavior than manually raising those exceptions. On unix, the app will also shut down on receiving the signals specified bystop_signals
.If
cert
andkey
are not provided, the webhook will be started directly onhttp://listen:port/url_path
, so SSL can be handled by another application. Else, the webhook will be started onhttps://listen:port/url_path
. Also callstelegram.Bot.set_webhook()
as required.The order of execution by
run_webhook()
is roughly as follows:Run the application until the users stops it
Important
If you want to use this method, you must install PTB with the optional requirement
webhooks
, i.e.pip install "python-telegram-bot[webhooks]"
Tip
When combining
python-telegram-bot
with otherasyncio
based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and theupdater
. Keeping the event loop running and listening for a stop signal is then up to you.To gracefully stop the execution of this method from within a handler, job or error callback, use
stop_running()
.
See also
- Parameters:
listen (
str
, optional) – IP-Address to listen on. Defaults to 127.0.0.1.port (
int
, optional) – Port the bot should be listening on. Must be one oftelegram.constants.SUPPORTED_WEBHOOK_PORTS
unless the bot is running behind a proxy. Defaults to80
.url_path (
str
, optional) – Path inside url. Defaults to `` ‘’ ``cert (
pathlib.Path
|str
, optional) – Path to the SSL certificate file.key (
pathlib.Path
|str
, optional) – Path to the SSL key file.bootstrap_retries (
int
, optional) –Whether the bootstrapping phase of the
telegram.ext.Updater
will retry on failures on the Telegram server.< 0 - retry indefinitely
0 - no retries (default)
> 0 - retry up to X times
webhook_url (
str
, optional) – Explicitly specify the webhook url. Useful behind NAT, reverse proxy, etc. Default is derived fromlisten
,port
,url_path
,cert
, andkey
.allowed_updates (List[
str
], optional) – Passed totelegram.Bot.set_webhook()
.drop_pending_updates (
bool
, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default isFalse
.ip_address (
str
, optional) – Passed totelegram.Bot.set_webhook()
.max_connections (
int
, optional) – Passed totelegram.Bot.set_webhook()
. Defaults to40
.close_loop (
bool
, optional) –If
True
, the current event loop will be closed upon shutdown. Defaults toTrue
.See also
stop_signals (Sequence[
int
] |None
, optional) –Signals that will shut down the app. Pass
None
to not use stop signals. Defaults tosignal.SIGINT
,signal.SIGTERM
andsignal.SIGABRT
.Caution
Not every
asyncio.AbstractEventLoop
implementsasyncio.loop.add_signal_handler()
. Most notably, the standard event loop on Windows,asyncio.ProactorEventLoop
, does not implement this method. If this method is not available, stop signals can not be set.secret_token (
str
, optional) –Secret token to ensure webhook requests originate from Telegram. See
telegram.Bot.set_webhook.secret_token
for more details.When added, the web server started by this call will expect the token to be set in the
X-Telegram-Bot-Api-Secret-Token
header of an incoming request and will raise ahttp.HTTPStatus.FORBIDDEN
error if either the header isn’t set or it is set to a wrong token.Added in version 20.0.
unix (
pathlib.Path
|str
|socket.socket
, optional) –Can be either:
the path to the unix socket file as
pathlib.Path
orstr
. This will be passed to tornado.netutil.bind_unix_socket to create the socket. If the Path does not exist, the file will be created.or the socket itself. This option allows you to e.g. restrict the permissions of the socket for improved security. Note that you need to pass the correct family, type and socket options yourself.
Caution
This parameter is a replacement for the default TCP bind. Therefore, it is mutually exclusive with
listen
andport
. When using this param, you must also run a reverse proxy to the unix socket and set the appropriatewebhook_url
.Added in version 20.8.
Changed in version 21.1: Added support to pass a socket instance itself.
- async shutdown()[source]¶
Shuts down the Application by shutting down:
bot
by callingtelegram.Bot.shutdown()
updater
by callingtelegram.ext.Updater.shutdown()
persistence
by callingupdate_persistence()
andBasePersistence.flush()
update_processor
by callingtelegram.ext.BaseUpdateProcessor.shutdown()
Does not call
post_shutdown
- that is only done byrun_polling()
andrun_webhook()
.See also
- Raises:
RuntimeError – If the application is still
running
.
- async start()[source]¶
Starts
a background task that fetches updates from
update_queue
and processes them viaprocess_update()
.job_queue
, if set.a background task that calls
update_persistence()
in regular intervals, ifpersistence
is set.
Note
This does not start fetching updates from Telegram. To fetch updates, you need to either start
updater
manually or use one ofrun_polling()
orrun_webhook()
.Tip
When using a custom logic for startup and shutdown of the application, eventual cancellation of pending tasks should happen only after
stop()
has been called in order to ensure that the tasks mentioned above are not cancelled prematurely.See also
- Raises:
RuntimeError – If the application is already running or was not initialized.
- async stop()[source]¶
Stops the process after processing any pending updates or tasks created by
create_task()
. Also stopsjob_queue
, if set. Finally, callsupdate_persistence()
andBasePersistence.flush()
onpersistence
, if set.Warning
Once this method is called, no more updates will be fetched from
update_queue
, even if it’s not empty.See also
Note
This does not stop
updater
. You need to either manually calltelegram.ext.Updater.stop()
or use one ofrun_polling()
orrun_webhook()
.Does not call
post_stop
- that is only done byrun_polling()
andrun_webhook()
.
- Raises:
RuntimeError – If the application is not running.
- stop_running()[source]¶
This method can be used to stop the execution of
run_polling()
orrun_webhook()
from within a handler, job or error callback. This allows a graceful shutdown of the application, i.e. the methods listed inrun_polling
andrun_webhook
will still be executed.This method can also be called within
post_init()
. This allows for a graceful, early shutdown of the application if some condition is met (e.g., a database connection could not be established).Note
If the application is not running and this method is not called within
post_init()
, this method does nothing.Warning
This method is designed to for use in combination with
run_polling()
orrun_webhook()
. Using this method in combination with a custom logic for starting and stopping the application is not guaranteed to work as expected. Use at your own risk.Added in version 20.5.
Changed in version 21.2: Added support for calling within
post_init()
.
- async update_persistence()[source]¶
Updates
user_data
,chat_data
,bot_data
inpersistence
along withcallback_data_cache
and the conversation states of any persistentConversationHandler
registered for this application.For
user_data
andchat_data
, only those entries are updated which either were used or have been manually marked viamark_data_for_update_persistence()
since the last run of this method.Tip
This method will be called in regular intervals by the application. There is usually no need to call it manually.
Note
Any data is deep copied with
copy.deepcopy()
before handing it over to the persistence in order to avoid race conditions, so all persisted data must be copyable.