API Reference

The following section outlines the API of steam.py’s command extension module.

Bot

class steam.ext.commands.Bot(*, command_prefix, help_command=<default_help_command>, **options)

Represents a Steam bot.

This class is a subclass of Client and as a result anything that you can do with Client you can do with Bot.

Parameters
  • command_prefix (CommandPrefixType) –

    What the message content must initially contain to have a command invoked.

    Can be any one of:

    Note

    The first prefix matched when getting context will always be returned, ensure that no prefix matches a longer prefix later in the sequence. e.g.

    bot = commands.Bot(command_prefix=("!", "!?"))
    # the "!?" prefix will never be matched as the previous
    # prefix would match the "!" at the start of the message
    

    This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

  • owner_id (int) – The Steam ID of the owner, this is converted to their 64 bit ID representation upon initialization.

  • owner_ids (set[int]) – The Steam IDs of the owners, these are converted to their 64 bit ID representations upon initialization.

  • case_insensitive (bool) – Whether or not commands should be invoke-able case insensitively.

property cogs: mappingproxy[str, steam.ext.commands.cog.Cog]

A read only mapping of any loaded cogs.

property extensions: mappingproxy[str, module]

A read only mapping of any loaded extensions.

property converters: mappingproxy[type, tuple['ConverterBase | BasicConverter[Any]', ...]]

A read only mapping of registered converters.

property help_command: HelpCommand | None

The bot’s help command.

await close()

Unloads any extensions and cogs, then closes the connection to Steam.

load_extension(extension)

Load an extension.

Parameters

extension (str | os.PathLike[str]) – The name of the extension to load.

Raises

ImportError – The extension is missing a setup function.

unload_extension(extension)

Unload an extension.

Parameters

extension (str | os.PathLike[str]) – The name of the extension to unload.

Raises

ModuleNotFoundError – The extension wasn’t found in the loaded extensions.

reload_extension(extension)

Atomically reload an extension. If any error occurs during the reload the extension will be reverted to its original state.

Parameters

extension (str | os.PathLike[str]) – The name of the extension to reload.

Raises

ModuleNotFoundError – The extension wasn’t found in the loaded extensions.

add_cog(cog)

Add a cog to the internal list.

Parameters

cog (steam.ext.commands.cog.Cog) – The cog to add.

remove_cog(cog)

Remove a cog from the internal list.

Parameters

cog (steam.ext.commands.cog.Cog) – The cog to remove.

add_listener(func, name=None)

Add a function from the internal listeners list.

Parameters
  • func (EventType) – The listener event to listen for.

  • name (str | None) – The name of the event to listen for. Defaults to func.__name__.

remove_listener(func, name=None)

Remove a function from the internal listeners list.

Parameters
  • func (EventType) – The listener to remove.

  • name (str | None) – The name of the event to remove. Defaults to func.__name__.

@listen(name=None)

A decorator that could be called. Register a function as a listener. Calls add_listener(). Similar to Cog.listener()

Parameters

name (str) – The name of the event to listen for. Will default to func.__name__.

Return type

Union[steam.client.E, collections.abc.Callable[steam.client.E, (~E,)]]

@check(predicate=None)

A decorator that could be called. Register a global check for all commands. This is similar to commands.check().

Return type

Union[steam.ext.commands.bot.Check, steam.ext.commands.commands.CHR]

add_check(predicate)

Add a global check to the bot.

Parameters

predicate (steam.ext.commands.commands.CheckReturnType) – The check to add.

remove_check(predicate)

Remove a global check from the bot.

Parameters

predicate (steam.ext.commands.commands.CheckReturnType) – The check to remove.

await can_run(ctx)

Whether or not the context’s command can be ran.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

Return type

bool

@before_invoke(coro=None)

A decorator that could be called. Register a coroutine to be ran before any arguments are parsed.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

@after_invoke(coro=None)

A decorator that could be called. Register a coroutine to be ran after a command has been invoked.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

await process_commands(message)

A method to process commands for a message.

Warning

This is vital for commands to function. If you have an on_message() as a registered event using event() commands will not be dispatched. Remember to add a call to this in your on_message() event.

Parameters

message (Message) – The message to get the context for.

add_command(command)

Add a command to the internal commands list.

Parameters

command (steam.ext.commands.commands.Command) – The command to register.

property all_commands: list[steam.ext.commands.commands.Command]

A list of the loaded commands.

await change_presence(*, game=None, games=None, state=None, ui_mode=None, flags=None, force_kick=False)

Set your status.

Parameters
  • game (Optional[steam.Game]) – A games to set your status as.

  • games (Optional[list[steam.Game]]) – A list of games to set your status to.

  • state (Optional[steam.enums.PersonaState]) –

    The state to show your account as.

    Warning

    Setting your status to Offline, will stop you receiving persona state updates and by extension on_user_update() will stop being dispatched.

  • ui_mode (Optional[steam.enums.UIMode]) – The UI mode to set your status to.

  • flags (Optional[steam.enums.PersonaStateFlag]) – The flags to update your account with.

  • force_kick (bool) – Whether or not to forcefully kick any other playing sessions.

property children: list[Self]

The commands children.

Return type

list[Command]

property clans: list[Clan]

A list of all the clans the connected client is in.

clear()

Clears the internal state of the bot. After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False. This also clears the internal cache.

await code()

Get the current steam guard code.

Warning

This function will wait for a Steam guard code using input() in an executor if no shared_secret is passed to run() or start(), which blocks exiting until one is entered.

Return type

str

@command(callback=None, *, name=None, cls=None, **attrs)

A decorator that could be called. A decorator that invokes command() and adds the created Command to the internal command list.

Parameters
  • name (str | None) – The name of the command. Will default to callback.__name__.

  • cls (type[Command]) – The class to construct the command from. Defaults to Command.

  • attrs (Any) – The parameters to pass to the command’s __init__.

