API Reference

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

Bot

Methods
class rebootpy.ext.commands.Bot(command_prefix, auth, *, help_command=<default-help-command>, description=None, **kwargs)[source]

Represents a fortnite bot.

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

This class also subclasses GroupMixin to provide the functionality to manage commands.

command_prefix

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and rebootpy.FriendMessage or rebootpy.PartyMessage as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation.

The command prefix could also be an iterable of strings indicating that multiple checks for the prefix should be used and the first one to match will be the invocation prefix. You can get this prefix via Context.prefix. To avoid confusion empty iterables are not allowed.

Note

When passing multiple prefixes be careful to not pass a prefix that matches a longer prefix occurring later in the sequence. For example, if the command prefix is ('!', '!?') the '!?' prefix will never be matched to any message as the previous one matches messages starting with !?. This is especially important when passing an empty string, it should always be last as no prefix after it will be matched.

case_insensitive

Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.

Type:

bool

description

The content prefixed into the default help message.

Type:

str

help_command

The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see ext_commands_help_command.

Type:

Optional[HelpCommand]

owner_id

The user ID that owns the bot. This is used by is_owner() and checks that call this method.

Type:

Optional[int]

owner_ids

The user IDs that owns the bot. This is similar to owner_id. For performance reasons it is recommended to use a set for the collection. You cannot set both owner_id and owner_ids. This is used by is_owner() and checks that call this method.

Type:

Optional[Collection[int]]

async close(*, close_http=True, dispatch_close=True)[source]

This function is a coroutine.

Logs the user out and closes running services.

Parameters:
  • close_http (bool) – Whether or not to close the clients aiohttp.ClientSession when logged out.

  • dispatch_close (bool) – Whether or not to dispatch the close event.

Raises:

HTTPException – An error occurred while logging out.

check(func)[source]

A decorator that adds a check globally to every command.

Note

This function can either be a regular function or a coroutine.

This function takes a single parameter, Context, and can only raise exceptions inherited from CommandError.

Example

@bot.check
def global_check(ctx):
    # Allows only party commands.
    return ctx.party is not None
add_check(func, *, call_once=False)[source]

Adds a global check to the bot.

This is the non-decorator interface to check() and check_once().

Parameters:
  • func – The function that was used as a global check.

  • call_once (bool) – If the function should only be called once per Command.invoke() call.

remove_check(func, *, call_once=False)[source]

Removes a global check from the bot.

Parameters:
  • func – The function to remove from the global checks.

  • call_once (bool) – If the function was added with call_once=True in the Bot.add_check() call or using check_once().

check_once(func)[source]

A decorator that adds a “call once” global check to the bot.

Unlike regular global checks, this one is called only once per Command.invoke() call.

Regular global checks are called whenever a command is called or Command.can_run() is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.

Note

This function can either be a regular function or a coroutine.

This function takes a single parameter, Context, and can only raise exceptions inherited from CommandError.

Example

@bot.check_once
def whitelist(ctx):
    return ctx.message.author.id in my_whitelist
async is_owner(user_id)[source]

This function is a coroutine.

Checks if a user id is the owner of the bot.

Parameters:

user_id (str) – The user id to check for.

Returns:

Whether the user is the owner.

Return type:

bool

