Skip to content
Back to top
View this page

# Updater

class telegram.ext.Updater(bot, update_queue)

  Bases: `contextlib.AbstractAsyncContextManager`

  This class fetches updates for the bot either via long polling or by starting a webhook server. Received updates are enqueued into the `update_queue` and may be fetched from there to handle them appropriately.

  Instances of this class can be used as asyncio context managers, where

      async with updater:
          # code

  is roughly equivalent to

      try:
          await updater.initialize()
          # code
      finally:
          await updater.shutdown()

  See also

  `__aenter__()` and `__aexit__()`.

  See also

  Architecture Overview, Builder Pattern

  Use In

  `telegram.ext.ApplicationBuilder.updater()`

  Available In

  `telegram.ext.Application.updater`

  Changed in version 20.0:

  - Removed argument and attribute `user_sig_handler`

  - The only arguments and attributes are now `bot` and `update_queue` as now the sole purpose of this class is to fetch updates. The entry point to a PTB application is now `telegram.ext.Application`.

  Parameters:

    - bot (`telegram.Bot`) – The bot used with this Updater.

    - update_queue (`asyncio.Queue`) – Queue for the updates.

  bot

    The bot used with this Updater.

    Type:

      `telegram.Bot`

  update_queue

    Queue for the updates.

    Type:

      `asyncio.Queue`

  async __aenter__()

    Asynchronous context manager which `initializes` the Updater.

    Returns:

      The initialized Updater 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 Updater.

  __repr__()

    Give a string representation of the updater in the form `Updater[bot=...]`.

    As this class doesn’t implement `object.__str__()`, the default implementation will be used, which is equivalent to `__repr__()`.

    Returns:

      `str`

  async initialize()

    Initializes the Updater & the associated `bot` by calling `telegram.Bot.initialize()`.

    See also

    `shutdown()`

  async shutdown()

    Shutdown the Updater & the associated `bot` by calling `telegram.Bot.shutdown()`.

    See also

    `initialize()`

    Raises:

      RuntimeError – If the updater is still running.

  async start_polling(poll_interval=0.0, timeout=datetime.timedelta(seconds=10), bootstrap_retries=0, allowed_updates=None, drop_pending_updates=None, error_callback=None)

    Starts polling updates from Telegram.

    Changed in version 20.0: Removed the `clean` argument in favor of `drop_pending_updates`.

    Changed in version 22.0: Removed the deprecated arguments `read_timeout`, `write_timeout`, `connect_timeout`, and `pool_timeout` in favor of setting the timeouts via the corresponding methods of `telegram.ext.ApplicationBuilder`. or by specifying the timeout via `telegram.Bot.get_updates_request`.

    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`. Defaults to `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 of 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.

      - 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

      - drop_pending_updates (`bool`, optional) –

        Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is `False`.

        Added in version 13.4.

      - error_callback (Callable[[`telegram.error.TelegramError`], `None`], optional) –

        Callback to handle `telegram.error.TelegramError` s that occur while calling `telegram.Bot.get_updates()` during polling. Defaults to `None`, in which case errors will be logged. Callback signature:

            def callback(error: telegram.error.TelegramError)

        Note

        The `error_callback` must not be a coroutine function! If asynchronous behavior of the callback is wanted, please schedule a task from within the callback.

    Returns:

      The update queue that can be filled from the main thread.

    Return type:

      `asyncio.Queue`

    Raises:

      RuntimeError – If the updater is already running or was not initialized.

  async start_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, secret_token=None, unix=None)

    Starts a small http server to listen for updates via webhook. 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.

    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]"

    See also

    Webhooks

    Changed in version 13.4: `start_webhook()` now always calls `telegram.Bot.set_webhook()`, so pass `webhook_url` instead of calling `updater.bot.set_webhook(webhook_url)` manually.

    Changed in version 20.0:

    - Removed the `clean` argument in favor of `drop_pending_updates` and removed the deprecated argument `force_event_loop`.

    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 (http(s)://listen:port/<url_path>). Defaults to `''`.

      - cert (`pathlib.Path` | `str`, optional) – Path to the SSL certificate file.

      - key (`pathlib.Path` | `str`, optional) – Path to the SSL key file.

      - drop_pending_updates (`bool`, optional) –

        Whether to clean any pending updates on Telegram servers before actually starting to poll. Default is `False`.

        Added in version 13.4.

      - bootstrap_retries (`int`, optional) –

        Whether the bootstrapping phase of 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`.

      - ip_address (`str`, optional) –

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

        Added in version 13.4.

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

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

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

      - max_connections (`int`, optional) –

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

        Added in version 13.6.

      - secret_token (`str`, optional) –

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

        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.

    Returns:

      The update queue that can be filled from the main thread.

    Return type:

      `queue.Queue`

    Raises:

      RuntimeError – If the updater is already running or was not initialized.

  async stop()

    Stops the polling/webhook.

    See also

    `start_polling()`, `start_webhook()`

    Raises:

      RuntimeError – If the updater is not running.