Returns

The created command.

Return type

Callable[[CallT], C] | C

property commands: set[steam.ext.commands.commands.Command]

A set of the loaded commands without duplicates.

await connect()

Initialize a connection to a Steam CM after logging in.

@event(coro=None)

A decorator that could be called. Register an event to listen to.

The events must be a coroutine, if not, TypeError is raised.

Usage:

@client.event
async def on_ready():
    print("Ready!")
Raises

TypeError – The function passed is not a coroutine.

Return type

Union[collections.abc.Callable[steam.client.E, (~E,)], steam.client.E]

await fetch_clan(id)

Fetches a clan from the websocket with a matching ID or None if the clan was not found.

Parameters

id (utils.Intable) – The ID of the clan, can be an SteamID.id64, SteamID.id, SteamID.id2 or an SteamID.id3.

Return type

Optional[steam.Clan]

await fetch_clan_named(name)

Fetches a clan from https://steamcommunity.com with a matching name or None if the clan was not found.

Parameters

name (str) – The name of the Steam clan.

Return type

Optional[steam.Clan]

await fetch_game(id)

Fetch a game from its ID or None if the game was not found.

Parameters

id (Union[int, steam.Game]) – The app id of the game or a Game instance.

Return type

Optional[steam.FetchedGame]

await fetch_price(name, game, currency=None)

Fetch the PriceOverview for an item.

Parameters
  • name (str) – The name of the item.

  • game (steam.Game) – The game the item is from.

  • currency (Optional[int]) – The currency to fetch the price in.

Return type

steam.PriceOverview

await fetch_server(*, id=None, ip=None, port=None)

Fetch a GameServer from its ip and port or its SteamID or None if fetching the server failed.

Parameters
  • ip (str) – The ip of the server.

  • port (Optional[int]) – The port of the server.

  • id (utils.Intable | None) – The ID of the game server, can be an SteamID.id64, SteamID.id2 or an SteamID.id3. If this is passed, it makes a call to the master server to fetch its ip and port.

Note

Passing an ip, port and id to this function will raise an TypeError.

Return type

Optional[steam.GameServer]

await fetch_servers(query, limit=100)

Query game servers.

Parameters
  • query (steam.Query) – The query to match servers with.

  • limit (int) – The maximum amount of servers to return.

Return type

list[steam.GameServer]

await fetch_trade(id)

Fetches a trade with a matching ID or None if the trade was not found.

Parameters

id (int) – The ID of the trade to search for from the API.

Return type

Optional[steam.TradeOffer]

await fetch_user(id)

Fetches a user with a matching ID or None if the user was not found.

Parameters

id (utils.Intable) – The ID of the user, can be an SteamID.id64, SteamID.id, SteamID.id2 or an SteamID.id3.

Return type

Optional[steam.User]

await fetch_user_named(name)

Fetches a user from https://steamcommunity.com from their community URL name.

Parameters

name (str) – The name of the user after https://steamcommunity.com/id

Return type

Optional[steam.User]

await fetch_users(*ids)

Fetches a list of User or None if the user was not found, from their IDs.

Note

The User objects returned are unlikely to retain the order they were originally in.

Parameters

ids (utils.Intable) – The user’s IDs.

Return type

list[Optional[steam.User]]

get_clan(id)

Get a clan from cache with a matching ID or None if the group was not found.

Parameters

id (utils.Intable) – The ID of the clan, can be an SteamID.id64, SteamID.id, SteamID.id2 or an SteamID.id3.

Return type

Optional[steam.Clan]

get_command(name)

Get a command.

Parameters

name (str) – The name of the command.

Returns

The found command or None.

Return type

Command | None

get_game(id)

Creates a stateful game from its ID.

Parameters

id (Union[int, steam.Game]) – The app id of the game or a Game instance.

Return type

steam.StatefulGame

get_group(id)

Get a group from cache with a matching ID or None if the group was not found.

Parameters

id (utils.Intable) – The ID of the group, can be an SteamID.id64, SteamID.id, SteamID.id2 or an SteamID.id3.

Return type

Optional[steam.Group]

get_trade(id)

Get a trade from cache with a matching ID or None if the trade was not found.

Parameters

id (int) – The id of the trade to search for from the cache.

Return type

Optional[steam.TradeOffer]

get_user(id)

Returns a user from cache with a matching ID or None if the user was not found.

Parameters

id (utils.Intable) – The ID of the user, can be an SteamID.id64, SteamID.id, SteamID.id2 or an SteamID.id3.

Return type

Optional[steam.User]

@group(callback=None, *, name=None, cls=None, **attrs)

A decorator that could be called. A decorator that invokes group() and adds the created Group to the internal command list.

Parameters
  • name (str | None) – The name of the command. Will default to callback.__name__.

  • cls (type[Group]) – The class to construct the command from. Defaults to Group.

  • attrs (Any) – The parameters to pass to the command’s __init__.

Returns

The created group command.

Return type

Callable[[CallT], G] | G

property groups: list[Group]

A list of all the groups the connected client is in.

await invoke(ctx)

Invoke a command. This will parse arguments, checks, cooldowns etc. correctly.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

is_closed()

Indicates if connection is closed to the API or CMs.

Return type

bool

is_ready()

Specifies if the client’s internal cache is ready for use.

Return type

bool

property latency: float

Measures latency between a heartbeat send and the heartbeat interval in seconds.

await login(username, password, *, shared_secret=None)

Login a Steam account and the Steam API with the specified credentials.

Parameters
  • username (str) – The username of the user’s account.

  • password (str) – The password of the user’s account.

  • shared_secret (Optional[str]) – The shared_secret of the desired Steam account, used to generate the 2FA code for login. If None is passed, the code will need to be inputted by the user via code().

