API Reference

Bot

class telegrampy.ext.commands.Bot(token: str, *, description: str | None = None, owner_id: int | None = None, owner_ids: list[int] | None = None, help_command: ~telegrampy.ext.commands.help.HelpCommand | None = <telegrampy.ext.commands.help.DefaultHelpCommand object>, **options: ~typing.Any)

Represents a Telegram bot.

Parameters:
description

The bot’s description.

Type:

str | None

owner_id

The owner’s ID.

Type:

int | None

owner_ids

The owner IDs.

Type:

list[int] | None

@command(self, name: str | None = None, **kwargs: Any) Callable[[Callable[Concatenate[CogT, ContextT, P], Coro[T]] | Callable[Concatenate[ContextT, P], Coro[T]]], Command[CogT, P, T]]

Turns a function into a Command and adds it to the bot.

Parameters:
  • name (str | None) – The name of the command to create, defaulting to the name of the function.

  • kwargs – The keyword arguments to pass into the Command constructor.

Raises:
await add_cog(cog: Cog, *, override: bool = False) None

This function is a coroutine.

Adds a cog to the bot.

Parameters:
  • cog (Cog) – The cog to add.

  • override (bool) – Whether to remove conflicting cogs with the same name, rather than raising an exception.

Raises:
add_command(command: CommandT) CommandT

Adds a command.

Parameters:

command (telegrampy.ext.commands.Command) – The command to add.

Returns:

The command added.

Return type:

telegrampy.ext.commands.Command

Raises:
add_inline_keyboard(message_id: int, keyboard: InlineKeyboard) None

Binds InlineKeyboard to a specific message on the client, to listen for updates. This is intended to be used when you want the inline keyboard to last longer than the lifecycle of the program.

add_listener(func: CoroFunc, name: str | None = None) None

Registers a function as a listener.

Parameters:
  • func – The function to register.

  • name (str | None) – The name of the event to register the function as.

property cogs: Mapping[str, Cog]

A read-only mapping of cogs added to the bot.

Type:

Mapping[str, Cog]

command(name: str | None = None, **kwargs: Any) Callable[[Callable[Concatenate[CogT, ContextT, P], Coro[T]] | Callable[Concatenate[ContextT, P], Coro[T]]], Command[CogT, P, T]]

Turns a function into a Command and adds it to the bot.

Parameters:
  • name (str | None) – The name of the command to create, defaulting to the name of the function.

  • kwargs – The keyword arguments to pass into the Command constructor.

Raises:
property commands: list[Command]

A list of the commands added to the bot.

Type:

list[Command]

event(func: CoroFunc) CoroFunc

Turns a function into an event handler.

Parameters:

func – The function to make an event handler.

await get_chat(chat_id: int) Chat

This function is a coroutine.

Fetches a chat by ID.

Parameters:

chat_id (int) – The ID of the chat to fetch.

Returns:

The chat that was fetched.

Return type:

telegrampy.Chat

Raises:

telegrampy.HTTPException – Fetching the chat failed.

get_cog(name: str) Cog | None

Returns the cog instance added to the bot by name, if found.

Parameters:

name (str) – The name of the cog to look for.

Returns:

The cog, if found.

Return type:

Cog | None

get_command(name: str) Command | None

Gets a command by name.

Parameters:

name (str) – The command name.

Returns:

The command with the name.

Return type:

telegrampy.ext.commands.Command

await get_context(message: Message, *, cls: type[ContextT] = <class 'telegrampy.ext.commands.context.Context'>) ContextT | None

This function is a coroutine.

Gets context for a given message.

Parameters:

message (telegrampy.Message) – The message to get context from.

Returns:

The context created, if applicable.

Return type:

telegrampy.ext.commands.Context | None

Raises:

telegrampy.ext.commands.CommandNotFound – The command specified was not found.

await get_me() ClientUser

This function is a coroutine.

Fetches the authenticated bot account.

Returns:

The user that was fetched.

Return type:

telegrampy.ClientUser

Raises:

telegrampy.HTTPException – Fetching the bot user failed.

get_partial_chat(chat_id) PartialChat

Returns a partial chat for the given ID, without fetching anything from Telegram.

This is useful for interacting with chat that you have an ID for, without making extra API calls.

Returns:

The partial chat that can be interacted with.

Return type:

telegrampy.PartialChat

property help_command: HelpCommand | None

The bot’s help command.

Type:

telegrampy.ext.commands.HelpCommand | None

listen(name: str | None = None) Callable[[CoroFunc], CoroFunc]

A decorator that registers a function as a listener.

Parameters:

name (str | None) – The name of the event to register the function as.

await load_extension(name: str) None

This function is a coroutine.

Loads an extension.

Parameters:

name (str) – The module location of the extension.

Raises:
await process_commands(message: Message) None

This function is a coroutine.

Process commands that have been registered. By default this is called in on_message. If you override on_message() you need to call this manually.

Parameters:

message (telegrampy.Message) – The message to process.

await reload_extension(name: str) None

This function is a coroutine.

Unloads and loads back the extension, reverting to the original state if anything fails.

Parameters:

name (str) – The module location of the extension.

Raises:
await remove_cog(name: str) Cog | None

This function is a coroutine.

Removes a cog from the bot.

Parameters:

name (str) – The name of the cog to remove.

Returns:

The cog that was removed, if found.

Return type:

Cog | None

remove_command(name: str) Command | None

Removes a command by name.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command removed.

Return type:

telegrampy.ext.commands.Command

remove_listener(func: CoroFunc) None

Removes a listener.

Parameters:

func – The function that is registered as a listener.

run() None

Runs the bot.

await set_description(description: str | None, *, language_code: str | None = None, short: bool = False) None

This function is a coroutine.

Sets the description that is shown for the bot.

Parameters:
  • description (str) – The new description. Maxmium of 512 characters for full description and 120 for short description.

  • language_code (str) – The two-letter ISO 639-1 language code for this description.

  • short (str) – Whether to set the short or full description. The full description appears on empty chats with the bot, while the long decription appears on the profile page.

await set_name(name: str | None, *, language_code: str | None = None) None

This function is a coroutine.

Sets the description that is shown for the bot.

Parameters:

name (str) – The display name of the bot, no longer than 64 chatacters.

await setup_hook() None

This function is a coroutine.

Called before the bot begins polling updates. This is meant to be overrided by subclasses that require asynchronous setup.

await start() None

This function is a coroutine.

Starts the bot.

Raises:

RuntimeError – This instance of the bot is already running.

await stop() None

This function is a coroutine.

Stops the bot.

Raises:

RuntimeError – This instance of the bot is not running.

await sync() None

This function is a coroutine.

Sets the user-facing Telegram commands to the curently registered commands with the instance.

Raises:

telegrampy.HTTPException – Setting the currently registered comands failed. This will happen of commands are missing a description.

await unload_extension(name: str) None

This function is a coroutine.

Unloads an extension.

Parameters:

name (str) – The module location of the extension.

Raises:

ExtensionNotLoaded – The extension is not loaded.

await wait_for(event: str, *, check: Callable[..., bool] | None = None, timeout: float | None = None) Any

This function is a coroutine.

Waits for an event.

Parameters:

event (str) – The name of the event to wait for.

Events

telegrampy.on_command(ctx)

Called when a command is invoked.

telegrampy.on_command_completion(ctx)

Called when a command is completed.

telegrampy.on_command_error(ctx, error)

Called when an error occurs in a command.

Command

telegrampy.ext.commands.command(name: str | None = None, **kwargs: Any) Callable[[Callable[Concatenate[CogT, ContextT, P], Coro[T]] | Callable[Concatenate[ContextT, P], Coro[T]]], Command[CogT, P, T]]

Turns a function into a Command.

Parameters:
  • name (str | None) – The name of the command to create, defaulting to the name of the function.

  • kwargs – The keyword arguments to pass into the Command constructor.

Raises:

TypeError – The function is not a coroutine.

class telegrampy.ext.commands.Command(func: Callable[Concatenate[CogT, ContextT, P], Coro[T]] | Callable[Concatenate[ContextT, P], Coro[T]], **kwargs)

Represents a command.

name

The name of the command.

Type:

str

description

The description of the command.

Type:

str

usage

The usage of the command.

Type:

str

aliases

The aliases for the command.

Type:

str

callback

The callback of the command.

hidden

If the command is hidden.

Type:

bool

cog

The cog the command is in.

Type:

telegrampy.ext.commands.Cog

bot

The bot the command is in.

Type:

telegrampy.ext.commands.Bot

add_check(func: Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) None

Adds a check to the command.

Parameters:

func – The function to add to the checks.

await can_run(ctx: Context) bool

This function is a coroutine.

Checks if the command can run.

Parameters:

ctx (telegrampy.ext.commands.Context) – The context invoking the command.

Returns:

A boolean indicating if the command can be invoked or not.

Return type:

bool

Raises:

telegrampy.ext.commands.CheckFailure – A check failed.

await invoke(ctx: Context) None

This function is a coroutine.

Invokes the command with given context.

Parameters:

ctx (telegrampy.ext.commands.Context) – The context invoking the command.

Returns:

A boolean that indicates if the command can be invoked or not.

Return type:

bool

Raises:

telegrampy.ext.commands.CommandError – The command failed.

remove_check(func: Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) None

Removes a check from the command.

Parameters:

func – The function to remove from the checks.

property signature: str

Returns a signature for a command that can be used in help commands.

<required> required param [optional] optional param [params…] optional list of params [optional=0] optional param defaults to 0

Type:

str

Checks

@telegrampy.ext.commands.check(check_func: Callable[[Context[Any]], bool | Coroutine[Any, Any, bool]]) Callable[[Command | Callable[[...], Coroutine[Any, Any, Any]]], Command | Callable[[...], Coroutine[Any, Any, Any]]]

Makes a check for a command.

@telegrampy.ext.commands.is_owner Callable[[Command | Callable[[...], Coroutine[Any, Any, Any]]], Command | Callable[[...], Coroutine[Any, Any, Any]]]

A command check for checking that the user is the owner.

@telegrampy.ext.commands.is_private_chat Callable[[Command | Callable[[...], Coroutine[Any, Any, Any]]], Command | Callable[[...], Coroutine[Any, Any, Any]]]

A command check for checking that the chat is a private chat.

@telegrampy.ext.commands.is_not_private_chat Callable[[Command | Callable[[...], Coroutine[Any, Any, Any]]], Command | Callable[[...], Coroutine[Any, Any, Any]]]

A command check for checking that the chat is not a private chat.

Help Command

class telegrampy.ext.commands.HelpCommand(*args: Any, **kwargs: Any)

Help command template.

context

The telegrampy.ext.commands.Context that invoked the current help callback.

Type:

telegrampy.ext.commands.Context | None

command_attrs

A dictionary of options to pass into the actual telegrampy.ext.commands.Command instance.

Type:

dict

await command_callback(ctx: Context, query: str | None) None

This function is a coroutine.

The callback that searches for a matching commmand or cog.

This should not be overridden unless it is necessary.

Parameters:

query (str | None) – The user’s query. Defaults to None.

await filter_commands(commands: list[CommandT]) list[CommandT]

This function is a coroutine.

Takes a list of commands and filters them.

Parameters:

commands (list[telegrampy.ext.commands.Command]) – The commands to filter.

Returns:

The filtered commands.

Return type:

list[telegrampy.ext.commands.Command]

await get_command_signature(command: Command) str

This function is a coroutine.

The method that gets a formatted command signature

Example: /help [command]

await send_bot_help() None

This function is a coroutine.

The method that sends help for the bot.

This is called when no query is provided. This method should handle the sending of the help message.

await send_cog_help(cog: Cog) None

This function is a coroutine.

The method that sends help for a cog.

