Skip to content
Back to top
View this page

# CallbackContext

class telegram.ext.CallbackContext(application, chat_id=None, user_id=None)

  This is a context object passed to the callback called by `telegram.ext.BaseHandler` or by the `telegram.ext.Application` in an error handler added by `telegram.ext.Application.add_error_handler` or to the callback of a `telegram.ext.Job`.

  Note

  `telegram.ext.Application` will create a single context for an entire update. This means that if you got 2 handlers in different groups and they both get called, they will receive the same `CallbackContext` object (of course with proper attributes like `matches` differing). This allows you to add custom attributes in a lower handler group callback, and then subsequently access those attributes in a higher handler group callback. Note that the attributes on `CallbackContext` might change in the future, so make sure to use a fairly unique name for the attributes.

  Warning

  Do not combine custom attributes with `telegram.ext.BaseHandler.block` set to `False` or `telegram.ext.Application.concurrent_updates` set to `True`. Due to how those work, it will almost certainly execute the callbacks for an update out of order, and the attributes that you think you added will not be present.

  This class is a `Generic` class and accepts four type variables:

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

  2. The type of `user_data` (if `user_data` is not `None`).

  3. The type of `chat_data` (if `chat_data` is not `None`).

  4. The type of `bot_data` (if `bot_data` is not `None`).

  Examples

  - Context Types Bot

  - Custom Webhook Bot

  See also

  `telegram.ext.ContextTypes.DEFAULT_TYPE`, Job Queue

  Use In

  `telegram.ext.ApplicationBuilder.context_types()`

  Returned In

  `telegram.ext.Application.builder()`

  Parameters:

    - application (`telegram.ext.Application`) – The application associated with this context.

    - chat_id (`int`, optional) –

      The ID of the chat associated with this object. Used to provide `chat_data`.

      Added in version 20.0.

    - user_id (`int`, optional) –

      The ID of the user associated with this object. Used to provide `user_data`.

      Added in version 20.0.

  coroutine

    Optional. Only present in error handlers if the error was caused by an awaitable run with `Application.create_task()` or a handler callback with `block=False`.

    Type:

      awaitable

  matches

    Optional. If the associated update originated from a `filters.Regex`, this will contain a list of match objects for every pattern where `re.search(pattern, string)` returned a match. Note that filters short circuit, so combined regex filters will not always be evaluated.

    Type:

      list[`re.Match`]

  args

    Optional. Arguments passed to a command if the associated update is handled by `telegram.ext.CommandHandler`, `telegram.ext.PrefixHandler` or `telegram.ext.StringCommandHandler`. It contains a list of the words in the text after the command, using any whitespace string as a delimiter.

    Type:

      list[`str`]

  error

    Optional. The error that was raised. Only present when passed to an error handler registered with `telegram.ext.Application.add_error_handler`.

    Type:

      `Exception`

  job

    Optional. The job which originated this callback. Only present when passed to the callback of `telegram.ext.Job` or in error handlers if the error is caused by a job.

    Changed in version 20.0: `job` is now also present in error handlers if the error is caused by a job.

    Type:

      `telegram.ext.Job`

  property application

    The application associated with this context.

    Type:

      `telegram.ext.Application`

  property bot

    The bot associated with this context.

    Type:

      `telegram.Bot`

  property bot_data

    Optional. An object that can be used to keep any data in. For each update it will be the same `ContextTypes.bot_data`. Defaults to `dict`.

    See also

    Storing Bot, User and Chat Related Data

    Type:

      `ContextTypes.bot_data`

  property chat_data

    Optional. An object that can be used to keep any data in. For each update from the same chat id it will be the same `ContextTypes.chat_data`. Defaults to `dict`.

    Warning

    When a group chat migrates to a supergroup, its chat id will change and the `chat_data` needs to be transferred. For details see our wiki page.

    See also

    Storing Bot, User and Chat Related Data

    Changed in version 20.0: The chat data is now also present in error handlers if the error is caused by a job.

    Type:

      `ContextTypes.chat_data`

  drop_callback_data(callback_query)

    Deletes the cached data for the specified callback query.

    Added in version 13.6.

    Note

    Will not raise exceptions in case the data is not found in the cache. Will raise `KeyError` in case the callback query can not be found in the cache.

    See also

    Arbitrary callback_data

    Parameters:

      callback_query (`telegram.CallbackQuery`) – The callback query.

    Raises:

      KeyError | RuntimeError – `KeyError`, if the callback query can not be found in the cache and `RuntimeError`, if the bot doesn’t allow for arbitrary callback data.

  classmethod from_error(update, error, application, job=None, coroutine=None)

    Constructs an instance of `telegram.ext.CallbackContext` to be passed to the error handlers.

    See also

    `telegram.ext.Application.add_error_handler()`

    Changed in version 20.0: Removed arguments `async_args` and `async_kwargs`.

    Parameters:

      - update (`object` | `telegram.Update`) – The update associated with the error. May be `None`, e.g. for errors in job callbacks.

      - error (`Exception`) – The error.

      - application (`telegram.ext.Application`) – The application associated with this context.

      - job (`telegram.ext.Job`, optional) –

        The job associated with the error.

        Added in version 20.0.

      - coroutine (awaitable, optional) –

        The awaitable associated with this error if the error was caused by a coroutine run with `Application.create_task()` or a handler callback with `block=False`.

        Added in version 20.0.

        Changed in version 20.2: Accepts `asyncio.Future` and generator-based coroutine functions.

    Returns:

      `telegram.ext.CallbackContext`

  classmethod from_job(job, application)

    Constructs an instance of `telegram.ext.CallbackContext` to be passed to a job callback.

    See also

    `telegram.ext.JobQueue()`

    Parameters:

      - job (`telegram.ext.Job`) – The job.

      - application (`telegram.ext.Application`) – The application associated with this context.

    Returns:

      `telegram.ext.CallbackContext`

  classmethod from_update(update, application)

    Constructs an instance of `telegram.ext.CallbackContext` to be passed to the handlers.

    See also

    `telegram.ext.Application.add_handler()`

    Parameters:

      - update (`object` | `telegram.Update`) – The update.

      - application (`telegram.ext.Application`) – The application associated with this context.

    Returns:

      `telegram.ext.CallbackContext`

  property job_queue

    The `JobQueue` used by the `telegram.ext.Application`.

    See also

    Job Queue

    Type:

      `telegram.ext.JobQueue`

  property match

    The first match from `matches`. Useful if you are only filtering using a single regex filter. Returns `None` if `matches` is empty.

    Type:

      `re.Match`

  async refresh_data()

    If `application` uses persistence, calls `telegram.ext.BasePersistence.refresh_bot_data()` on `bot_data`, `telegram.ext.BasePersistence.refresh_chat_data()` on `chat_data` and `telegram.ext.BasePersistence.refresh_user_data()` on `user_data`, if appropriate.

    Will be called by `telegram.ext.Application.process_update()` and `telegram.ext.Job.run()`.

    Added in version 13.6.

  update(data)

    Updates `self.__slots__` with the passed data.

    Parameters:

      data (dict[`str`, `object`]) – The data.

  property update_queue

    The `asyncio.Queue` instance used by the `telegram.ext.Application` and (usually) the `telegram.ext.Updater` associated with this context.

    Type:

      `asyncio.Queue`

  property user_data

    Optional. An object that can be used to keep any data in. For each update from the same user it will be the same `ContextTypes.user_data`. Defaults to `dict`.

    See also

    Storing Bot, User and Chat Related Data

    Changed in version 20.0: The user data is now also present in error handlers if the error is caused by a job.

    Type:

      `ContextTypes.user_data`