Raises
await on_announcement_create(announcement)

Called when an announcement in a clan is created.

Parameters

announcement (steam.event.Announcement) – The announcement that was created.

await on_clan_invite_decline(invite)

Called when the client/invitee declines an invite to join a Clan.

Parameters

invite (steam.ClanInvite) – The invite that was declined.

await on_clan_join(clan)

Called when the client joins a new clan.

Parameters

clan (steam.Clan) – The joined clan.

await on_clan_leave(clan)

Called when the client leaves a clan.

Parameters

clan (steam.Clan) – The left clan.

await on_clan_update(before, after)

Called when a clan is updated, due to one or more of the following attributes changing:

Parameters
  • before (steam.Clan) – The clan’s state before it was updated.

  • after (steam.Clan) – The clan’s state now.

await on_event_create(event)

Called when an event in a clan is created.

Parameters

event (steam.event.Event) – The event that was created.

await on_group_join(group)

Called when the client joins a new group.

Parameters

group (steam.Group) – The joined group.

await on_group_leave(group)

Called when the client leaves a group.

Parameters

group (steam.Group) – The left group.

await on_group_update(before, after)

Called when a group is updated.

Parameters
  • before (steam.Group) – The group’s state before it was updated.

  • after (steam.Group) – The group’s state now.

await on_user_invite_decline(invite)

Called when the client/invitee declines an invite from/to a User to become a friend.

Parameters

invite (steam.UserInvite) – The invite that was declined.

await on_user_remove(user)

Called when you or the user remove each other from your friends lists.

Parameters

user (steam.User) – The user who was removed.

remove_command(name)

Remove a command from the internal commands list.

Parameters

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

Returns

The removed command or None if the command was not found.

Return type

Command | None

run(*args, **kwargs)

A blocking call that abstracts away the event loop initialisation from you.

It is not recommended to subclass this method, it is normally favourable to subclass start() as it is a coroutine.

Note

This takes the same arguments as start().

await start(username, password, *, shared_secret=None, identity_secret=None)

A shorthand coroutine for login() and connect().

If no shared_secret is passed, you will have to manually enter a Steam guard code using code().

Parameters
  • username (str) – The username of the account to login to.

  • password (str) – The password of the account to login to.

  • shared_secret (Optional[str]) – The shared secret for the account to login to.

  • identity_secret (Optional[str]) – The identity secret for the account to login to.

async for ... in trade_history(limit=100, before=None, after=None)

An AsyncIterator for accessing a steam.ClientUser’s steam.TradeOffer objects.

Examples

Usage:

async for trade in client.trade_history(limit=10):
    items = [getattr(item, "name", str(item.asset_id)) for item in trade.items_to_receive]
    items = ", ".join(items) or "Nothing"
    print("Partner:", trade.partner)
    print("Sent:", items)

Flattening into a list:

trades = await client.trade_history(limit=50).flatten()
# trades is now a list of TradeOffer

All parameters are optional.

Parameters
  • limit (Optional[int]) – The maximum number of trades to search through. Default is 100. Setting this to None will fetch all of the user’s trades, but this will be a very slow operation.

  • before (Optional[datetime.datetime]) – A time to search for trades before.

  • after (Optional[datetime.datetime]) – A time to search for trades after.

Yields

TradeOffer

await trade_url(generate_new=False)

Fetches this account’s trade url.

Parameters

generate_new (bool) – Whether or not to generate a new trade token, defaults to False.

Return type

str

property trades: list[TradeOffer]

A list of all the trades the connected client can see.

property user: ClientUser

Represents the connected client. None if not logged in.

property users: list[User]

A list of all the users the connected client can see.

await wait_until_ready()

Waits until the client’s internal cache is all ready.

await get_context(message, *, cls=<class 'steam.ext.commands.context.Context'>)

Get the context for a certain message.

Parameters
  • message (Message) – The message to get the context for.

  • cls (type[C]) – The class to construct the context with, this is the type of the return type

Return type

steam.ext.commands.bot.C

await get_prefix(message)

Get the command prefix for a certain message.

Parameters

message (Message) – The message to get the prefix for.

Return type

Optional[str]

get_cog(name)

Get a loaded cog or None.

Parameters

name (str) – The name of the cog.

Return type

Optional[steam.ext.commands.cog.Cog]

wait_for(**kwds)

Helper for @overload to raise when called.

steam.ext.commands.when_mentioned(bot, message)

A callable that implements a command prefix equivalent to being mentioned. This is meant to be passed into the Bot.command_prefix attribute.

Return type

list[str]

steam.ext.commands.when_mentioned_or(*prefixes)

A callable that implements when mentioned or other prefixes provided. These are meant to be passed into the Bot.command_prefix attribute.

Example

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"))

Note

This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:

async def get_prefix(bot: commands.Bot, message: steam.Message) -> list[str]:
    extras = await prefixes_for(message.clan)  # a user defined function that returns a list
    return commands.when_mentioned_or(*extras)(bot, message)

See also

when_mentioned()

Return type

collections.abc.Callable[steam.Bot, steam.abc.Message, (list[str],)]

Event Reference

These events function similar to the regular events, and all of the events there are also applicable to Bot. These are however unique to the commands extension module.

await steam.ext.commands.Bot.on_command_error(self, ctx, error)

The default command error handler provided by the bot. This only fires if you do not specify any listeners for command error.

Parameters
  • ctx (commands.Context) – The invocation context where the error happened.

  • error (Exception) – The error that was raised.

await steam.ext.commands.Bot.on_command(self, ctx)

A method that is called every time a command is dispatched.

Parameters

ctx (commands.Context) – The invocation context.

await steam.ext.commands.Bot.on_command_completion(self, ctx)

A method that is called every time a command is dispatched and completed without error.

Parameters

ctx (commands.Context) – The invocation context.

Enumerations

