Skip to content
Back to top
View this page

# Application

class telegram.ext.Application(*, bot, update_queue, updater, job_queue, update_processor, persistence, context_types, post_init, post_shutdown, post_stop)

  Bases: `contextlib.AbstractAsyncContextManager`, `typing.Generic`

  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

  See also

  Your First Bot, Architecture Overview

  Use In

  `telegram.ext.ApplicationBuilder.application_class()`

  Available In

  - `telegram.ext.CallbackContext.application`

  - `telegram.ext.JobQueue.application`

  Returned In

  `telegram.ext.ApplicationBuilder.build()`

  Changed in version 20.0:

  - Initialization is now done through the `telegram.ext.ApplicationBuilder`.

  - Removed the attribute `groups`.

  bot

    The bot object that should be passed to the handlers.

    Type:

      `telegram.Bot`

  update_queue

    The synchronized queue that will contain the updates.

    Type:

      `asyncio.Queue`

  updater

    Optional. The updater used by this application.

    Type:

      `telegram.ext.Updater`

  chat_data

    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

    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

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

    Type:

      `dict`

  persistence

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

    Type:

      `telegram.ext.BasePersistence`

  handlers

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

    See also

    `add_handler()`, `add_handlers()`.

    Type:

      dict[`int`, list[`telegram.ext.BaseHandler`]]

  error_handlers

    A dictionary where the keys are error handlers and the values indicate whether they are to be run blocking.

    See also

    `add_error_handler()`

    Type:

      dict[coroutine function, `bool`]

  context_types

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

    Type:

      `telegram.ext.ContextTypes`

  post_init

    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

    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

    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__()

    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)

    Asynchronous context manager which `shuts down` the App.

  __repr__()

    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)

    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

    Hint

    This method currently has no influence on calls to `process_error()` that are already in progress.

    Warning

    This behavior should currently be considered an implementation detail and not as guaranteed behavior.

    See also

    Exceptions, Warnings and Logging

    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)

    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.

    Hint

    This method currently has no influence on calls to `process_update()` that are already in progress.

    Warning

    This behavior should currently be considered an implementation detail and not as guaranteed behavior.

    Parameters:

      - handler (`telegram.ext.BaseHandler`) – A BaseHandler instance.

      - group (`int`, optional) – The group identifier. Default is `0`.

  add_handlers(handlers, group=0)

    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 (Sequence[`telegram.ext.BaseHandler`] | dict[int, Sequence[`telegram.ext.BaseHandler`]]) –

        Specify a sequence of handlers or a dictionary where the keys are groups and values are handlers.

        Changed in version 21.7: Accepts any `collections.abc.Sequence` as input instead of just a list or tuple.

      - group (`int`, optional) – Specify which group the sequence of `handlers` should be added to. Defaults to `0`.

    Example:

        app.add_handlers(handlers={
            -1: [MessageHandler(...)],
            1: [CallbackQueryHandler(...), CommandHandler(...)]
        }

    Raises:

      TypeError – If the combination of arguments is invalid.

  static builder()

    Convenience method. Returns a new `telegram.ext.ApplicationBuilder`.

    Added in version 20.0.

  property concurrent_updates

    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)

    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:

      - coroutine (awaitable) –

        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 to `process_error()` as additional information for the error handlers. Moreover, the corresponding `chat_data` and `user_data` entries will be updated in the next run of `update_persistence()` after the `coroutine` is finished.

    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)

    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)

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

    Initializes the Application by initializing:

    - The `bot`, by calling `telegram.Bot.initialize()`.

    - The `updater`, by calling `telegram.ext.Updater.initialize()`.

    - The `persistence`, by loading persistent conversations and data.

    - The `update_processor` by calling `telegram.ext.BaseUpdateProcessor.initialize()`.

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

    See also

    `shutdown()`

  property job_queue
    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)

    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:

      - chat_ids (`int` | Collection[`int`], optional) – Chat IDs to mark.

      - user_ids (`int` | Collection[`int`], optional) – User IDs to mark.

  migrate_chat_data(message=None, old_chat_id=None, new_chat_id=None)

    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

    - Any data stored in `chat_data` at key `new_chat_id` will be overridden

    - The key `old_chat_id` of `chat_data` will be deleted

    - This does not update the `chat_id` attribute of any scheduled `telegram.ext.Job`.

    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.

    See also

    Storing Bot, User and Chat Related Data

    Parameters:

      - message (`telegram.Message`, optional) –

        A message with either `migrate_from_chat_id` or `migrate_to_chat_id`. Mutually exclusive with passing `old_chat_id` and `new_chat_id`.

        See also

        `telegram.ext.filters.StatusUpdate.MIGRATE`

      - old_chat_id (`int`, optional) – The old chat ID. Mutually exclusive with passing `message`

      - new_chat_id (`int`, optional) – The new chat ID. Mutually exclusive with passing `message`

    Raises:

      ValueError – Raised if the input is invalid.

  async process_error(update, error, job=None, coroutine=None)

    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:

    - `dispatch_error` was renamed to `process_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.

      - error (`Exception`) – The error that was raised.

      - 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 raised `telegram.ext.ApplicationHandlerStop`. `False`, otherwise.

    Return type:

      `bool`

  async process_update(update)

    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)

    Removes an error handler.

    Hint

    This method currently has no influence on calls to `process_error()` that are already in progress.

    Warning

    This behavior should currently be considered an implementation detail and not as guaranteed behavior.

    Parameters:

      callback (coroutine function) – The error handler to remove.

  remove_handler(handler, group=0)

    Remove a handler from the specified group.

    Hint

    This method currently has no influence on calls to `process_update()` that are already in progress.

    Warning

    This behavior should currently be considered an implementation detail and not as guaranteed behavior.

    Parameters:

      - handler (`telegram.ext.BaseHandler`) – A `telegram.ext.BaseHandler` instance.

      - group (`object`, optional) – The group identifier. Default is `0`.

  run_polling(poll_interval=0.0, timeout=datetime.timedelta(seconds=10), bootstrap_retries=0, allowed_updates=None, drop_pending_updates=None, close_loop=True, stop_signals=None)

    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:

    - `initialize()`

    - `post_init()`

    - `telegram.ext.Updater.start_polling()`

    - `start()`

    - Run the application until the users stops it

    - `telegram.ext.Updater.stop()`

    - `stop()`

    - `post_stop()`

    - `shutdown()`

    - `post_shutdown()`

    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()`.

    Changed in version Removed: the deprecated parameters `read_timeout`, `write_timeout`, `connect_timeout`, and `pool_timeout`. Use the corresponding methods in `telegram.ext.ApplicationBuilder` instead.

    Parameters:

      - poll_interval (`float`, optional) – Time to wait between polling updates from Telegram in seconds. Default is `0.0`.

      - timeout (`int` | `datetime.timedelta`, optional) –

        Passed to `telegram.Bot.get_updates.timeout`. Default is `timedelta(seconds=10)`.

        Changed in version v22.2: `datetime.timedelta` objects are accepted in addition to plain `int` values.

      - bootstrap_retries (`int`, optional) –

        Whether the bootstrapping phase (calling `initialize()` and the boostrapping of `telegram.ext.Updater.start_polling()`) will retry on failures on the Telegram server.

        - < 0 - retry indefinitely

        - 0 - no retries (default)

        - > 0 - retry up to X times

        Changed in version 21.11: The default value will be changed to from `-1` to `0`. Indefinite retries during bootstrapping are not recommended.

      - drop_pending_updates (`bool`, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is `False`.

      - allowed_updates (Sequence[`str`], optional) –

        Passed to `telegram.Bot.get_updates()`.

        Changed in version 21.9: Accepts any `collections.abc.Sequence` as input instead of just a list

      - close_loop (`bool`, optional) –

        If `True`, the current event loop will be closed upon shutdown. Defaults to `True`.

        See also

        `asyncio.loop.close()`

      - stop_signals (Sequence[`int`] | `None`, optional) –

        Signals that will shut down the app. Pass `None` to not use stop signals. Defaults to `signal.SIGINT`, `signal.SIGTERM` and `signal.SIGABRT` on non Windows platforms.

        Caution

        Not every `asyncio.AbstractEventLoop` implements `asyncio.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)

    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:

    - `initialize()`

    - `post_init()`

    - `telegram.ext.Updater.start_webhook()`

    - `start()`

    - Run the application until the users stops it

    - `telegram.ext.Updater.stop()`

    - `stop()`

    - `post_stop()`

    - `shutdown()`

    - `post_shutdown()`

    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:

      - 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 of `telegram.constants.SUPPORTED_WEBHOOK_PORTS` unless the bot is running behind a proxy. Defaults to `80`.

      - 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 (calling `initialize()` and the boostrapping of `telegram.ext.Updater.start_polling()`) 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 from `listen`, `port`, `url_path`, `cert`, and `key`.

      - allowed_updates (Sequence[`str`], optional) –

        Passed to `telegram.Bot.set_webhook()`.

        Changed in version 21.9: Accepts any `collections.abc.Sequence` as input instead of just a list

      - drop_pending_updates (`bool`, optional) – Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is `False`.

      - ip_address (`str`, optional) – Passed to `telegram.Bot.set_webhook()`.

      - max_connections (`int`, optional) – Passed to `telegram.Bot.set_webhook()`. Defaults to `40`.

      - close_loop (`bool`, optional) –

        If `True`, the current event loop will be closed upon shutdown. Defaults to `True`.

        See also

        `asyncio.loop.close()`

      - stop_signals (Sequence[`int`] | `None`, optional) –

        Signals that will shut down the app. Pass `None` to not use stop signals. Defaults to `signal.SIGINT`, `signal.SIGTERM` and `signal.SIGABRT`.

        Caution

        Not every `asyncio.AbstractEventLoop` implements `asyncio.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 a `http.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` or `str`. 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` and `port`. When using this param, you must also run a reverse proxy to the unix socket and set the appropriate `webhook_url`.

        Added in version 20.8.

        Changed in version 21.1: Added support to pass a socket instance itself.

  property running

    Indicates if this application is running.

    See also

    `start()`, `stop()`

    Type:

      `bool`

  async shutdown()

    Shuts down the Application by shutting down:

    - `bot` by calling `telegram.Bot.shutdown()`

    - `updater` by calling `telegram.ext.Updater.shutdown()`

    - `persistence` by calling `update_persistence()` and `BasePersistence.flush()`

    - `update_processor` by calling `telegram.ext.BaseUpdateProcessor.shutdown()`

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

    Starts

    - a background task that fetches updates from `update_queue` and processes them via `process_update()`.

    - `job_queue`, if set.

    - a background task that calls `update_persistence()` in regular intervals, if `persistence` is set.

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

    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

    - This does not stop `updater`. You need to either manually call `telegram.ext.Updater.stop()` or use one of `run_polling()` or `run_webhook()`.

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

    Raises:

      RuntimeError – If the application is not running.

  stop_running()

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

    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.

    See also

    `telegram.ext.BasePersistence.update_interval`, `mark_data_for_update_persistence()`

  property update_processor

    The update processor used by this application.

    See also

    Concurrency

    Added in version 20.4.

    Type:

      `telegram.ext.BaseUpdateProcessor`