before_invoke(coro)[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context.

Note

The before_invoke() and after_invoke() hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.

Parameters:

coro – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

after_invoke(coro)[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context.

Note

Similar to before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e. CommandInvokeError). This makes it ideal for clean-up scenarios.

Parameters:

coro – The coroutine to register as the post-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

add_cog(cog)[source]

Adds a “cog” to the bot.

A cog is a class that has its own event listeners and commands.

Parameters:

cog (Cog) – The cog to register to the bot.

Raises:
remove_cog(name)[source]

Removes a cog from the bot.

All registered commands and event listeners that the cog has registered will be removed as well.

If no cog is found then this method has no effect.

Parameters:

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

get_cog(name)[source]

Gets the cog instance requested.

If the cog is not found, None is returned instead.

Parameters:

name (str) – The name of the cog you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

property cogs

A read-only mapping of cog name to cog.

Type:

Mapping[str, Cog]

load_extension(name)[source]

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, extension_setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

Parameters:

name (str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises:
unload_extension(name)[source]

Unloads an extension.

When the extension is unloaded, all commands, listeners, and cogs are removed from the bot and the module is un-imported.

The extension can provide an optional global function, cog_teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, the bot, similar to extension_setup from load_extension().

Parameters:

name (str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises:

ExtensionNotLoaded – The extension was not loaded.

reload_extension(name)[source]

Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a unload_extension() followed by a load_extension() except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.

Parameters:

name (str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g. foo.test if you want to import foo/test.py.

Raises:
property extensions

A read-only mapping of extension name to extension.

Type:

Mapping[str, types.ModuleType]

async get_prefix(message)[source]

This function is a coroutine.

Retrieves the prefix the bot is listening to with the message as a context.

Parameters:

message (Union[rebootpy.FriendMessage, rebootpy.PartyMessage]) – The message context to get the prefix of.

Returns:

A list of prefixes or a single prefix that the bot is listening for.

Return type:

Union[List[str], str]

async get_context(message, *, cls=<class 'rebootpy.ext.commands.context.Context'>)[source]

This function is a coroutine.

Returns the invocation context from the message.

This is a more low-level counter-part for process_commands() to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is.

If the context is not valid then it is not a valid candidate to be invoked under invoke().

Parameters:
  • message (Union[rebootpy.FriendMessage, rebootpy.PartyMessage]) – The message to get the invocation context from.

  • cls – The factory class that will be used to create the context. By default, this is Context. Should a custom class be provided, it must be similar enough to Context's interface.

Returns:

The invocation context. The type of this can change via the cls parameter.

Return type:

Context

async accept_friend(user_id)

This function is a coroutine.

Warning

Do not use this method to send a friend request. It will then not return until the friend request has been accepted by the user.

Accepts a request.

Parameters:

user_id (str) – The id of the user you want to accept.

Raises:
  • NotFound – The specified user does not exist.

  • DuplicateFriendship – The client is already friends with this user.

  • FriendshipRequestAlreadySent – The client has already sent a friendship request that has not been handled yet by the user.

  • Forbidden – The client is not allowed to send friendship requests to the user because of the users settings.

  • HTTPException – An error occurred while requesting to accept this friend.

Returns:

Object of the friend you just added.

Return type:

Friend

add_command(command)

Adds a Command or its subclasses into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
  • .ClientException – If the command is already registered.

  • TypeError – If the command passed is not a subclass of Command.

add_event_handler(event, coro)

Registers a coroutine as an event handler. You can register as many coroutines as you want to a single event.

Parameters:
  • event (str) – The name of the event you want to register this coro for.

  • coro (coroutine) – The coroutine to function as the handler for the specified event.

Raises:

TypeError – The function passed to coro is not a coroutine.

async add_friend(user_id)

This function is a coroutine.

Sends a friend request to the specified user id.

Parameters:

user_id (str) – The id of the user you want to add.

Raises:
  • NotFound – The specified user does not exist.

  • DuplicateFriendship – The client is already friends with this user.

  • FriendshipRequestAlreadySent – The client has already sent a friendship request that has not been handled yet by the user.

  • MaxFriendshipsExceeded – The client has hit the max amount of friendships a user can have at a time. For most accounts this limit is set to 1000 but it could be higher for others.

  • InviteeMaxFriendshipsExceeded – The user you attempted to add has hit the max amount of friendships a user can have at a time.

  • InviteeMaxFriendshipRequestsExceeded – The user you attempted to add has hit the max amount of friendship requests a user can have at a time. This is usually 700 total requests.

  • Forbidden – The client is not allowed to send friendship requests to the user because of the users settings.

  • HTTPException – An error occurred while requesting to add this friend.

async block_user(user_id)

This function is a coroutine.

Blocks a user by a given user id.

Parameters:

user_id (str) – The id of the user you want to block.

Raises:

HTTPException – Something went wrong when trying to block this user.

property blocked_user_count

The amount of blocked users the bot currently has blocked.

Type:

int

property blocked_users

A list of the users client has as blocked.

Type:

List[BlockedUser]

command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

property commands

A unique set of commands without aliases that are registered.

Type:

Set[Command]

event(event_or_coro=None)

A decorator to register an event.

Note

You do not need to decorate events in a subclass of BasicClient but the function names of event handlers must follow this format event_<event>.

Usage:

@client.event
async def event_friend_message(message):
    await message.reply('Thanks for your message!')

@client.event('friend_message')
async def my_message_handler(message):
    await message.reply('Thanks for your message!')
Raises:
  • TypeError – The decorated function is not a coroutine.

  • TypeError – Event is not specified as argument or function name with event prefix.

async fetch_active_ltms(region)

This function is a coroutine.

Fetches active LTMs for a specific region.

Parameters:

region (Region) – The region to request active LTMs for.

Raises:

HTTPException – An error occurred while requesting.

Returns:

List of internal playlist names. Returns an empty list of none LTMs are for the specified region.

Return type:

List[str]

async fetch_avatars(users)

This function is a coroutine.

Fetches the avatars of the provided user ids.

Warning

You can only fetch avatars of friends. That means that the bot has to be friends with the users you are requesting the avatars of.

Parameters:

users (List[str]) – A list containing user ids.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A dict containing avatars mapped to their user id.

Return type:

Dict[str, Avatar]

async fetch_battlepass_level(user_id, *, season, start_time=None, end_time=None)

This function is a coroutine.

Fetches a user’s battlepass level.

Parameters:
  • user_id (str) – The user id to fetch the battlepass level for.

  • season (Season) –

    The season enum to request the battlepass level for.

    Warning

    If you are requesting the previous season and the new season has not been added to the library yet (check SeasonStartTimestamp), you have to manually include the previous season’s end timestamp in epoch seconds.

  • start_time (Optional[Union[int, datetime.datetime]) – The UTC start time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or the ``start_timestamp`` value of a :class:`Season` e.g. `Season.C5SOG.start_timestamp` Defaults to None

  • end_time (Optional[Union[int, datetime.datetime]) – The UTC end time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or the ``start_timestamp`` value of a :class:`Season` e.g. `Season.C5SOG.start_timestamp` Defaults to None

Raises:
Returns:

The user’s battlepass level. None is returned if the user has not played any real matches this season.

Note

The decimals are the percent progress to the next level. E.g. 208.63 -> Level 208 and 63% on the way to 209.

Return type:

Optional[float]

async fetch_blocklist()

This function is a coroutine.

Retrieves the blocklist with an api call.

Raises:

HTTPException – An error occurred while fetching blocklist.

Returns:

List of ids

Return type:

List[str]

async fetch_br_news()

This function is a coroutine.

Fetches news for the Battle Royale gamemode.

Note

News is now specific to the player, most players who play regularly may get 1 or 2 different news posts to an account that has either never played or hasnt played in a while.

Raises:

HTTPException – An error occurred when requesting.

Returns:

List[BattleRoyaleNewsPost]

Return type:

list

async fetch_br_playlists()

This function is a coroutine.

Fetches all playlists registered on Fortnite. This includes all previous gamemodes that is no longer active.

Raises:

HTTPException – An error occurred while requesting.

Returns:

List containing all playlists registered on Fortnite.

Return type:

List[Playlist]

async fetch_br_stats(user_id, *, start_time=None, end_time=None)

This function is a coroutine.

Gets Battle Royale stats for the specified user.

Parameters:
  • user_id (str) – The id of the user you want to fetch stats for.

  • start_time (Optional[Union[int, datetime.datetime]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the ``start_timestamp`` value of a :class:`Season` (e.g., ``Season.C5SOG.start_timestamp``). Defaults to None.

  • end_time (Optional[Union[int, datetime.datetime]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the ``end_timestamp`` value of a :class:`Season` (e.g., ``Season.C5SOG.end_timestamp``). Defaults to None.

Raises:
  • Forbidden

    The user has chosen to be hidden from public stats by disabling the fortnite setting below. | Settings -> Account and Privacy -> Show on career     leaderboard

  • HTTPException – An error occurred while requesting.

Returns:

An object representing the stats for this user. If the user was not found None is returned.

Return type:

StatsV2

async fetch_creative_island(code)

This function is a coroutine.

Fetches a creative island or playlist by its code.

Parameters:

code (str) – Either the island code or playlist ID.

Raises:

HTTPException – An error occurred while requesting.

Returns:

Object representing the data of the creative island/playlist.

Return type:

CreativeIsland

async fetch_event_tokens(user_id)

This function is a coroutine.

Gets event tokens for the specified user.

Parameters:

user_id (str) – The id of the user you want to fetch event tokens for.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A list of event tokens.

Return type:

list[str]

async fetch_flag(user_id)

This function is a coroutine.

Gets current set flag for the specified user.

Parameters:

user_id (str) – The id of the user you want to fetch the flag for.

Raises:

HTTPException – An error occurred while requesting.

Returns:

The users flag.

Return type:

Country | None

async fetch_item_shop()

This function is a coroutine.

Fetches the current item shop.

Example:

# fetches all CIDs (character ids) of of the current item shop.
async def get_current_item_shop_cids():
    store = await client.fetch_item_shop()

    cids = []
    for item in store.featured_items + store.daily_items:
        for grant in item.grants:
            if grant['type'] == 'AthenaCharacter':
                cids.append(grant['asset'])

    return cids
Raises:

HTTPException – An error occurred when requesting.

Returns:

Object representing the data from the current item shop.

Return type:

Store

async fetch_leaderboard(stat)

This function is a coroutine.

Fetches the leaderboard for a stat.

Warning

For some weird reason, the only valid stat you can pass is one with placetop1 (wins is also accepted).

Example usage:

async def get_leaderboard():
    stat = rebootpy.StatsV2.create_stat(
        'wins',
        rebootpy.V2Input.KEYBOARDANDMOUSE,
        'defaultsquad'
    )

    data = await client.fetch_leaderboard(stat)

    for placement, entry in enumerate(data):
        print('[{0}] Id: {1} | Wins: {2}'.format(
            placement, entry['account'], entry['value']))
Parameters:

stat (str) – The stat you are requesting the leaderboard entries for. You can use StatsV2.create_stat() to create this string.

Raises:
  • ValueError – You passed an invalid/non-accepted stat argument.

  • HTTPException – An error occurred when requesting.

Returns:

List of dictionaries containing entry data. Example return:

{
    'account': '4480a7397f824fe4b407077fb9397fbb',
    'value': 5082
}

Return type:

List[Dict[str, Union[str, int]]]

async fetch_lightswitch_status(service_id='Fortnite')

This function is a coroutine.

Fetches the lightswitch status of an epicgames service.

Parameters:

service_id (str) – The service id to check status for.

Raises:
  • ValueError – The returned data was empty. Most likely because service_id is not valid.

  • HTTPException – An error occurred when requesting.

Returns:

True if service is up else False

Return type:

bool

async fetch_multiple_battlepass_levels(users, season, *, start_time=None, end_time=None)

This function is a coroutine.

Fetches multiple users’ battlepass level.

Parameters:
  • users (List[str]) – List of user ids.

  • season (Season) – The season enum to request the battlepass levels for.

  • start_time (Optional[Union[int, datetime.datetime]]) – The UTC start time of the window to get the battlepass level from. Must be seconds since epoch or a datetime.datetime instance. Defaults to None.

  • end_time (Optional[Union[int, datetime.datetime]]) – The UTC end time of the window to get the battlepass level from. Must be seconds since epoch or a datetime.datetime instance. Defaults to None.

Raises:
  • ValueError – If end_time is earlier than the season’s start timestamp.

  • HTTPException – An error occurred while requesting.

Returns:

Users’ battlepass level mapped to their account id. Returns None if no battlepass level was found. If a user has career board set to private, they will not appear in the result. Therefore you should never expect a user to be included.

Note

The decimals are the percent progress to the next level. E.g. 208.63 -> Level 208 and 63% on the way to 209.

Note

If a user’s battlepass level is missing in the returned mapping, it means that the user has opted out of public leaderboards and that the client therefore does not have permission to request their stats.

Return type:

Dict[str, Optional[float]]

async fetch_multiple_br_stats(user_ids, stats, *, start_time=None, end_time=None)

This function is a coroutine.

Gets Battle Royale stats for multiple users at the same time.

Note

This function is not the same as doing fetch_br_stats() for multiple users. The expected return for this function would not be all the stats for the specified users but rather the stats you specify.

Example usage:

async def stat_function():
    stats = [
        rebootpy.StatsV2.create_stat('placetop1', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'),
        rebootpy.StatsV2.create_stat('kills', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'),
        rebootpy.StatsV2.create_stat('matchesplayed', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo')
    ]

    users = await self.fetch_users(['SypherPK', 'CouRageJD'])
    user_ids = [u.id for u in users]

    data = await self.fetch_multiple_br_stats(user_ids=user_ids, stats=stats)
    for id, res in data.items():
        if res is not None:
            print('ID: {0} | Stats: {1}'.format(id, res.get_stats()))
        else:
            print('ID: {0} not found.')

# Example output:
# ID: 463ca9d604524ce38071f512baa9cd70 | Stats: {'keyboardmouse': {'defaultsolo': {'wins': 759, 'kills': 28093, 'matchesplayed': 6438}}}
# ID: 3900c5958e4b4553907b2b32e86e03f8 | Stats: {'keyboardmouse': {'defaultsolo': {'wins': 1763, 'kills': 41375, 'matchesplayed': 7944}}}
# ID: NonValidUserIdForTesting not found.
Parameters:
  • user_ids (List[str]) – A list of ids you are requesting the stats for.

  • stats (List[str]) –

    A list of stats to get for the users. Use StatsV2.create_stat() to create the stats.

    Example:

    [
        rebootpy.StatsV2.create_stat('placetop1', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'),
        rebootpy.StatsV2.create_stat('kills', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'),
        rebootpy.StatsV2.create_stat('matchesplayed', rebootpy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo')
    ]
    

  • start_time (Optional[Union[int, datetime.datetime]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the `start_timestamp` value of a :class:`Season` (e.g., ``Season.C5SOG.start_timestamp``). Defaults to None.

  • end_time (Optional[Union[int, datetime.datetime]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the `end_timestamp` value of a :class:`Season` (e.g., ``Season.C5SOG.end_timestamp``). Defaults to None.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A mapping where StatsV2 is bound to its owners id. If a userid was not found then the value bound to that userid will be None.

Note

If a users stats is missing in the returned mapping it means that the user has opted out of public leaderboards and that the client therefore does not have permissions to request their stats.

Return type:

Dict[str, Optional[StatsV2]]

async fetch_multiple_br_stats_collections(user_ids, collection=None, *, start_time=None, end_time=None)

This function is a coroutine.

Gets Battle Royale stats collections for multiple users at the same time.

Parameters:
  • user_ids (List[str]) – A list of ids you are requesting the stats for.

  • collection (StatsCollectionType) – The collection to receive. Collections are predefined stats that it attempts to request.

  • start_time (Optional[Union[int, datetime.datetime]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the `start_timestamp` value of a :class:`Season` (e.g., ``Season.C5SOG.start_timestamp``). Defaults to None.

  • end_time (Optional[Union[int, datetime.datetime]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime`, or the `end_timestamp` value of a :class:`Season` (e.g., ``Season.C5SOG.end_timestamp``). Defaults to None.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A mapping where StatsCollection is bound to its owner’s id. If a userid was not found then the value bound to that userid will be None.

Note

If a user’s stats are missing in the returned mapping, it means that the user has opted out of public leaderboards and that the client therefore does not have permissions to request their stats.

Return type:

Dict[str, Optional[StatsCollection]]

async fetch_multiple_event_tokens(user_ids)

This function is a coroutine.

Gets event tokens for the specified users.

Parameters:

user_ids (list) – A list of user ids you want to fetch event tokens for.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A dictionary with user ids mapped to a list of tokens.

Return type:

dict

async fetch_multiple_flags(user_ids)

This function is a coroutine.

Gets the current set flags for the specified users.

Parameters:

user_ids (str) – A list of user ids you want to fetch flags for.

Raises:

HTTPException – An error occurred while requesting.

Returns:

A dictionary with user ids mapped to a flag enum.

Return type:

dict[str, Country | None]

async fetch_party(party_id)

This function is a coroutine.

Fetches a party by its id.

Parameters:

party_id (str) – The id of the party.

Raises:

Forbidden – You are not allowed to look up this party.

Returns:

The party that was fetched. None if not found.

Return type:

Optional[Party]

async fetch_ranked_stats(user_id, season=None)

This function is a coroutine.

Gets ranked stats of the specified user, currently this works for all users even if they have their stats set to private.

Usage:

# get my C5S3 ranked stats
async def get_6v_ranked_stats():
    print(f'Fetching ranked stats for C5S3')

    user = await bot.fetch_user('6v.')
    ranks = await bot.fetch_ranked_stats(
        user_id=user.id,
        season=rebootpy.Season.C5S3
    )

    for rank in ranks:
        print(f'{rank.ranking_type.name} - {rank.current_division.name}')

# Example output:
# Fetching ranked stats for C5S3
# BATTLE_ROYALE - DIAMOND_2
# ROCKET_RACING - UNRANKED
# ZERO_BUILD - UNREAL
Parameters:
  • user_id (str) – The id of the user you want to fetch stats for.

  • season (Optional[Season]) – The season that you want to get ranks from. If not provided, it will get the current season’s ranked tracks automatically. Defaults to None

Raises:

HTTPException – An error occurred while requesting.

Returns:

A list of all of the user’s ranks in the requested season.

Return type:

List[CompetitiveRank]

async fetch_user(user, *, cache=False, raw=False)

This function is a coroutine.

Fetches a single user by the given id/displayname.

Parameters:
  • user (str) – Id or display name

  • cache (bool) –

    If set to True it will try to get the user from the friends or user cache and fall back to an api request if not found.

    Note

    Setting this parameter to False will make it an api call.

  • raw (bool) –

    If set to True it will return the data as you would get it from the api request.

    Note

    Setting raw to True does not work with cache set to True.

Raises:

HTTPException – An error occurred while requesting the user.

Returns:

The user requested. If not found it will return None

Return type:

Optional[User]

async fetch_user_by_display_name(display_name, *, cache=False, raw=False)

This function is a coroutine.

Fetches a user from the passed display name.

Parameters:
  • display_name (str) – The display name of the user you want to fetch the user for.

  • cache (bool) –

    If set to True it will try to get the user from the friends or user cache.

    Note

    Setting this parameter to False will make it an api call.

  • raw (bool) –

    If set to True it will return the data as you would get it from the api request.

    Note

    Setting raw to True does not work with cache set to True.

Raises:

HTTPException – An error occurred while requesting the user.

Returns:

The user requested. If not found it will return None.

Return type:

Optional[User]

async fetch_users(users, *, cache=False, raw=False)

This function is a coroutine.

Fetches multiple users at once by the given ids/displaynames.

Parameters:
  • users (Iterable[str]) – An iterable containing ids/displaynames.

  • cache (bool) –

    If set to True it will try to get the users from the friends or user cache and fall back to an api request if not found.

    Note

    Setting this parameter to False will make it an api call.

  • raw (bool) –

    If set to True it will return the data as you would get it from the api request.

    Note

    Setting raw to True does not work with cache set to True.

Raises:

HTTPException – An error occurred while requesting user information.

Returns:

Users requested. Only users that are found gets returned.

Return type:

List[User]

async fetch_users_by_display_name(display_name, *, raw=False)

This function is a coroutine.

Fetches all users including external users (accounts from other platforms) that matches the given the display name.

Warning

This function is not for requesting multiple users by multiple display names. Use BasicClient.fetch_user() for that.

Parameters:
  • display_name (str) – The display name of the users you want to get.

  • raw (bool) – If set to True it will return the data as you would get it from the api request. Defaults to ``False``

Raises:

HTTPException – An error occurred while requesting the user.

Returns:

A list containing all payloads found for this user.

Return type:

List[User]

property friend_count

The amount of friends the bot currently has.

Type:

int

property friends

A list of the clients friends.

Type:

List[Friend]

get_blocked_user(user_id)

Tries to get a blocked user from the blocked users cache by the given user id.

Parameters:

user_id (str) – The id of the blocked user.

Returns:

The blocked user if found, else None

Return type:

Optional[BlockedUser]

get_command(name)

Get a Command or subclasses from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

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

Returns:

The command that was requested. If not found, returns None.

Return type:

Command or subclass

get_friend(user_id)

Tries to get a friend from the friend cache by the given user id.

Parameters:

user_id (str) – The id of the friend.

Returns:

The friend if found, else None

Return type:

Optional[Friend]

get_incoming_pending_friend(user_id)

Tries to get an incoming pending friend from the pending friends cache by the given user id.

Parameters:

user_id (str) – The id of the incoming pending friend.

Returns:

The incoming pending friend if found, else None.

Return type:

Optional[IncomingPendingFriend]

get_outgoing_pending_friend(user_id)

Tries to get an outgoing pending friend from the pending friends cache by the given user id.

Parameters:

user_id (str) – The id of the outgoing pending friend.

Returns:

The outgoing pending friend if found, else None.

Return type:

Optional[OutgoingPendingFriend]

get_pending_friend(user_id)

Tries to get a pending friend from the pending friend cache by the given user id.

Parameters:

user_id (str) – The id of the pending friend.

Returns:

  • Optional[Union[IncomingPendingFriend,

  • OutgoingPendingFriend]] – The pending friend if found, else None

get_presence(user_id)

Tries to get the latest received presence from the presence cache.

Parameters:

user_id (str) – The id of the friend you want the last presence of.

Returns:

The presence if found, else None

Return type:

Optional[Presence]

get_user(user_id)

Tries to get a user from the user cache by the given user id.

Parameters:

user_id (str) – The id of the user.

Returns:

The user if found, else None

Return type:

Optional[User]

group(*args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

has_friend(user_id)

Checks if the client is friends with the given user id.

Parameters:

user_id (str) – The id of the user you want to check.

Returns:

True if user is friends with the client else False

Return type:

bool

property incoming_pending_friend_count

The amount of active incoming pending friends the bot currently has received.

Type:

int

property incoming_pending_friends

A list of the clients incoming pending friends.

Type:

List[IncomingPendingFriend]

is_blocked(user_id)

Checks if the given user id is blocked by the client.

Parameters:

user_id (str) – The id of the user you want to check.

Returns:

True if user is blocked else False

Return type:

bool

is_closed()

bool: Whether the client is running or not.

is_pending(user_id)

Checks if the given user id is a pending friend of the client.

Parameters:

user_id (str) – The id of the user you want to check.

Returns:

True if user is a pending friend else False

Return type:

bool

is_ready()

Specifies if the internal state of the client is ready.

Returns:

True if the internal state is ready else False

Return type:

bool

async join_party(party_id)

This function is a coroutine.

Joins a party by the party id.

Parameters:

party_id (str) – The id of the party you wish to join.

Raises:
  • .. warning:: – Because the client has to leave its current party before joining a new one, a new party is created if some of these errors are raised. Most of the time though this is not the case and the client will remain in its current party.

  • PartyError – You are already a member of this party.

  • NotFound – The party was not found.

  • PartyIsFull – The party you attempted to join is full.

  • Forbidden – You are not allowed to join this party because it’s private and you have not been a part of it before. .. note:: If you have been a part of the party before but got kicked, you are ineligible to join this party and this error is raised.

  • HTTPException – An error occurred when requesting to join the party.

Returns:

The party that was just joined.

Return type:

ClientParty

property outgoing_pending_friend_count

The amount of active outgoing pending friends the bot has sent.

Type:

int

property outgoing_pending_friends

A list of the clients outgoing pending friends.

Type:

List[OutgoingPendingFriend]

property pending_friend_count

The amount of pending friends the bot currently has.

Type:

int

property pending_friends

List[Union[IncomingPendingFriend, OutgoingPendingFriend]]: A list of all of the clients pending friends.

Note

Pending friends can be both incoming (pending friend sent the request to the bot) or outgoing (the bot sent the request to the pending friend). You must check what kind of pending friend an object is by their attributes incoming or outgoing.

property presences

A list of the last presences from currently online friends.

Type:

List[Presence]

property qualified_case_insensitive

The qualified case insensitive. This means that the it will never return None as it checks inherited values. Could be None but only if the bot is not ultimately registered to the bot yet.

Type:

bool

register_connectors(http_connector=None, ws_connector=None)

This can be used to register connectors after the client has already been initialized. It must however be called before start() has been called, or in event_before_start().

Warning

Connectors passed will not be closed on shutdown. You must close them yourself if you want a graceful shutdown.

Parameters:
remove_command(name)

Remove a Command or subclasses from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

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

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Command or subclass

remove_event_handler(event, coro)

Removes a coroutine as an event handler.

Parameters:
  • event (str) – The name of the event you want to remove this coro for.

  • coro (coroutine) – The coroutine that already functions as a handler for the specified event.

async remove_or_decline_friend(user_id)

This function is a coroutine.

Removes a friend by the given id.

Parameters:

user_id (str) – The id of the friend you want to remove.

Raises:

HTTPException – Something went wrong when trying to remove this friend.

async restart()

This function is a coroutine.

Restarts the client completely. All events received while this method runs are dispatched when it has finished.

Raises:
  • AuthException – Raised if invalid credentials in any form was passed or some other misc failure.

  • HTTPException – A request error occurred while logging in.

run()

This function starts the loop and then calls start() for you. If your program already has an asyncio loop setup, you should use start() instead.

Warning

This function is blocking and should be the last function to run.

Raises:
  • AuthException – Raised if invalid credentials in any form was passed or some other misc failure.

  • HTTPException – A request error occurred while logging in.

async search_sac_by_slug(slug)

This function is a coroutine.

Searches for an owner of slug + retrieves owners of similar slugs.

Parameters:

slug (str) – The slug (support a creator code) you wish to search for.

Raises:

HTTPException – An error occurred while requesting fortnite’s services.

Returns:

An ordered list of users who matched the exact or slightly modified slug.

Return type:

List[SacSearchEntryUser]

async search_users(prefix, platform)

This function is a coroutine.

Searches after users by a prefix and returns up to 100 matches.

Parameters:
  • prefix (str) –

    The prefix you want to search by. The prefix is case insensitive.
    Example: Tfue will return Tfue’s user + up to 99 other

    users which have display names that start with or match exactly to Tfue like Tfue_Faze dequan.

  • platform (UserSearchPlatform) –

    The platform you wish to search by.

    Note

    The platform is only important for prefix matches. All exact matches are returned regardless of which platform is specified.

Raises:

HTTPException – An error occurred while requesting.

Returns:

An ordered list of users that matched the prefix.

Return type:

List[UserSearchEntry]

async send_presence(status, *, away=AwayStatus.ONLINE, to=None)

This function is a coroutine.

Sends this status to all or one single friend.

Parameters:
  • status (Union[str, dict]) – The status message in str or full status in dict.

  • away (AwayStatus) – The away status to use. Defaults to AwayStatus.ONLINE.

  • to (Optional[aioxmpp.JID]) – The JID of the user that should receive this status. Defaults to None which means it will send to all friends.

Raises:

TypeError – Status was an invalid type.

async set_platform(platform)

This function is a coroutine.

Sets and updates the clients platform. You may need to click off the lobby (i.e. go to your locker and back) to see platform changes in the same party.

Parameters:

platform (Platform) – The platform to set.

Raises:

HTTPException – An error occurred when requesting.

set_presence(status, *, away=AwayStatus.ONLINE)

This function is a coroutine.

Sends and sets the status. This status message will override all other presence statuses including party presence status.

Parameters:
  • status (str) – The status you want to set.

  • away (AwayStatus) – The away status to use. Defaults to AwayStatus.ONLINE.

Raises:

TypeError – The status you tried to set were not a str.

start(dispatch_ready=True)

This function is a coroutine.

Starts the client and logs into the specified user.

This method can be used as a coroutine or an async context manager, depending on your needs.

How to use as an async context manager: ::
async with client.start():

user = await client.fetch_user(‘Ninja’) print(user.display_name)

If you want to use it as an async context manager, but also keep the client running forever, you can await the return of start like this:

async with client.start() as future:
    user = await client.fetch_user('Ninja')
    print(user.display_name)

    await future  # Nothing after this line will run.

Warning

This method is blocking if you await it as a coroutine or you await the return future. This means that no code coming after will run until the client is closed. When the client is ready it will dispatch event_ready().

Parameters:

dispatch_ready (bool) – Whether or not the client should dispatch the ready event when ready.

Raises:
  • AuthException – Raised if invalid credentials in any form was passed or some other misc failure.

  • HTTPException – A request error occurred while logging in.

async unblock_user(user_id)

This function is a coroutine.

Unblocks a user by a given user id.

Parameters:

user_id (str) – The id of the user you want to unblock

Raises:

HTTPException – Something went wrong when trying to unblock this user.

wait_for(event, *, check=None, timeout=None)

This function is a coroutine.

Waits for an event to be dispatch.

In case the event returns more than one arguments, a tuple is passed containing the arguments.

Examples

This example waits for the author of a FriendMessage to say hello.:

@client.event
async def event_friend_message(message):
    await message.reply('Say hello!')

    def check_function(m):
        return m.author.id == message.author.id

    msg = await client.wait_for('message', check=check_function, timeout=60)
    await msg.reply('Hello {0.author.display_name}!'.format(msg))

This example waits for the the leader of a party to promote the bot after joining and then sets a new custom key:

@client.event
async def event_party_member_join(member):

    # checks if the member that joined is the UserClient
    if member.id != client.user.id:
        return

    def check(m):
        return m.id == client.user.id

    try:
        await client.wait_for('party_member_promote', check=check, timeout=120)
    except asyncio.TimeoutError:
        await member.party.send('You took too long to promote me!')

    await member.party.set_custom_key('my_custom_key_123')
Parameters:
  • event (str) –

    The name of the event.

    Note

    The name of the event must be without the event_

    prefix. | | Wrong = event_friend_message. | Correct = friend_message.

  • check (Optional[Callable]) – A predicate to check what to wait for. Defaults to a predicate that always returns True. This means it will return the first result unless you pass another predicate.

  • timeout (int) – How many seconds to wait for before asyncio.TimeoutError is raised. Defaults to ``None`` which means it will wait forever.

Raises:

asyncio.TimeoutError – No event was retrieved in the time you specified.

Returns:

Returns arguments based on the event you are waiting for. An event might return no arguments, one argument or a tuple of arguments. Check the event reference <rebootpy-events-api> for more information about the returning arguments.

Return type:

Any

async wait_until_closed()

This function is a coroutine.

Waits until the client is fully closed.

async wait_until_ready()

This function is a coroutine.

Waits until the internal state of the client is ready.

walk_commands()

An iterator that recursively walks through all commands and subcommands.

async invoke(ctx)[source]

This function is a coroutine.

Invokes the command given under the invocation context and handles all the internal event dispatch mechanisms.

Parameters:

ctx (Context) – The invocation context to invoke.

async process_commands(message)[source]

This function is a coroutine.

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called automatically when a new message is received.

This is built using other low level tools, and is equivalent to a call to get_context() followed by a call to invoke().

Parameters:

message (Union[rebootpy.FriendMessage, rebootpy.PartyMessage]) – The message to process commands for.

Event Reference

These events function similar to the regular events, except they are custom to the command extension module.

rebootpy.event_command_error(ctx, error)

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

Command error handlers are raised in a specific order. Returning False in any of them will invoke the next handler in the chain. If there are no handlers left to call, then the error is printed to stderr (console).

The order goes as follows: 1. The local command error handler is called. (Handler specified by decorating a command error handler with Command.error()) 2. The local cog command error handler is called. 3. All event_command_error() handlers are called simultaneously. If any of them return False, then the error will be printed.

Parameters:
  • ctx (Context) – The invocation context.

  • error (CommandError derived) – The error that was raised.

rebootpy.event_command(ctx)

An event that is called when a command is found and is about to be invoked.

This event is called regardless of whether the command itself succeeds via error or completes.

Parameters:

ctx (Context) – The invocation context.

rebootpy.event_command_completion(ctx)

An event that is called when a command has completed its invocation.

This event is called only if the command succeeded, i.e. all checks have passed and the user input it correctly.

Parameters:

ctx (Context) – The invocation context.

Command

command()

rebootpy.ext.commands.command(name=None, cls=None, **attrs)[source]

A decorator that transforms a function into a Command or if called with group(), Group.

By default the help attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using utf-8 encoding.

All checks added using the check() & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

Parameters:
  • name (str) – The name to create the command with. By default this uses the function name unchanged.

  • cls – The class to construct with. By default this is Command. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises:

TypeError – If the function is not a coroutine or is already a command.

group()

rebootpy.ext.commands.group(name=None, **attrs)[source]

A decorator that transforms a function into a Group.

This is similar to the command() decorator but the cls parameter is set to Group by default.

Command

class rebootpy.ext.commands.Command(*args, **kwargs)[source]

A class that implements the protocol for a bot text command. These are not created manually, instead they are created via the decorator or functional interface.

name

The name of the command.

Type:

str

callback

The coroutine that is executed when the command is called.

help

The long help text for the command.

Type:

str

brief

The short help text for the command. If this is not specified then the first line of the long help text is used instead.

Type:

str

usage

A replacement for arguments in the default help text.

Type:

str

aliases

The list of aliases the command can be invoked under.

Type:

Union[list, tuple]

enabled

A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the event_command_error() event. Defaults to True.

Type:

bool

parent

The parent command that this command belongs to. None if there isn’t one.

Type:

Optional[Command]

cog

The cog that this command belongs to. None if there isn’t one.

Type:

Optional[Cog]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the event_command_error() event.

Type:

List[Callable[…, bool]]

description

The message prefixed into the default help command.

Type:

str

hidden

If True, the default help command does not show this in the help output.

Type:

bool

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type:

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type:

Optional[Command]

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise event_command_error() and local error handlers are called with TooManyArguments. Defaults to True.

Type:

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type:

bool

add_check(func)[source]

Adds a check to the command.

This is the non-decorator interface to check().

Parameters:

func – The function that will be used as a check.

remove_check(func)[source]

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

Parameters:

func – The function to remove from the checks.

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

async __call__(*args, **kwargs)[source]

This function is a coroutine.

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 and types to this function.

property clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

Type:

OrderedDict[str, typing.Parameter]

property full_parent_name

Retrieves the fully qualified parent command name.

This is the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

property parents

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

Type:

Command

property root_parent

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

property qualified_name

Retrieves the fully qualified command name.

This is the full parent name with the command name as well.

For example, in ?one two three the qualified name would be one two three.

Type:

str

is_on_cooldown(ctx)[source]

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

reset_cooldown(ctx)[source]

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

error(coro)[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an event_command_error() event limited to a single command.

Command error handlers are raised in a specific order. Returning False in any of them will invoke the next handler in the chain. If there are no handlers left to call, then the error is printed to stderr (console).

The order goes as follows: 1. The local command error handler is called. (Handler specified by this decorator.) 2. The local cog command error handler is called. 3. All event_command_error() handlers are called simultaneously. If any of them return False, then the error will be printed.

Parameters:

coro – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

before_invoke(coro)[source]

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context. See Bot.before_invoke() for more info.

Parameters:

coro – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

after_invoke(coro)[source]

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context. See Bot.after_invoke() for more info.

Parameters:

coro – The coroutine to register as the post-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property cog_name

The name of the cog this command belongs to. None otherwise.

Type:

str

property short_doc

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature

Returns a POSIX-like signature useful for help command output.

Type:

str

async can_run(ctx)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

A boolean indicating if the command can be invoked.

Return type:

bool

Group

class rebootpy.ext.commands.Group(*args, **kwargs)[source]

A class that implements a grouping protocol for commands to be executed as subcommands.

This class is a subclass of Command and thus all options valid in Command are valid in here as well.

invoke_without_command

Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is False, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults to False.

Type:

Optional[bool]

case_insensitive

Indicates if the group’s commands should be case insensitive. Defaults to None which means it inherits the parents or bots value.

Type:

Optional[bool]

add_check(func)

Adds a check to the command.

This is the non-decorator interface to check().

Parameters:

func – The function that will be used as a check.

add_command(command)

Adds a Command or its subclasses into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
  • .ClientException – If the command is already registered.

  • TypeError – If the command passed is not a subclass of Command.

after_invoke(coro)

A decorator that registers a coroutine as a post-invoke hook.

A post-invoke hook is called directly after the command is called. This makes it a useful function to clean-up database connections or any type of clean up required.

This post-invoke hook takes a sole parameter, a Context. See Bot.after_invoke() for more info.

Parameters:

coro – The coroutine to register as the post-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

before_invoke(coro)

A decorator that registers a coroutine as a pre-invoke hook.

A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.

This pre-invoke hook takes a sole parameter, a Context. See Bot.before_invoke() for more info.

Parameters:

coro – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

async can_run(ctx)

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. This also checks whether the command is disabled.

Parameters:

ctx (Context) – The ctx of the command currently being invoked.

Raises:

CommandError – Any command error that was raised during a check call will be propagated by this function.

Returns:

A boolean indicating if the command can be invoked.

Return type:

bool

property clean_params

Retrieves the parameter OrderedDict without the context or self parameters.

Useful for inspecting signature.

Type:

OrderedDict[str, typing.Parameter]

property cog_name

The name of the cog this command belongs to. None otherwise.

Type:

str

command(*args, **kwargs)

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

property commands

A unique set of commands without aliases that are registered.

Type:

Set[Command]

error(coro)

A decorator that registers a coroutine as a local error handler.

A local error handler is an event_command_error() event limited to a single command.

Command error handlers are raised in a specific order. Returning False in any of them will invoke the next handler in the chain. If there are no handlers left to call, then the error is printed to stderr (console).

The order goes as follows: 1. The local command error handler is called. (Handler specified by this decorator.) 2. The local cog command error handler is called. 3. All event_command_error() handlers are called simultaneously. If any of them return False, then the error will be printed.

Parameters:

coro – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

property full_parent_name

Retrieves the fully qualified parent command name.

This is the base command name required to execute it. For example, in ?one two three the parent name would be one two.

Type:

str

get_command(name)

Get a Command or subclasses from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

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

Returns:

The command that was requested. If not found, returns None.

Return type:

Command or subclass

group(*args, **kwargs)

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

is_on_cooldown(ctx)

Checks whether the command is currently on cooldown.

Parameters:

ctx (Context) – The invocation context to use when checking the commands cooldown status.

Returns:

A boolean indicating if the command is on cooldown.

Return type:

bool

property parents

Retrieves the parents of this command.

If the command has no parents then it returns an empty list.

For example in commands ?a b c test, the parents are [c, b, a].

Type:

Command

property qualified_case_insensitive

The qualified case insensitive. This means that the it will never return None as it checks inherited values. Could be None but only if the bot is not ultimately registered to the bot yet.

Type:

bool

property qualified_name

Retrieves the fully qualified command name.

This is the full parent name with the command name as well.

For example, in ?one two three the qualified name would be one two three.

Type:

str

remove_check(func)

Removes a check from the command.

This function is idempotent and will not raise an exception if the function is not in the command’s checks.

Parameters:

func – The function to remove from the checks.

remove_command(name)

Remove a Command or subclasses from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

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

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Command or subclass

reset_cooldown(ctx)

Resets the cooldown on this command.

Parameters:

ctx (Context) – The invocation context to reset the cooldown under.

property root_parent

Retrieves the root parent of this command.

If the command has no parents then it returns None.

For example in commands ?a b c test, the root parent is a.

property short_doc

Gets the “short” documentation of a command.

By default, this is the brief attribute. If that lookup leads to an empty string then the first line of the help attribute is used instead.

Type:

str

property signature

Returns a POSIX-like signature useful for help command output.

Type:

str

update(**kwargs)

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

walk_commands()

An iterator that recursively walks through all commands and subcommands.

GroupMixin

class rebootpy.ext.commands.GroupMixin(*args, **kwargs)[source]

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

A mapping of command name to Command or subclass objects.

Type:

dict

case_insensitive

The passed value telling if the commands should be case insensitive. Defaults to None. Use qualified_case_insensitive to check if the command truly is case insensitive.

Type:

Optional[bool]

property qualified_case_insensitive

The qualified case insensitive. This means that the it will never return None as it checks inherited values. Could be None but only if the bot is not ultimately registered to the bot yet.

Type:

bool

property commands

A unique set of commands without aliases that are registered.

Type:

Set[Command]

add_command(command)[source]

Adds a Command or its subclasses into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
  • .ClientException – If the command is already registered.

  • TypeError – If the command passed is not a subclass of Command.

remove_command(name)[source]

Remove a Command or subclasses from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

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

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Command or subclass

walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

get_command(name)[source]

Get a Command or subclasses from the internal list of commands.

This could also be used as a way to get aliases.

The name could be fully qualified (e.g. 'foo bar') will get the subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

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

Returns:

The command that was requested. If not found, returns None.

Return type:

Command or subclass

command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_command().

group(*args, **kwargs)[source]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

Cogs

Cog

class rebootpy.ext.commands.Cog(*args, **kwargs)[source]

The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Cogs page.

When inheriting from this class, the options shown in CogMeta are equally valid here.

get_commands()[source]

Returns a list of Commands that are defined inside this cog.

Note

This does not include subcommands.

property qualified_name

Returns the cog’s specified name, not the class name.

Type:

str

property description

Returns the cog’s description, typically the cleaned docstring.

Type:

str

walk_commands()[source]

An iterator that recursively walks through this cog’s commands and subcommands.

property event_handlers

A list of (name, function) event handler pairs that are defined in this cog.

Type:

list

classmethod event(event=None)[source]

A decorator to register an event.

Usage:

@commands.Cog.event()
async def event_friend_message(message):
    await message.reply('Thanks for your message!')

@commands.Cog.event('friend_message')
async def my_message_handler(message):
    await message.reply('Thanks for your message!')
Raises:
  • TypeError – The decorated function is not a coroutine.

  • TypeError – Event is not specified as argument or function name with event prefix.

cog_unload()[source]

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

This function cannot be a coroutine. It must be a regular function.

Subclasses must replace this if they want special unloading behaviour.

bot_check_once(ctx)[source]

A special method that registers as a Bot.check_once() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

bot_check(ctx)[source]

A special method that registers as a Bot.check() check.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_check(ctx)[source]

A special method that registers as a commands.check() for every command and subcommand in this cog.

This function can be a coroutine and must take a sole parameter, ctx, to represent the Context.

cog_command_error(ctx, error)[source]

A special method that is called whenever an error is dispatched inside this cog.

This is similar to event_command_error() except only applying to the commands inside this cog.

Command error handlers are raised in a specific order. Returning False in any of them will invoke the next handler in the chain. If there are no handlers left to call, the error is printed.

The order goes as follows: 1. The local command error handler is called. (Handler specified by Command.check()) 2. The local cog command error handler is called. (This) 3. All event_command_error() handlers are called simultaneously. If any of them return False, the error will be printed.

This must be a coroutine.

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

  • error (CommandError) – The error that happened.

async cog_before_invoke(ctx)[source]

A special method that acts as a cog local pre-invoke hook.

This is similar to Command.before_invoke().

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

async cog_after_invoke(ctx)[source]

A special method that acts as a cog local post-invoke hook.

This is similar to Command.after_invoke().

This must be a coroutine.

Parameters:

ctx (Context) – The invocation context.

CogMeta

Attributes
class rebootpy.ext.commands.CogMeta(*args, **kwargs)[source]

A metaclass for defining a cog.

Note that you should probably not use this directly. It is exposed purely for documentation purposes.

Note

When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:

class MyCog(commands.Cog, name='My Cog'):
    pass
name

The cog name. By default, it is the name of the class with no modification.

Type:

str

command_attrs

A list of attributes to apply to every command inside this cog. The dictionary is passed into the Command (or its subclass) options at __init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:

class MyCog(commands.Cog, command_attrs=dict(hidden=True)):

    @commands.command()
    async def foo(self, ctx):
        pass # hidden -> True

    @commands.command(hidden=False)
    async def bar(self, ctx):
        pass # hidden -> False
Type:

dict

Help Commands

HelpCommand

class rebootpy.ext.commands.HelpCommand(*args, **kwargs)[source]

The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in discord.py issue 2123.

This means that relying on the state of this class to be the same between command invocations would not work as expected.

context

The context that invoked this help formatter. This is generally set after the help command assigned, command_callback(), has been called.

Type:

Optional[Context]

show_hidden

Specifies if hidden commands should be shown in the output. Defaults to False.

Type:

bool

verify_checks

Specifies if commands should have their Command.checks called and verified. Defaults to True.

Type:

bool

command_attrs

A dictionary of options to pass in for the construction of the help command. This allows you to change the command behaviour without actually changing the implementation of the command. The attributes will be the same as the ones passed in the Command constructor.

Type:

dict

get_bot_mapping()[source]

Retrieves the bot mapping passed to send_bot_help().

property command_prefix

The prefix used to invoke the help command.

property invoked_with

Similar to Context.invoked_with except properly handles the case where Context.send_help() is used.

If the help command was used regularly then this returns the Context.invoked_with attribute. Otherwise, if it the help command was called using Context.send_help() then it returns the internal command name of the help command.

Returns:

The command name that triggered this invocation.

Return type:

str

get_command_signature(command)[source]

Retrieves the signature portion of the help page.

Parameters:

command (Command) – The command to get the signature of.

Returns:

The signature for the command.

Return type:

str

property cog

A property for retrieving or setting the cog for the help command.

When a cog is set for the help command, it is as-if the help command belongs to that cog. All cog special methods will apply to the help command and it will be automatically unset on unload.

To unbind the cog from the help command, you can set it to None.

Returns:

The cog that is currently set for the help command.

Return type:

Optional[Cog]

command_not_found(string)[source]

This function could be a coroutine.

A method called when a command is not found in the help command. This is useful to override for i18n.

Defaults to No command called {0} found.

Parameters:

string (str) – The string that contains the invalid command. Note that this has had mentions removed to prevent abuse.

Returns:

The string to use when a command has not been found.

Return type:

str

subcommand_not_found(command, string)[source]

This function could be a coroutine.

A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n.

Defaults to either:

  • 'Command "{command.qualified_name}" has no subcommands.'
    • If there is no subcommand in the command parameter.

  • 'Command "{command.qualified_name}" has no subcommand named {string}'
    • If the command parameter has subcommands but not one named string.

Parameters:
  • command (Command) – The command that did not have the subcommand requested.

  • string (str) – The string that contains the invalid subcommand.

Returns:

The string to use when the command did not have the subcommand requested.

Return type:

str

async filter_commands(commands, *, sort=False, key=None)[source]

This function is a coroutine.

Returns a filtered list of commands and optionally sorts them.

This takes into account the verify_checks and show_hidden attributes.

Parameters:
  • commands (Iterable[Command]) – An iterable of commands that are getting filtered.

  • sort (bool) – Whether to sort the result.

  • key (Optional[Callable[Command, Any]]) – An optional key function to pass to sorted() that takes a Command as its sole parameter. If sort is passed as True then this will default as the command name.

Returns:

A list of commands that passed the filter.

Return type:

List[Command]

get_max_size(commands)[source]

Returns the largest name length of the specified command list.

Parameters:

commands (Sequence[Command]) – A sequence of commands to check for the largest size.

Returns:

The maximum width of the commands.

Return type:

int

get_destination()[source]

Returns either rebootpy.Friend or rebootpy.ClientParty where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s destination.

async send_error_message(error)[source]

This function is a coroutine.

Handles the implementation when an error happens in the help command. For example, the result of command_not_found() or command_has_no_subcommand_found() will be passed here.

You can override this method to customise the behaviour.

By default, this sends the error message to the destination specified by get_destination().

Note

You can access the invocation context with HelpCommand.context.

Parameters:

error (str) – The error message to display to the user.

async help_command_error_handler(ctx, error)[source]

This function is a coroutine.

The help command’s error handler, as specified by Error Handling.

Useful to override if you need some specific behaviour when the error handler is called.

By default this method does nothing and just propagates to the default error handlers.

Parameters:
  • ctx (Context) – The invocation context.

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

async send_bot_help(page)[source]

This function is a coroutine.

Handles the implementation of the bot command page in the help command. This function is called when the help command is called with no arguments.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context. Also, the commands in the mapping are not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

page (int) – The page to send.

async send_cog_help(cog, page)[source]

This function is a coroutine.

Handles the implementation of the cog page in the help command. This function is called when the help command is called with a cog as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context. To get the commands that belong to this cog see Cog.get_commands(). The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:
  • cog (Cog) – The cog that was requested for help.

  • page (int) – The page to send.

async send_group_help(group)[source]

This function is a coroutine.

Handles the implementation of the group page in the help command. This function is called when the help command is called with a group as the argument.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context. To get the commands that belong to this group without aliases see Group.commands. The commands returned not filtered. To do the filtering you will have to call filter_commands() yourself.

Parameters:

group (Group) – The group that was requested for help.

async send_command_help(command)[source]

This function is a coroutine.

Handles the implementation of the single command page in the help command.

It should be noted that this method does not return anything – rather the actual message sending should be done inside this method. Well behaved subclasses should use get_destination() to know where to send, as this is a customisation point for other users.

You can override this method to customise the behaviour.

Note

You can access the invocation context with HelpCommand.context.

Showing Help

There are certain attributes and methods that are helpful for a help command to show such as the following:

There are more than just these attributes but feel free to play around with these to help you get started to get the output that you want.

Parameters:

command (Command) – The command that was requested for help.

async prepare_help_command(ctx, command=None)[source]

This function is a coroutine.

A low level method that can be used to prepare the help command before it does anything. For example, if you need to prepare some state in your subclass before the command does its processing then this would be the place to do it.

The default implementation does nothing.

Note

This is called inside the help command callback body. So all the usual rules that happen inside apply here as well.

Parameters:
  • ctx (Context) – The invocation context.

  • command (Optional[str]) – The argument passed to the help command.

async command_callback(ctx, *, command=None, page=1)[source]

This function is a coroutine.

The actual implementation of the help command.

It is not recommended to override this method and instead change the behaviour through the methods that actually get dispatched.

FortniteHelpCommand

class rebootpy.ext.commands.FortniteHelpCommand(*args, **kwargs)[source]

The implementation of the default help command.

This inherits from HelpCommand.

It extends it with the following attributes.

dm_help

A tribool that indicates if the help command should DM the user instead of sending it to the channel it received it from. If the boolean is set to True, then all help output is DM’d. If False, none of the help output is DM’d.

Type:

Optional[bool]

paginator

The paginator used to paginate the help command output.

Type:

Paginator

commands_title

The commands title. Defaults to Commands:.

Type:

str

cog_title

The cog title. Defaults to Category:.

Type:

str

usage_title

The usage title. Defaults to Usage:.

Type:

str

description_title

The description title. Defaults to Description:.

Type:

str

help_title

The help title. Defaults to Help:.

Type:

str

sub_commands_title

The sub commands title. Defaults to Help Commands:.

Type:

str

no_category_heading

The text to use as heading if no category (cog) is found for the command. Defaults to No Category.

Type:

str

height

The maximum number of lines to fit. Defaults to 15.

Type:

int

width

The maximum number of characters that fit in a line. Defaults to 60.

Type:

int

indent

How much to indent the commands and other text from a title. Defaults to 4.

Type:

int

title_prefix

The prefix to use for the help title. Defaults to `` +``.

Type:

str

title_suffix

The suffix to use for the help title. Defaults to +.

Type:

str

title_char

The char to use for the help title. Defaults to =.

Type:

str

line_prefix

The prefix to use for all lines. Defaults to `` ``. (Three spaces)

Type:

str

line_suffix

The prefix to use for all lines. Defaults to ````. (Empty)

Type:

str

footer_prefix

The prefix to use for the help footer. Defaults to `` +``.

Type:

str

footer_suffix

The suffix to use for the help footer. Defaults to +.

Type:

str

footer_char

The char to use for the help footer. Defaults to =.

Type:

str

get_command_name(command)[source]

Gets the name of a command.

This method can be overridden for custom text.

Parameters:

command (Command) – The command to get the name for.

Returns:

The command name.
Defaults to self.command_prefix + command.qualified_name

Return type:

str

get_sub_command_name(sub_command)[source]

Gets the name of a sub command.

This method can be overridden for custom text.

Parameters:

sub_command (Command) – The sub command to get the name for.

Returns:

The sub command name.
Defaults to {self.command_prefix} {sub_command.qualified_name}

Return type:

str

get_bot_header(page_num, pages_amount)[source]

Gets the name of a sub command.

This method can be overridden for custom text.

Parameters:
  • page_num (int) – The page being built.

  • pages_amount (int) – The amount of pages available.

Returns:

The sub command name.
Defaults to {self.command_prefix} {sub_command.qualified_name}

Return type:

str

Gets the text to appear in the footer when send_bot_help() is called.

This method can be overridden for custom text.

Parameters:
  • page_num (int) – The page being built.

  • pages_amount (int) – The amount of pages available.

Returns:

The bot footer.
Defaults to ```` (Empty)

Return type:

str

get_command_header(command)[source]

Gets the text to appear in the header when send_command_help() is called.

This method can be overridden for custom text.

Parameters:

command (Command) – The command to get the header for.

Returns:

The header text.
Defaults to Command | {self.command_prefix}{command.qualified_name}

Return type:

str

Gets the text to appear in the footer when send_command_help() is called.

This method can be overridden for custom text.

Parameters:

command (Command) – The command to get the footer for.

Returns:

The footer text.
Defaults to ```` (Empty)

Return type:

str

get_group_header(group)[source]

Gets the text to appear in the header when send_group_help() is called.

This method can be overridden for custom text.

Parameters:

command (Group) – The group to get the header for.

Returns:

The header text.
Defaults to Command | {self.command_prefix}{group.qualified_name}

Return type:

str

Gets the text to appear in the footer when send_group_help() is called.

This method can be overridden for custom text.

Parameters:

command (Group) – The group to get the footer for.

Returns:

The footer text.
Defaults to ```` (Empty)

Return type:

str

get_cog_header(cog, page_num, pages_amount)[source]

Gets the text to appear in the header when send_cog_help() is called.

This method can be overridden for custom text.

Parameters:
  • cog (Cog) – The cog to get the header for.

  • page_num (int) – The page being built.

  • pages_amount (int) – The amount of pages available.

Returns:

The header text.
Defaults to Category | {cog.qualified_name} - {page_num} / {pages_amount}

Return type:

str

Gets the text to appear in the footer when send_cog_help() is called.

This method can be overridden for custom text.

Parameters:
  • cog (Cog) – The cog to get the footer for.

  • page_num (int) – The page being built.

  • pages_amount (int) – The amount of pages available.

Returns:

The footer text.
Defaults to {self.command_prefix}{self.invoked_with} {cog.qualified_name} <page> | {self.command_prefix}{self.invoked_with} <command>

Return type:

str

shorten_text(text, max_len, dot_amount=3)[source]

Shortens text to fit into the width.

async send_pages()[source]

A helper utility to send the page output from paginator to the destination.

async send_page(page_num)[source]

A helper utility to send a page output from paginator to the destination.

get_destination()[source]

Returns either rebootpy.Friend or rebootpy.ClientParty where the help command will be output.

You can override this method to customise the behaviour.

By default this returns the context’s destination.

Paginator

class rebootpy.ext.commands.Paginator(prefix='', suffix='', max_size=10000)[source]

A class that aids in paginating code blocks for Fortnite messages.

len(x)
Returns the total number of characters in the paginator.
prefix

The prefix inserted to every page.

Type:

str

suffix

The suffix appended at the end of every page.

Type:

str

max_size

The maximum amount of codepoints allowed in a page.

Type:

int

clear()[source]

Clears the paginator to have no pages.

add_page(text)[source]

Adds a page to the paginator with no additional checks done.

add_line(line='', *, empty=False)[source]

Adds a line to the current page.

If the line exceeds the max_size then an exception is raised.

Parameters:
  • line (str) – The line to add.

  • empty (bool) – Indicates if another empty line should be added.

Raises:

RuntimeError – The line was too big for the current max_size.

close_page()[source]

Prematurely terminate a page.

property pages

Returns the rendered list of pages.

Enums

class rebootpy.ext.commands.BucketType

Specifies a type of bucket for, e.g. a cooldown.

default

The default bucket operates on a global basis.

user

The user bucket operates on a per-user basis.

Checks

rebootpy.ext.commands.check(predicate)[source]

A decorator that adds a check to the Command or its subclasses. These checks could be accessed via Command.checks.

These checks should be predicates that take in a single parameter taking a Context. If the check returns a False-like value then during invocation a CheckFailure exception is raised and sent to the event_command_error() event.

If an exception should be thrown in the predicate then it should be a subclass of CommandError. Any exception not subclassed from it will be propagated while those subclassed will be sent to event_command_error().

A special attribute named predicate is bound to the value returned by this decorator to retrieve the predicate passed to the decorator.

Note

The function returned by predicate is always a coroutine, even if the original function was not a coroutine.

Examples

Creating a basic check to see if the command invoker is you.

def check_if_it_is_me(ctx):
    return ctx.author.id == "8b6373cbbe7d452b8172b5ee67ad53fa"

@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
    await ctx.send('I know you!')

Transforming common checks into its own decorator:

def is_me():
    def predicate(ctx):
        return ctx.author.id == "8b6373cbbe7d452b8172b5ee67ad53fa"
    return commands.check(predicate)

@bot.command()
@is_me()
async def only_me(ctx):
    await ctx.send('Only you!')
Parameters:

predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

rebootpy.ext.commands.check_any(*checks)[source]

A check() that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then CheckAnyFailure is raised to signal the failure. It inherits from CheckFailure.

Note

The predicate attribute for this function is a coroutine.

Parameters:

*checks (Callable[[Context], bool]) – An argument list of checks that have been decorated with the check() decorator.

Raises:

TypeError – A check passed has not been decorated with the check() decorator.

Examples

Creating a basic check to see if it’s the bot owner or the party leader:

def is_party_leader():
    def predicate(ctx):
        return ctx.party is not None and ctx.author.leader
    return commands.check(predicate)

@bot.command()
@commands.check_any(commands.is_owner(), is_party_leader())
async def only_for_owners(ctx):
    await ctx.send('Hello mister owner!')
rebootpy.ext.commands.cooldown(rate, per, type=BucketType.default)[source]

A decorator that adds a cooldown to a Command or its subclasses.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-user or global basis. Denoted by the third argument of type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in event_command_error() and the local error handler.

A command can only have a single cooldown.

Parameters:
  • rate (int) – The number of times a command can be used before triggering a cooldown.

  • per (float) – The amount of seconds to wait for a cooldown when it’s been triggered.

  • type (BucketType) – The type of cooldown to have.

rebootpy.ext.commands.max_concurrency(number, per=BucketType.default, *, wait=False)[source]

A decorator that adds a maximum concurrency to a Command or its subclasses.

This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.

Parameters:
  • number (int) – The maximum number of invocations of this command that can be running at the same time.

  • per (BucketType) – The bucket that this concurrency is based on, e.g. BucketType.user would allow it to be used up to number times per user.

  • wait (bool) – Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises MaxConcurrencyReached to its error handler. If this is set to True then the command waits until it can be executed.

rebootpy.ext.commands.before_invoke(coro)[source]

A decorator that registers a coroutine as a pre-invoke hook.

This allows you to refer to one before invoke hook for several commands that do not have to be within the same cog.

Example

async def record_usage(ctx):
    print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at)

@bot.command()
@commands.before_invoke(record_usage)
async def who(ctx): # Output: <User> used who at <Time>
    await ctx.send('i am a bot')

class What(commands.Cog):

    @commands.before_invoke(record_usage)
    @commands.command()
    async def who(self, ctx): # Output: <User> used when at <Time>
        await ctx.send('and my name is {}'.format(ctx.bot.user.display_name))

    @commands.command()
    async def where(self, ctx): # Output: <Nothing>
        await ctx.send('on Fortnite')

    @commands.command()
    async def why(self, ctx): # Output: <Nothing>
        await ctx.send('because someone made me')

bot.add_cog(What())
rebootpy.ext.commands.after_invoke(coro)[source]

A decorator that registers a coroutine as a post-invoke hook.

This allows you to refer to one after invoke hook for several commands that do not have to be within the same cog.

rebootpy.ext.commands.party_only()[source]

A check() that indicates this command must only be used in a party context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, PartyMessageOnly that is inherited from CheckFailure.

rebootpy.ext.commands.dm_only()[source]

A check() that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.

This check raises a special exception, PrivateMessageOnly that is inherited from CheckFailure.

rebootpy.ext.commands.is_owner()[source]

A check() that checks if the person invoking this command is the owner of the bot.

This is powered by Bot.is_owner().

This check raises a special exception, NotOwner that is derived from CheckFailure.

Context

class rebootpy.ext.commands.Context(**attrs)[source]

Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

message

The message that triggered the command being executed.

Type:

Union[FriendMessage, PartyMessage]

bot

The bot that contains the command being executed.

Type:

Bot

args

The list of transformed arguments that were passed into the command. If this is accessed during the event_command_error() event then this list could be incomplete.

Type:

list

kwargs

A dictionary of transformed arguments that were passed into the command. Similar to args, if this is accessed in the event_command_error() event then this dict could be incomplete.

Type:

dict

prefix

The prefix that was used to invoke the command.

Type:

str

command

The command (i.e. Command or its subclasses) that is being invoked currently.

invoked_with

The command name that triggered this invocation. Useful for finding out which alias called the command.

Type:

str

invoked_subcommand

The subcommand (i.e. Command or its subclasses) that was invoked. If no valid subcommand was invoked then this is equal to None.

subcommand_passed

The string that was attempted to call a subcommand. This does not have to point to a valid registered subcommand and could just point to a nonsense string. If nothing was passed to attempt a call to a subcommand then this is set to None.

Type:

Optional[str]

command_failed

A boolean that indicates if the command failed to be parsed, checked, or invoked.

Type:

bool

async invoke(*args, **kwargs)[source]

This function is a coroutine.

Calls a command with the arguments given.

This is useful if you want to just call the callback that a Command holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.

Warning

The first parameter passed must be the command being invoked.

Parameters:
  • command (Command) – A command or subclass of a command that is going to be called.

  • *args – The arguments to to use.

  • **kwargs – The keyword arguments to use.

async reinvoke(*, call_hooks=False, restart=True)[source]

This function is a coroutine.

Calls the command again.

This is similar to invoke() except that it bypasses checks, cooldowns, and error handlers.

Note

If you want to bypass UserInputError derived exceptions, it is recommended to use the regular invoke() as it will work more naturally. After all, this will end up using the old arguments the user has used and will thus just fail again.

Parameters:
  • call_hooks (bool) – Whether to call the before and after invoke hooks.

  • restart (bool) – Whether to start the call chain from the very beginning or where we left off (i.e. the command that caused the error). The default is to start where we left off.

property valid

Checks if the invocation context is valid to be invoked with.

Type:

bool

property cog

Returns the cog associated with this context’s command. None if it does not exist.

Type:

Optional[Cog]

property party

The party this message was sent from. None if the message was not sent from a party.

Type:

Optional[rebootpy.ClientParty]

property author

Union[rebootpy.Friend, rebootpy.PartyMember]: The author of the message.

property friend

Optional[rebootpy.Friend]: The rebootpy.Friend object for this friend, None if the client is not friends with the author.

property member

Optional[rebootpy.PartyMember]: The rebootpy.PartyMember object for this friend, None if the client is not in the same party as the author.

property me

Union[rebootpy.ClientPartyMember, rebootpy.ClientUser]: Similar to rebootpy.ClientPartyMember except that it returns rebootpy.ClientUser when not sent from a party.

async send(content)[source]

This function is a coroutine.

Sends a message to the context destination.

Parameters:

content (str) – The contents of the message.

async send_help(entity=<bot>, page=1)[source]

This function is a coroutine.

Shows the help command for the specified entity if given. The entity can be a command or a cog.

If no entity is given, then it’ll show help for the entire bot.

If the entity is a string, then it looks up whether it’s a Cog or a Command.

Note

Due to the way this function works, instead of returning something similar to command_not_found() this returns None on bad input or no help command.

Parameters:
  • entity (Optional[Union[Command, Cog, str]]) – The entity to show help for.

  • page (int) – The page to show. Only has an effect if the entity is either the bot or a cog.

Returns:

The result of the help command, if any.

Return type:

Any

Converters

class rebootpy.ext.commands.Converter[source]

The base class of custom converters that require the Context to be passed to be useful.

This allows you to implement converters that function similar to the special cased rebootpy classes.

Classes that derive from this should override the convert() method to do its conversion logic. This method must be a coroutine.

async convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

class rebootpy.ext.commands.UserConverter[source]

Converts to a User.

The lookup strategy is as follows (in order): 1. Cache lookup by ID. 2. Cache lookup by display name. 3. API Request to fetch the user by id/display name.

async convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

class rebootpy.ext.commands.FriendConverter[source]

Converts to a Friend.

All lookups are via the friend cache.

The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by display name.

async convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

class rebootpy.ext.commands.PartyMemberConverter[source]

Converts to a PartyMember.

All lookups are done via the bots party member cache.

The lookup strategy is as follows (in order): 1. Lookup by ID. 2. Lookup by display name.

async convert(ctx, argument)[source]

This function is a coroutine.

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a CommandError derived exception as it will properly propagate to the error handlers.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

ext.commands.Greedy

A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

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

An invocation of [p]test 1 2 3 4 5 6 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

For more information, check Special Converters.

Exceptions

exception rebootpy.ext.commands.CommandError(message=None, *args)[source]

The base exception type for all command related errors.

This inherits from rebootpy.FortniteException.

This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from Bot, event_command_error().

exception rebootpy.ext.commands.ConversionError(converter, original)[source]

Exception raised when a Converter class raises non-CommandError.

This inherits from CommandError.

converter

The converter that failed.

Type:

rebootpy.ext.commands.Converter

original

The original exception that was raised. You can also get this via the __cause__ attribute.

exception rebootpy.ext.commands.MissingRequiredArgument(param)[source]

Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from UserInputError

param

The argument that is missing.

Type:

inspect.Parameter

exception rebootpy.ext.commands.ArgumentParsingError(message=None, *args)[source]

An exception raised when the parser fails to parse a user’s input.

This inherits from UserInputError.

There are child classes that implement more granular parsing errors for i18n purposes.

exception rebootpy.ext.commands.UnexpectedQuoteError(quote)[source]

An exception raised when the parser encounters a quote mark inside a non-quoted string.

This inherits from ArgumentParsingError.

quote

The quote mark that was found inside the non-quoted string.

Type:

str

exception rebootpy.ext.commands.InvalidEndOfQuotedStringError(char)[source]

An exception raised when a space is expected after the closing quote in a string but a different character is found.

This inherits from ArgumentParsingError.

char

The character found instead of the expected string.

Type:

str

exception rebootpy.ext.commands.ExpectedClosingQuoteError(close_quote)[source]

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type:

str

exception rebootpy.ext.commands.BadArgument(message=None, *args)[source]

Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.

This inherits from UserInputError

exception rebootpy.ext.commands.BadUnionArgument(param, converters, errors)[source]

Exception raised when a typing.Union converter fails for all its associated types.

This inherits from UserInputError

param

The parameter that failed being converted.

Type:

inspect.Parameter

converters

A tuple of converters attempted in conversion, in order of failure.

Type:

Tuple[Type, …]

errors

A list of errors that were caught from failing the conversion.

Type:

List[CommandError]

exception rebootpy.ext.commands.PrivateMessageOnly(message=None)[source]

Exception raised when an operation does not work outside of private message contexts.

This inherits from CheckFailure

exception rebootpy.ext.commands.PartyMessageOnly(message=None)[source]

Exception raised when an operation does not work outside of party message contexts.

This inherits from CheckFailure

exception rebootpy.ext.commands.CheckFailure(message=None, *args)[source]

Exception raised when the predicates in Command.checks have failed.

This inherits from CommandError

exception rebootpy.ext.commands.CheckAnyFailure(checks, errors)[source]

Exception raised when all predicates in check_any() fail.

This inherits from CheckFailure.

errors

A list of errors that were caught during execution.

Type:

List[CheckFailure]

checks

A list of check predicates that failed.

Type:

List[Callable[[Context], bool]]

exception rebootpy.ext.commands.CommandNotFound(message=None, *args)[source]

Exception raised when a command is attempted to be invoked but no command under that name is found.

This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.

This inherits from CommandError.

exception rebootpy.ext.commands.DisabledCommand(message=None, *args)[source]

Exception raised when the command being invoked is disabled.

This inherits from CommandError

exception rebootpy.ext.commands.CommandInvokeError(e)[source]

Exception raised when the command being invoked raised an exception.

This inherits from CommandError

original

The original exception that was raised. You can also get this via the __cause__ attribute.

exception rebootpy.ext.commands.TooManyArguments(message=None, *args)[source]

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

This inherits from UserInputError

exception rebootpy.ext.commands.UserInputError(message=None, *args)[source]

The base exception type for errors that involve errors regarding user input.

This inherits from CommandError.

exception rebootpy.ext.commands.CommandOnCooldown(cooldown, retry_after)[source]

Exception raised when the command being invoked is on cooldown.

This inherits from CommandError

cooldown

A class with attributes rate, per, and type similar to the cooldown() decorator.

Type:

Cooldown

retry_after

The amount of seconds to wait before you can retry again.

Type:

float

exception rebootpy.ext.commands.MaxConcurrencyReached(number, per)[source]

Exception raised when the command being invoked has reached its maximum concurrency.

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type:

int

per

The bucket type passed to the max_concurrency() decorator.

Type:

BucketType

exception rebootpy.ext.commands.NotOwner(message=None, *args)[source]

Exception raised when the message author is not the owner of the bot.

This inherits from CheckFailure

exception rebootpy.ext.commands.ExtensionError(message=None, *args, name)[source]

Base exception for extension related errors.

This inherits from FortniteException.

name

The extension that had an error.

Type:

str

exception rebootpy.ext.commands.ExtensionAlreadyLoaded(name)[source]

An exception raised when an extension has already been loaded.

This inherits from ExtensionError

exception rebootpy.ext.commands.ExtensionNotLoaded(name)[source]

An exception raised when an extension was not loaded.

This inherits from ExtensionError

exception rebootpy.ext.commands.ExtensionMissingEntryPoint(name)[source]

An exception raised when an extension does not have a extension_setup entry point function.

This inherits from ExtensionError

exception rebootpy.ext.commands.ExtensionFailed(name, original)[source]

An exception raised when an extension failed to load during execution of the module or extension_setup entry point.

This inherits from ExtensionError

name

The extension that had the error.

Type:

str

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception rebootpy.ext.commands.ExtensionNotFound(name)[source]

An exception raised when an extension is not found.

This inherits from ExtensionError

name

The extension that had the error.

Type:

str