class steam.ext.commands.BucketType(value)

A enumeration that handles cooldowns.

Each attribute operates on a per x basis. So User operates on a per User basis.

Default = 0

The default BucketType this operates on a global basis.

User = 1

The BucketType for a steam.User.

Member = 2

The BucketType for a steam.User and a steam.Clan.

Group = 3

The BucketType for a steam.User in a steam.Clan / steam.Group.

Clan = 4

The BucketType for a steam.Clan.

Role = 5

The BucketType for a steam.Role.

Channel = 6

The BucketType for a steam.Channel.

Admin = 7

The BucketType for a steam.Clan’s steam.Clan.admins.

get_bucket(ctx)

Get a bucket key for a message or context.

Parameters

ctx (Message | Messageable) – The message or context to get the bucket for.

Return type

Union[int, tuple[int]]

Commands

@steam.ext.commands.command(callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]) steam.ext.commands.commands.Command[steam.ext.commands.commands.P]
@steam.ext.commands.command(callback: None) Callable[[steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]], steam.ext.commands.commands.Command[steam.ext.commands.commands.P]]
@steam.ext.commands.command(*, name: str | None = None, cls: type[C] | None = None, help: str | None = '...', brief: str | None = '...', usage: str | None = '...', description: str | None = '...', aliases: Iterable[str] | None = '...', checks: list[steam.ext.commands.commands.CheckReturnType] = '...', cooldown: list[steam.ext.commands.cooldown.Cooldown] = '...', special_converters: list[type['ConverterBase | BasicConverter[Any]']] = '...', cog: Cog | None = '...', parent: Command | None = '...', enabled: bool = '...', hidden: bool = '...', case_insensitive: bool = '...') Callable[[steam.ext.commands.commands.CallbackType], steam.ext.commands.commands.Command]

A decorator that could be called. A decorator that turns a coroutine function into a Command.

Parameters
  • name – The name of the command. Will default to callback.__name__.

  • cls (type[Command]) – The class to construct the command from. Defaults to Command.

  • attrs – The attributes to pass to the command’s __init__.

Return type

The created command.

@steam.ext.commands.group(callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]) steam.ext.commands.commands.Group[steam.ext.commands.commands.P]
@steam.ext.commands.group(callback: None) Callable[[steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]], steam.ext.commands.commands.Group[steam.ext.commands.commands.P]]
@steam.ext.commands.group(*, name: str | None = None, cls: type[G] | None = None, help: str | None = '...', brief: str | None = '...', usage: str | None = '...', description: str | None = '...', aliases: Iterable[str] | None = '...', checks: list[steam.ext.commands.commands.CheckReturnType] = '...', cooldown: list[steam.ext.commands.cooldown.Cooldown] = '...', special_converters: list[type['ConverterBase | BasicConverter[Any]']] = '...', cog: Cog | None = '...', parent: Command | None = '...', enabled: bool = '...', hidden: bool = '...', case_insensitive: bool = '...') Callable[[steam.ext.commands.commands.CallT], steam.ext.commands.commands.G]

A decorator that could be called. A decorator that turns a coroutine function into a Group.

Parameters
  • name – The name of the command. Will default to callback.__name__.

  • cls (type[Group]) – The class to construct the command from. Defaults to Group.

  • attrs – The attributes to pass to the command’s __init__.

Return type

The created group command.

@steam.ext.commands.check

A decorator that registers a function that could be a coroutine as a check to a command.

They should take a singular argument representing the Context for the message.

Examples

def is_mod(ctx: commands.Context) -> bool:
    return ctx.clan and ctx.author in ctx.clan.mods

@commands.check(is_mod)
@bot.command
async def kick(ctx: commands.Context, user: steam.User) -> None:
    ...

This will raise an steam.ext.commands.CheckFailure if the user is not an a mod in the clan.

steam.ext.commands.predicate

The registered check, this will always be a coroutine function even if the original check wasn’t.

@steam.ext.commands.cooldown(rate, per, type=BucketType.Default)

Give a Command’s a cooldown.

Parameters
  • rate (int) – The amount of times a command can be executed before being put on cooldown.

  • per (float) – The amount of time to wait between cooldowns.

  • type (steam.ext.commands.cooldown.BucketType) – The bucket that the cooldown applies to.

Examples

Usage

@bot.command
@commands.cooldown(rate=1, per=10, commands.BucketType.User)
async def once_every_ten_seconds(ctx: commands.Context) -> None:
    ...  # this can only be invoked a user every ten seconds.
@steam.ext.commands.is_owner(command: None = None) steam.ext.commands.commands.MCD
@steam.ext.commands.is_owner(command: steam.ext.commands.commands.MCD) steam.ext.commands.commands.MCD

A decorator that could be called. A decorator that will only allow the bot’s owner(s) to invoke the command.

Warning

This relies on owner_id or owner_ids to be set to function if they are not no one will be able to use these commands.

class steam.ext.commands.Command(*args, **kwargs)

A class to represent a command.

name

The command’s name.

Type

str

help

The command’s help docstring.

Type

Optional[str]

checks

A list of the command’s checks.

Type

list[steam.ext.commands.commands.CheckReturnType]

cooldown

The command’s cooldowns.

Type

list[steam.ext.commands.cooldown.Cooldown[typing.Any]]

special_converters

A list of the command’s special converters as registered by steam.ext.commands.Converter.register().

Type

list[type[steam.ext.commands.converters.Converter[typing.Any]]]

enabled

Whether or not the command is enabled.

Type

bool

cog

The command’s cog.

Type

Optional[Union[steam.ext.commands.cog.Cog, steam.Bot]]

parent

The command’s parent.

Type

Optional[steam.GroupMixin]

description

The command’s description.

Type

str

hidden

Whether or not the command is hidden.

Type

bool

aliases

The command’s aliases.