This is called when a cog matches the query. This method should handle the sending of the help message.

Parameters:

cog (telegrampy.ext.commands.Cog) – The cog that matched the query

await send_command_help(command: Command) None

The method that sends help for a command.

This is called when a command matches the query. This method should handle the sending of the help message.

Parameters:

command (telegrampy.ext.commands.Command) – The command that matched the query

await send_not_found(query: str) None

This function is a coroutine.

The method that sends a ‘not found’ message or similar.

This method is called when no match is found for the query.

Parameters:

query (str) – The user’s query

class telegrampy.ext.commands.DefaultHelpCommand(*args: Any, **kwargs: Any)

The default help command.

This help command mimics BotFather’s help command look.

Parameters:
  • no_category (str | None) – The heading for commands without a category. Defaults to “No Category”.

  • sort_commands (bool | None) – Whether to sort the commands. Defaults to True.

await format_command(command: Command) list[str]

This function is a coroutine.

The method that formats an individual command.

Parameters:

command (Command) – The command to format.

await format_commands(commands: list[Command], *, heading: str) list[str]

This function is a coroutine.

The method that formats a given list of commands.

Parameters:
  • commands (list[:class`telegrampy.ext.commands.Command`]) – The list of commands to format.

  • heading (str) – The heading to display.

get_ending_note() str

Returns the command’s ending note.

await send_bot_help() None

This function is a coroutine.

The method that sends help for the bot.

This is called when no query is provided. This method should handle the sending of the help message.

await send_cog_help(cog: Cog) None

This function is a coroutine.

The method that sends help for a cog.

This is called when a cog matches the query. This method should handle the sending of the help message.

Parameters:

cog (telegrampy.ext.commands.Cog) – The cog that matched the query

await send_command_help(command: Command) None

The method that sends help for a command.

This is called when a command matches the query. This method should handle the sending of the help message.

Parameters:

command (telegrampy.ext.commands.Command) – The command that matched the query

Cog

class telegrampy.ext.commands.Cog

The base cog class that cogs inherit from.

cog_check(ctx) bool

A special check that registers for all commands in the cog.

await cog_load() None

This function could be a coroutine.

Called when the cog is added to the bot. Subclasses can override this with their own behavior.

await cog_unload() None

This function could be a coroutine.

Called when the cog is removed from the bot. Subclasses can override this with their own behavior.

property description: str | None

The cog’s description.

Type:

str

get_commands() list[Command[Self, ..., Any]]

Returns all the commands registered in the cog.

:param list[Command]: The commands defined inside the cog.

classmethod listener(name: str | None = None) Callable[[FuncT], FuncT]

Makes a method in a cog a listener.

Parameters:

name (str | None) – The name of the event to register the function as.

Context

class telegrampy.ext.commands.Context

Context for a command.

bot

The bot that created the context.

Type:

Bot

message

The message the invoked the command.

Type:

telegrampy.Message

command

The command that is being invoked.

Type:

Command

invoked_with

The text that triggered the invocation.

Type:

str

chat

The chat the command is being invoked in.

Type:

telegrampy.Chat

author

The author invoking the command.

Type:

telegrampy.User

command_failed

If the command failed or not.

Type:

bool

args

The arguments passed into the command.

Type:

list

kwargs

The keyword arguments passed into the command.

Type:

dict

await reply(content: str, *, parse_mode: ParseMode | None = None, reply_markup: ReplyMarkup | None = None) Message

This function is a coroutine.

Replys to the message.

Parameters:
  • content (str) – The content of the message to send.

  • parse_mode (str | None) – The parse mode of the message to send.

  • reply_markup (InlineKeyboard | ReplyKeyboard | ReplyKeyboardRemove | ForceReply | None) – The reply markup interface to send with the message.

Returns:

The message sent.

Return type:

telegrampy.Message

Raises:

telegrampy.HTTPException – Sending the message failed.

Converters

class telegrampy.ext.commands.Converter

The base class for custom converters that require Context in order to function.

await convert(ctx: Context, argument: str) Any

