CommandHandler

class telegram.ext.CommandHandler(command, callback, filters=None, block=True, has_args=None)[source]

Bases: telegram.ext.BaseHandler

Handler class to handle Telegram commands.

Commands are Telegram messages that start with /, optionally followed by an @ and the bot’s name and/or some additional text. The handler will add a list to the CallbackContext named CallbackContext.args. It will contain a list of strings, which is the text following the command split on single or consecutive whitespace characters.

By default, the handler listens to messages as well as edited messages. To change this behavior use ~filters.UpdateType.EDITED_MESSAGE in the filter argument.

Note

CommandHandler does not handle (edited) channel posts and does not handle commands that are part of a caption. Please use MessageHandler with a suitable combination of filters (e.g. telegram.ext.filters.UpdateType.CHANNEL_POSTS, telegram.ext.filters.CAPTION and telegram.ext.filters.Regex) to handle those messages.

Warning

When setting block to False, you cannot rely on adding custom attributes to telegram.ext.CallbackContext. See its docs for more info.

Changed in version 20.0:

  • Renamed the attribute command to commands, which now is always a frozenset

  • Updating the commands this handler listens to is no longer possible.

Parameters:
Raises:

ValueError – When the command is too long or has illegal chars.

commands[source]

The set of commands this handler should listen for.

Type:

frozenset[str]

callback[source]

The callback function for this handler.

Type:

coroutine function

filters[source]

Optional. Only allow updates with these filters.

Type:

telegram.ext.filters.BaseFilter

block[source]

Determines whether the return value of the callback should be awaited before processing the next handler in telegram.ext.Application.process_update().

Type:

bool

has_args[source]

Optional argument, otherwise all implementations of CommandHandler will break. Defaults to None, which means the handler will process any args or no args.

Added in version 20.5.

Type:

bool | int | None

check_update(update)[source]

Determines whether an update should be passed to this handler’s callback.

Parameters:

update (telegram.Update | object) – Incoming update.

Returns:

The list of args for the handler.

Return type:

list

collect_additional_context(context, update, application, check_result)[source]

Add text after the command to CallbackContext.args as list, split on single whitespaces and add output of data filters to CallbackContext as well.