Type

Iterable[str]

params

The command’s parameters.

Type

dict[str, inspect.Parameter]

property callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]

The internal callback the command holds.

clean_params

The command’s parameters without "self" and "ctx".

property qualified_name: str

The full name of the command, this takes into account subcommands etc.

property parents: list[Self]

The command’s parents.

Return type

list[Command]

await __call__(ctx, *args, **kwargs)

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments (excluding the parameter “self” in a cog context) and types to this function.

@error(coro: None = None) Callable[[steam.ext.commands.commands.Err], steam.ext.commands.commands.Err]
@error(coro: steam.ext.commands.commands.Err) steam.ext.commands.commands.Err

A decorator that could be called. Register a coroutine function to handle a commands on_error functionality similarly to steam.ext.commands.Bot.on_command_error().

Example:

@bot.command
async def raise_an_error(ctx: commands.Context) -> None:
    raise Exception("oh no an error")


@raise_an_error.error
async def on_error(ctx: commands.Context, error: Exception) -> None:
    await ctx.send(f"{ctx.command.name} raised an exception {error!r}")
Return type

Union[collections.abc.Callable[steam.ext.commands.commands.Err, (~Err,)], steam.ext.commands.commands.Err]

@before_invoke(coro: None = None) Callable[[steam.ext.commands.commands.InvokeT], steam.ext.commands.commands.InvokeT]
@before_invoke(coro: steam.ext.commands.commands.InvokeT) steam.ext.commands.commands.InvokeT

A decorator that could be called. Register a coroutine function to be ran before any arguments are parsed.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

@after_invoke(coro: None = None) Callable[[steam.ext.commands.commands.InvokeT], steam.ext.commands.commands.InvokeT]
@after_invoke(coro: steam.ext.commands.commands.InvokeT) steam.ext.commands.commands.InvokeT

A decorator that could be called. Register a coroutine function to be ran after the command has been invoked.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

await invoke(ctx)

Invoke the callback the command holds.

Parameters

ctx (Context) – The invocation context.

await can_run(ctx)

Whether or not the command can be ran.

Parameters

ctx (Context) – The invocation context.

Return type

bool

class steam.ext.commands.Group(*args, **kwargs)
await __call__(ctx, *args, **kwargs)

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments (excluding the parameter “self” in a cog context) and types to this function.

add_command(command)

Add a command to the internal commands list.

Parameters

command (steam.Command) – The command to register.

@after_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran after the command has been invoked.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

property all_commands: list[steam.Command]

A list of the loaded commands.

@before_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran before any arguments are parsed.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

property callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]

The internal callback the command holds.

await can_run(ctx)

Whether or not the command can be ran.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

Return type

bool

property children: list[Self]

The commands children.

Return type

list[Command]

clean_params

The command’s parameters without "self" and "ctx".

@command(callback=None, *, name=None, cls=None, **attrs)

A decorator that could be called. A decorator that invokes command() and adds the created Command to the internal command list.

Parameters
  • name (str | None) – The name of the command. Will default to callback.__name__.

  • cls (type[Command]) – The class to construct the command from. Defaults to Command.

  • attrs (Any) – The parameters to pass to the command’s __init__.

Returns

The created command.

Return type

Union[steam.Command, collections.abc.Callable[steam.ext.commands.commands.CallbackType, (<class ‘steam.Command’>,)], collections.abc.Callable[steam.ext.commands.commands.CallT, (~C,)]]

property commands: set[steam.Command]

A set of the loaded commands without duplicates.

@error(coro=None)

A decorator that could be called. Register a coroutine function to handle a commands on_error functionality similarly to steam.ext.commands.Bot.on_command_error().

Example:

@bot.command
async def raise_an_error(ctx: commands.Context) -> None:
    raise Exception("oh no an error")


@raise_an_error.error
async def on_error(ctx: commands.Context, error: Exception) -> None:
    await ctx.send(f"{ctx.command.name} raised an exception {error!r}")
Return type

Union[collections.abc.Callable[steam.ext.commands.commands.Err, (~Err,)], steam.ext.commands.commands.Err]

get_command(name)

Get a command.

Parameters

name (str) – The name of the command.

Returns

The found command or None.

Return type

Optional[steam.Command]

@group(callback=None, *, name=None, cls=None, **attrs)

A decorator that could be called. A decorator that invokes group() and adds the created Group to the internal command list.

Parameters
  • name (str | None) – The name of the command. Will default to callback.__name__.

  • cls (type[Group]) – The class to construct the command from. Defaults to Group.

  • attrs (Any) – The parameters to pass to the command’s __init__.

Returns

The created group command.

Return type

Union[steam.Group, collections.abc.Callable[steam.ext.commands.commands.CallbackType, (<class ‘steam.Group’>,)], collections.abc.Callable[steam.ext.commands.commands.CallT, (~G,)]]

property parents: list[Self]

The command’s parents.

Return type

list[Command]

property qualified_name: str

The full name of the command, this takes into account subcommands etc.

remove_command(name)

Remove a command from the internal commands list.

Parameters

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

Returns

The removed command or None if the command was not found.

Return type

Optional[steam.Command]

await invoke(ctx)

Invoke the callback the command holds.

Parameters

ctx (Context) – The invocation context.

Command Parsing

steam.py offers multiple ways to parse commands.

Positional or Keyword

  • Values are passed to matching parameter based on their position.

Example:

@bot.command()
async def command(ctx, argument_1, argument_2):
    ...

An invocation of !command some string would pass "some" to argument_1 and "string" to argument_2.

Variadic Positional

  • Values are passed as a tuple of positional arguments that can be indefinitely long. This corresponds to an *args parameter in a function definition.

Example:

@bot.command()
async def command(ctx, argument_1, *arguments):
    ...