This function is a coroutine.

Does the converting.

class telegrampy.ext.commands.ChatConverter

Converts an argument into a telegrampy.Chat.

await convert(ctx: Context, argument: str) Chat

This function is a coroutine.

Does the converting.

class telegrampy.ext.commands.MemberConverter

Converts an argument into a telegrampy.Member.

await convert(ctx: Context, argument: str) Member

This function is a coroutine.

Does the converting.

Exceptions

class telegrampy.ext.commands.CommandError

Base exception for all command errors.

This inherits from telegrampy.TelegramException.

class telegrampy.ext.commands.CommandNotFound

Raised when a command is not found.

This inherits from telegrampy.ext.commands.CommandError.

class telegrampy.ext.commands.CommandRegistrationError(name: str, *, alias_conflict: bool = False)

Raised when a command cannot be registered, because it’s name is already being used.

This inherits from telegrampy.ext.commands.CommandError.

name

The command name that had a conflict.

Type:

str

alias_conflict

Whether the command name was an alias of the command being added.

Type:

bool

class telegrampy.ext.commands.ExtensionError

Base exception for extension related errors.

This inherits from telegrampy.ext.commands.CommandError.

class telegrampy.ext.commands.ExtensionAlreadyLoaded(name: str)

Raised when an extension is already loaded.

This inherits from telegrampy.ext.commands.ExtensionError.

class telegrampy.ext.commands.ExtensionNotLoaded(name: str)

Raised when an extension is not loaded.

This inherits from telegrampy.ext.commands.ExtensionError.

class telegrampy.ext.commands.NoEntryPointError(name: str)

Raised when an extension has no setup function.

This inherits from telegrampy.ext.commands.ExtensionError.

class telegrampy.ext.commands.ExtensionNotFound(name: str)

Raised when an extension is not found.

This inherits from telegrampy.ext.commands.ExtensionError.

class telegrampy.ext.commands.ExtensionFailed(name: str, original: Exception)

Raised when an extension fails.

This inherits from telegrampy.ext.commands.ExtensionError.

name

The extension that failed.

Type:

str

original

The original error that was raised.

Type:

Exception

class telegrampy.ext.commands.UserInputError

Base exception for errors that involve user input.

This inherits from telegrampy.ext.commands.CommandError.

class telegrampy.ext.commands.MissingRequiredArgument(param: Parameter)

Raised when a required argument is missing.

This inherits from telegrampy.ext.commands.UserInputError.

param

The argument that is missing.

Type:

inspect.Parameter

class telegrampy.ext.commands.BadArgument

Raised when a bad argument is given.

This inherits from telegrampy.ext.commands.UserInputError.

arg

The bad argument.

Type:

str

converter

The name of the converter that failed.

Type:

str

class telegrampy.ext.commands.ArgumentParsingError

Base exception for argument parsing errors.

This inherits from telegrampy.ext.commands.UserInputError.

class telegrampy.ext.commands.ExpectedClosingQuote(message: str | None = None)

Raised when the argument parser expects a closing quote but can’t find one.

This inherits from telegrampy.ext.commands.ArgumentParsingError.

class telegrampy.ext.commands.CheckFailure

Raised when a check fails.

This inherits from telegrampy.ext.commands.CheckFailure.

class telegrampy.ext.commands.NotOwner(message: str | None = None)

Raised when a user is not the owner of the bot.

This inherits from telegrampy.ext.commands.CheckFailure.

class telegrampy.ext.commands.PrivateChatOnly(message: str | None = None)

Raised when a command can only be used in private chats.

This inherits from telegrampy.ext.commands.CheckFailure.

class telegrampy.ext.commands.GroupOnly(message: str | None = None)

Raised when a command can only be used in groups.

This inherits from telegrampy.ext.commands.CheckFailure.

class telegrampy.ext.commands.CommandInvokeError(original: Exception)

Raised when a command fails.

This inherits from telegrampy.ext.commands.CommandError.

original

The original error that was raised.

Type:

Exception