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, contextlib.AbstractAsyncContextManager

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 or builder() (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()

See also

__aenter__() and __aexit__().

This class is a Generic class and accepts six type variables:

  1. The type of bot. Must be telegram.Bot or a subclass of that class.

  2. The type of the argument context of callback functions for (error) handlers and jobs. Must be telegram.ext.CallbackContext or a subclass of that class. This must be consistent with the following types.

  3. The type of the values of user_data.

  4. The type of the values of chat_data.

  5. The type of bot_data.

  6. The type of job_queue. Must either be telegram.ext.JobQueue or a subclass of that or None.

Examples

Echo Bot

Changed in version 20.0:

bot[source]

The bot object that should be passed to the handlers.

Type:

telegram.Bot

update_queue[source]

The synchronized queue that will contain the updates.

Type:

asyncio.Queue

updater[source]

Optional. The updater used by this application.

Type:

telegram.ext.Updater

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. editing context.chat_data within a handler callback is possible (and encouraged), but editing the mapping application.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:

types.MappingProxyType

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. editing context.user_data within a handler callback is possible (and encouraged), but editing the mapping application.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:

types.MappingProxyType

bot_data[source]

A dictionary handlers can use to store data for the bot.

Type:

dict

persistence[source]

The persistence class to store data that should be persistent over restarts.

Type:

telegram.ext.BasePersistence

handlers[source]

A dictionary mapping each handler group to the list of handlers registered to that group.

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.

Type:

dict[coroutine function, bool]

context_types[source]

Specifies the types used by this dispatcher for the context argument of handler and job callbacks.

Type:

telegram.ext.ContextTypes

post_init[source]

Optional. A callback that will be executed by Application.run_polling() and Application.run_webhook() after initializing the application via initialize().

Type:

coroutine function

post_shutdown[source]

Optional. A callback that will be executed by Application.run_polling() and Application.run_webhook() after shutting down the application via shutdown().

Type:

coroutine function

post_stop[source]

Optional. A callback that will be executed by Application.run_polling() and Application.run_webhook() after stopping the application via stop().

Added in version 20.1.

Type:

coroutine function

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:

str

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

Errorhandler Bot

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 in process_error(). Defaults to True.

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. If telegram.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:
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:

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

Concurrency

Type:

int

create_task(coroutine, update=None, *, name=None)[source]

Thin wrapper around asyncio.create_task() that handles exceptions raised by the coroutine with process_error().

Note

  • If coroutine raises an exception, it will be set on the task created by this method even though it’s handled by process_error().

  • If the application is currently running, tasks created by this method will be awaited with stop().

See also

Concurrency

Parameters:
Keyword Arguments:

name (str, optional) –

The name of the task.

Added in version 20.4.

Returns:

The created task.

Return type:

asyncio.Task

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 of update_persistence(), if applicable.

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.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.

Parameters:

chat_id (int) – The chat id to delete. The entry will be deleted even if it is not empty.

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 of update_persistence(), if applicable.

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.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.

Parameters:

user_id (int) – The user id to delete. The entry will be deleted even if it is not empty.

async initialize()[source]

Initializes the Application by initializing:

Does not call post_init - that is only done by run_polling() and run_webhook().

See also

shutdown()

property job_queue[source]
The JobQueue used by the

telegram.ext.Application.

See also

Job Queue

Type:

telegram.ext.JobQueue

mark_data_for_update_persistence(chat_ids=None, user_ids=None)[source]

Mark entries of chat_data and user_data to be updated on the next run of update_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 use bot_data instead.

Added in version 20.3.

Parameters:
migrate_chat_data(message=None, old_chat_id=None, new_chat_id=None)[source]

Moves the contents of chat_data at key old_chat_id to the key new_chat_id. Also marks the entries to be updated accordingly in the next run of update_persistence().

Warning

When using concurrent_updates or the job_queue, process_update() or telegram.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:
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 raises telegram.ext.ApplicationHandlerStop, the error will not be handled by other error handlers. Raising telegram.ext.ApplicationHandlerStop also stops processing of the update when this method is called by process_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:

Parameters:
Returns:

True, if one of the error handlers raised telegram.ext.ApplicationHandlerStop. False, otherwise.

Return type:

bool

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

Concurrency

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:
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 or SystemExit is raised. This also works from within handlers, error handlers and jobs. However, using stop_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 by stop_signals.

The order of execution by run_polling() is roughly as follows:

A small wrapper is passed to telegram.ext.Updater.start_polling.error_callback which forwards errors occurring during polling to registered error handlers. The update parameter of the callback will be set to None.

Tip

  • When combining python-telegram-bot with other asyncio 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 the updater. 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:
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 or SystemExit is raised. This also works from within handlers, error handlers and jobs. However, using stop_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 by stop_signals.

If cert and key are not provided, the webhook will be started directly on http://listen:port/url_path, so SSL can be handled by another application. Else, the webhook will be started on https://listen:port/url_path. Also calls telegram.Bot.set_webhook() as required.

The order of execution by run_webhook() is roughly as follows:

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 other asyncio 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 the updater. 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

Webhooks

Parameters:
property running[source]

Indicates if this application is running.

See also

start(), stop()

Type:

bool

async shutdown()[source]

Shuts down the Application by shutting down:

Does not call post_shutdown - that is only done by run_polling() and run_webhook().

See also

initialize()

Raises:

RuntimeError – If the application is still running.

async start()[source]

Starts

Note

This does not start fetching updates from Telegram. To fetch updates, you need to either start updater manually or use one of run_polling() or run_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

stop()

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 stops job_queue, if set. Finally, calls update_persistence() and BasePersistence.flush() on persistence, 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

start()

Note

Raises:

RuntimeError – If the application is not running.

stop_running()[source]

This method can be used to stop the execution of run_polling() or run_webhook() from within a handler, job or error callback. This allows a graceful shutdown of the application, i.e. the methods listed in run_polling and run_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() or run_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 in persistence along with callback_data_cache and the conversation states of any persistent ConversationHandler registered for this application.

For user_data and chat_data, only those entries are updated which either were used or have been manually marked via mark_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.

property update_processor[source]

The update processor used by this application.

See also

Concurrency

Added in version 20.4.

Type:

telegram.ext.BaseUpdateProcessor