An invocation of !command some longer string would pass "some" to argument_1 and ("longer", "string") to arguments.

Note

This has to be the last parameter in a function definition.

Keyword only

  • Any value is passed from the rest of the command to the first keyword only argument.

Example:

@bot.command()
async def command(ctx, argument_1, *, argument_2):
    ...

An invocation of !command some longer string would pass "some" to argument_1 and "longer string" to argument_2.

Note

This has to be the last parameter in a function definition.

Variadic Keyword

  • Values are passed as a dict of keyword arguments that can be indefinitely long. This corresponds to a **kwargs parameter in a function definition.

Example:

@bot.command()
async def command(ctx, argument_1, **arguments):
    ...

An invocation of !command some string=long would pass "some" to argument_1 and {"string": "long"} to **arguments.

Note

This has to be the last parameter in a function definition.

Warning

Type-hinting this function does not work like it strictly should, it should be done using **kwargs: value_type whereas with steam.py it is **kwargs: dict[key_type, value_type] the rational behind this decision was to allow for non-string keys e.g. !ban user="reason to ban".

Help Commands

class steam.ext.commands.HelpCommand(*args, **kwargs)

The base implementation of the help command.

context: steam.ext.commands.context.Context
await command_callback(ctx, *, content=None)

The actual implementation of the help command.

This method should not directly subclassed instead you should change the behaviour through the methods that actually get dispatched:

get_bot_mapping()

Generate a mapping of the bot’s commands. It’s not normally necessary to subclass this. This is passed to send_help().

Return type

Mapping[Optional[str], list[steam.Command]]

abstractmethod await send_help(mapping)

Send the basic help message for the bot’s command.

Parameters

mapping (Mapping[str | None, list[commands.Command]]) – The mapping from get_bot_mapping().

abstractmethod await send_cog_help(cog)

The method called with a cog is passed as an argument.

Note

Cog names are case-sensitive.

Parameters

cog (commands.Cog) – The cog that was passed as an argument.

abstractmethod await send_command_help(command)

The method called when a normal command is passed as an argument.

Parameters

command (commands.Command) – The command that was passed as an argument.

abstractmethod await send_group_help(command)

The method called when a group command is passed as an argument.

Parameters

command (commands.Group) – The command that was passed as an argument.

abstractmethod await command_not_found(command)

The default implementation for when a command isn’t found.

This by default sends “The command {command} was not found.”

Parameters

command (str) – The command that was not found.

await on_error(ctx, error)

The default error handler for the help command. This performs the functionality as steam.ext.commands.Bot.on_command_error().

Parameters
await cog_command_error(ctx, error)

The default error handler for the help command. This performs the functionality as steam.ext.commands.Bot.on_command_error().

Parameters
await __call__(ctx, *args, **kwargs)

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments (excluding the parameter “self” in a cog context) and types to this function.

@after_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran after the command has been invoked.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

@before_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran before any arguments are parsed.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

property callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]

The internal callback the command holds.

await can_run(ctx)

Whether or not the command can be ran.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

Return type

bool

clean_params

The command’s parameters without "self" and "ctx".

@error(coro=None)

A decorator that could be called. Register a coroutine function to handle a commands on_error functionality similarly to steam.ext.commands.Bot.on_command_error().

Example:

@bot.command
async def raise_an_error(ctx: commands.Context) -> None:
    raise Exception("oh no an error")


@raise_an_error.error
async def on_error(ctx: commands.Context, error: Exception) -> None:
    await ctx.send(f"{ctx.command.name} raised an exception {error!r}")
Return type

Union[collections.abc.Callable[steam.ext.commands.commands.Err, (~Err,)], steam.ext.commands.commands.Err]

await invoke(ctx)

Invoke the callback the command holds.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

property parents: list[Self]

The command’s parents.

Return type

list[Command]

property qualified_name: str

The full name of the command, this takes into account subcommands etc.

class steam.ext.commands.DefaultHelpCommand(*args, **kwargs)

The default implementation of the help command.

await send_help(mapping)

Send the basic help message for the bot’s command.

Parameters

mapping (Mapping[str | None, list[commands.Command]]) – The mapping from get_bot_mapping().

await send_cog_help(cog)

The method called with a cog is passed as an argument.

Note

Cog names are case-sensitive.

Parameters

cog (commands.Cog) – The cog that was passed as an argument.

await send_command_help(command)

The method called when a normal command is passed as an argument.

Parameters

command (commands.Command) – The command that was passed as an argument.

await send_group_help(command)

The method called when a group command is passed as an argument.

Parameters

command (commands.Group) – The command that was passed as an argument.

await command_not_found(command)

The default implementation for when a command isn’t found.

This by default sends “The command {command} was not found.”

Parameters

command (str) – The command that was not found.

await __call__(ctx, *args, **kwargs)

Calls the internal callback that the command holds.

Note

This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments (excluding the parameter “self” in a cog context) and types to this function.

@after_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran after the command has been invoked.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

@before_invoke(coro=None)

A decorator that could be called. Register a coroutine function to be ran before any arguments are parsed.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.InvokeT, (~InvokeT,)], steam.ext.commands.commands.InvokeT]

property callback: steam.ext.commands.commands.CallbackType[steam.ext.commands.commands.P]

The internal callback the command holds.

await can_run(ctx)

Whether or not the command can be ran.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

Return type

bool

clean_params

The command’s parameters without "self" and "ctx".

await cog_command_error(ctx, error)

The default error handler for the help command. This performs the functionality as steam.ext.commands.Bot.on_command_error().

Parameters
await command_callback(ctx, *, content=None)

The actual implementation of the help command.

This method should not directly subclassed instead you should change the behaviour through the methods that actually get dispatched:

@error(coro=None)

A decorator that could be called. Register a coroutine function to handle a commands on_error functionality similarly to steam.ext.commands.Bot.on_command_error().

Example:

@bot.command
async def raise_an_error(ctx: commands.Context) -> None:
    raise Exception("oh no an error")


@raise_an_error.error
async def on_error(ctx: commands.Context, error: Exception) -> None:
    await ctx.send(f"{ctx.command.name} raised an exception {error!r}")
Return type

Union[collections.abc.Callable[steam.ext.commands.commands.Err, (~Err,)], steam.ext.commands.commands.Err]

get_bot_mapping()

Generate a mapping of the bot’s commands. It’s not normally necessary to subclass this. This is passed to send_help().

Return type

Mapping[Optional[str], list[steam.Command]]

await invoke(ctx)

Invoke the callback the command holds.

Parameters

ctx (steam.ext.commands.context.Context) – The invocation context.

await on_error(ctx, error)

The default error handler for the help command. This performs the functionality as steam.ext.commands.Bot.on_command_error().

Parameters
property parents: list[Self]

The command’s parents.

Return type

list[Command]

property qualified_name: str

The full name of the command, this takes into account subcommands etc.

Cogs

class steam.ext.commands.Cog

A class from which Cogs can be created. These are used to separate commands and listeners into separate files.

qualified_name

The name of the cog. Can be set in a subclass e.g.

class MyCog(commands.Cog, name="SpecialCogName"):
    ...

Defaults to Cog.__name__.

Type

str

command_attrs

Attributes to pass to every command registered in the cog. Can be set in subclass e.g.

class MyBrokenCog(commands.Cog, command_attrs=dict(enabled=False)):
    # all the commands by default would be disabled

    @commands.command()
    async def broken(self, ctx):  # disabled
        ...

    @commands.command(enabled=True)
    async def working(self, ctx):  # enabled
        ...
Type

dict[str, typing.Any]

description

The cleaned up doc-string for the cog.

Type

Optional[str]

property commands: set[steam.Command]

A set of the cog’s commands.

property listeners: list[tuple[str, EventType]]

A list of tuples of the events registered with the format (name, listener)

classmethod @listener(coro: E) E
classmethod @listener(name: str | None = None) Callable[[E], E]

A decorator that could be called. Register a coroutine function as a listener. Similar to listen().

Parameters

name (str) – The name of the event to listen for. Defaults to func.__name__.

Return type

Union[steam.client.E, collections.abc.Callable[steam.client.E, (~E,)]]

await cog_command_error(ctx, error)

A special method that is called when an error is dispatched inside this cog. This is similar to on_command_error() except it only applies to the commands inside this cog.

Parameters
await cog_check(ctx)

This function could be a coroutine. A special method that registers as a commands.check() for every command and subcommand in this cog. This should return a boolean result.

Parameters

ctx (commands.Context) – The invocation context.

Return type

bool

await bot_check(ctx)

This function could be a coroutine. A special method that registers as a commands.Bot.check() globally. This should return a boolean result.

Parameters

ctx (commands.Context) – The invocation context.

Return type

bool

cog_unload()

A special method that is called when the cog gets removed.

This is called before teardown().

Context

class steam.ext.commands.Context(**attrs)

Represents the context of a command.

message

The message the context was generated from.

Type

steam.abc.Message

prefix

The prefix of the message the context was generated from

Type

Optional[str]

author

The author of the message.

Type

steam.User

channel

The channel the message was sent in.

Type

steam.abc.Channel[steam.abc.Message]

clan

The clan the message was sent in None if the message wasn’t sent in a clan.

Type

Optional[steam.Clan]

group

The group the message was sent in None if the message wasn’t sent in a group.

Type

Optional[steam.Group]

bot

The bot instance.

Type

steam.Bot

command

The command the context is attached to.

Type

Optional[steam.Command]

cog

The cog the command is in.

Type

Optional[steam.Cog]

await invoke()

A shortcut method that invokes the current context using invoke().

Equivalent to

await ctx.command.invoke(ctx)
history(limit=100, before=None, after=None)

A shortcut method that gets the current channel’s history.

Equivalent to

ctx.channel.history(**kwargs)
Return type

steam.AsyncIterator[steam.abc.Message]

property valid: bool

Whether or not the context could be invoked.

await send(content=None, image=None)

Send a message to a certain destination.

Parameters
  • content (Optional[Any]) – The content of the message to send.

  • image (Optional[steam.Image]) – The image to send to the user.

Note

Anything as passed to content is implicitly cast to a str.

Raises
Returns

The sent message, only applicable if content is passed.

Return type

Optional[steam.abc.M_co]

Cooldowns

Attributes
Methods
class steam.ext.commands.Cooldown(rate, per, bucket)

The class that holds a command’s cooldown.

bucket: steam.ext.commands.cooldown.BucketType
reset()

Reset the command’s cooldown.

get_retry_after(bucket, now)

Get the retry after for a command.

Parameters
  • bucket (steam.ext.commands.cooldown.T_Bucket) – The bucket to find in the cache.

  • now (float) – The UNIX timestamp to find times after.

Return type

float

Converters

@steam.ext.commands.converter_for

The recommended way to mark a function converter as such.

Note

All of the converters marked with this decorator or derived from Converter can be accessed via converters.

Examples

@commands.converter_for(commands.Command)  # this is the type hint used
def command_converter(argument: str) -> commands.Command:
    return bot.get_command(argument)

# then later
@bot.command
async def source(ctx, command: commands.Command):  # this then calls command_converter on invocation.
    ...
Parameters

converter_for (T) – The type annotation the decorated converter should convert for.

steam.ext.commands.converter_for

The class that the converter can be type-hinted to to.

Type

T

class steam.ext.commands.Converter

A custom typing.Protocol from which converters can be derived.

Note

All of the converters derived from Converter or marked with the converter_for() decorator can be accessed via converters.

Some custom dataclasses from this library can be type-hinted without the need for a custom converter:

Examples

Builtin:

@bot.command
async def command(ctx, user: steam.User):
    ...  # this will tell the parser to convert user from a str to a steam.User object.

# invoked as
# !command 76561198248053954
# or !command Gobot1234

A custom converter:

class ImageConverter(commands.Converter[steam.Image]):  # the annotation to typehint to
    async def convert(self, ctx: commands.Context, argument: str) -> steam.Image:
        async with aiohttp.ClientSession() as session:
            async with session.get(argument) as r:
                image_bytes = BytesIO(await r.read())
        try:
            return steam.Image(image_bytes)
        except (TypeError, ValueError):  # failed to convert to an image
            raise commands.BadArgument("Cannot convert image") from None


# then later
@bot.command
async def set_avatar(ctx: commands.Context, avatar: steam.Image) -> None:
    await bot.user.edit(avatar=avatar)
    await ctx.send("👌")


# invoked as
# !set_avatar https://my_image_url.com
classmethod @register(command: None = None) Callable[[MC], MC]
classmethod @register(command: MC) MC

A decorator that could be called. Register a converter to a specific command.

Examples

class CustomUserConverter(commands.Converter[steam.User]):
    async def convert(self, ctx: commands.Context, argument: str) -> steam.User:
        ...

@bot.command
@CustomUserConverter.register
async def is_cool(ctx, user: steam.User):
    ...

In this example is_cool’s user parameter would be registered to the CustomUserConverter rather than the global UserConverter.

Return type

Union[collections.abc.Callable[steam.ext.commands.commands.MC, (~MC,)], steam.ext.commands.commands.MC]

class property converter_for: steam.ext.commands.converters.T_co

The class that the converter can be type-hinted to to.

class steam.ext.commands.UserConverter

The converter that is used when the type-hint passed is User.

Lookup is in the order of:
  • Steam ID

  • Mentions

  • Name

  • URLs

class steam.ext.commands.ChannelConverter

The converter that is used when the type-hint passed is Channel.

Lookup is in the order of:
  • ID

  • Name

class steam.ext.commands.ClanConverter

The converter that is used when the type-hint passed is Clan.

Lookup is in the order of:
  • Steam ID

  • Name

  • URLs

class steam.ext.commands.GroupConverter

The converter that is used when the type-hint passed is Group.

Lookup is in the order of:
  • ID

  • Name

class steam.ext.commands.GameConverter

The converter that is used when the type-hint passed is Game.

If the param is a digit it is assumed that the argument is the Game.id else it is assumed it is the Game.title.

Default Values

class steam.ext.commands.Default

A custom way to specify a default values for commands.

Examples

Builtin:

@bot.command()
async def info(ctx, user=DefaultAuthor):
    ...  # if no user is passed it will be ctx.author

A custom default:

class CurrentCommand(commands.Default):
    async def default(self, ctx: commands.Context) -> commands.Command:
        return ctx.command  # return the current command

# then later
@bot.command
async def source(ctx: commands.Context, command: commands.Command = CurrentCommand):
    ...  # command would now be source


# this could also be mixed in with a converter to convert a string to a command.
class steam.ext.commands.DefaultAuthor

Returns the Context.author

class steam.ext.commands.DefaultChannel

Returns the Context.channel

class steam.ext.commands.DefaultClan

Returns the Context.clan

class steam.ext.commands.DefaultGroup

Returns the Context.group

class steam.ext.commands.DefaultGame

Returns the Context.author’s game

Greedy

Attributes
class steam.ext.commands.Greedy

A custom typing.Generic that allows for special greedy command parsing behaviour. It signals to the command parser to consume as many arguments as it can until it silently errors reverts the last argument being read and then carries on normally.

Greedy can be mixed in with any normally supported positional or keyword argument type any number of times.

Example

@bot.command()
async def test(ctx, numbers: commands.Greedy[int], reason: str):
    await ctx.send(f"numbers: {numbers}, reason: {reason}")

An invocation of "test 1 2 3 4 5 6 hello" would pass (1, 2, 3, 4, 5, 6) to numbers and "hello" to reason.

converter: steam.ext.commands.converters.T
classmethod __class_getitem__(converter)

The entry point for creating a Greedy type.

Note

Passing more than one argument to converter is shorthand for Union[converter_tuple].

Return type

steam.Greedy

Exceptions

exception steam.ext.commands.CommandError

Base Exception for errors raised by commands.

Subclass of SteamException.

exception steam.ext.commands.BadArgument

Exception raised when a bad argument is passed to a command.

Subclass of CommandError.

exception steam.ext.commands.MissingRequiredArgument(param)

Exception raised when a required argument is not passed to a command.

Subclass of BadArgument.

param

The argument that is missing.

exception steam.ext.commands.DuplicateKeywordArgument(name)

Exception raised when a keyword argument passed would shadow another.

Subclass of BadArgument.

name

The argument that would shadow another.

exception steam.ext.commands.UnmatchedKeyValuePair

Exception raised when an incorrect number of key value pairs are passed to a command to be unpacked.

Subclass of BadArgument.

exception steam.ext.commands.CheckFailure

Base Exception raised when a check fails.

Subclass of CommandError.

exception steam.ext.commands.NotOwner

Exception raised the user does not own the bot.

Subclass of CheckFailure.

exception steam.ext.commands.CommandNotFound

Exception raised when a command is not found.

Subclass of CommandError.

exception steam.ext.commands.CommandDisabled(command)

Exception raised when a command is disabled and is attempted to be ran.

Subclass of CheckFailure.

command

The command that has been disabled.

exception steam.ext.commands.CommandOnCooldown(retry_after)

Exception raised when a command is still on cooldown.

Subclass of CommandError.

retry_after

The time in seconds at which that the next command can successfully be executed.

Exception Hierarchy