API Reference¶
The following section outlines the API of fortnitepy’s command extension module.
Bot¶
- blocked_user_count
- blocked_users
- case_insensitive
- cogs
- command_prefix
- commands
- description
- extensions
- friend_count
- friends
- help_command
- incoming_pending_friend_count
- incoming_pending_friends
- outgoing_pending_friend_count
- outgoing_pending_friends
- owner_id
- owner_ids
- pending_friend_count
- pending_friends
- presences
- qualified_case_insensitive
- @after_invoke()
- @before_invoke()
- @check()
- @check_once()
- @command()
- @event()
- @group()
- add_check()
- add_cog()
- add_command()
- add_event_handler()
- get_blocked_user()
- get_cog()
- get_command()
- get_friend()
- get_incoming_pending_friend()
- get_outgoing_pending_friend()
- get_pending_friend()
- get_presence()
- get_user()
- has_friend()
- is_blocked()
- is_closed()
- is_pending()
- is_ready()
- load_extension()
- register_connectors()
- reload_extension()
- remove_check()
- remove_cog()
- remove_command()
- remove_event_handler()
- run()
- unload_extension()
- walk_commands()
- awaitaccept_friend()
- awaitadd_friend()
- awaitblock_user()
- awaitclose()
- awaitfetch_active_ltms()
- awaitfetch_avatars()
- awaitfetch_battlepass_level()
- awaitfetch_blocklist()
- awaitfetch_br_news()
- awaitfetch_br_playlists()
- awaitfetch_br_stats()
- awaitfetch_item_shop()
- awaitfetch_leaderboard()
- awaitfetch_lightswitch_status()
- awaitfetch_multiple_battlepass_levels()
- awaitfetch_multiple_br_stats()
- awaitfetch_multiple_br_stats_collections()
- awaitfetch_party()
- awaitfetch_user()
- awaitfetch_user_by_display_name()
- awaitfetch_user_by_email()
- awaitfetch_users()
- awaitfetch_users_by_display_name()
- awaitget_context()
- awaitget_prefix()
- awaitinvoke()
- awaitis_owner()
- awaitjoin_party()
- awaitprocess_commands()
- awaitremove_or_decline_friend()
- awaitrestart()
- awaitsearch_sac_by_slug()
- awaitsearch_users()
- awaitsend_presence()
- awaitset_platform()
- awaitset_presence()
- awaitstart()
- awaitunblock_user()
- awaitwait_for()
- awaitwait_until_closed()
- awaitwait_until_ready()
-
class
fortnitepy.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
fortnitepy.Client
and as a result anything that you can do with afortnitepy.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
fortnitepy.FriendMessage
orfortnitepy.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
-
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 byis_owner()
and checks that call this method.- Type
Optional[Collection[
int
]]
-
await
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 clientsaiohttp.ClientSession
when logged out.dispatch_close (
bool
) – Whether or not to dispatch the close event.
- Raises
HTTPException – An error occured 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 fromCommandError
.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()
andcheck_once()
.- Parameters
func – The function that was used as a global check.
call_once (
bool
) – If the function should only be called once perCommand.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 withcall_once=True
in theBot.add_check()
call or usingcheck_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 fromCommandError
.Example
@bot.check_once def whitelist(ctx): return ctx.message.author.id in my_whitelist
-
await
is_owner
(user_id)[source]¶ This function is a coroutine.
Checks if a user id is the owner of the bot.
-
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()
andafter_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
CommandError – An error happened during loading.
-
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.
-
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, thebot
.- 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 importfoo/test.py
.- Raises
ExtensionNotFound – The extension could not be imported.
ExtensionAlreadyLoaded – The extension is already loaded.
ExtensionMissingEntryPoint – The extension does not have a extension_setup function.
ExtensionFailed – The extension or its setup function had an execution error.
-
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, thebot
, similar toextension_setup
fromload_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 importfoo/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 aload_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 importfoo/test.py
.- Raises
ExtensionNotLoaded – The extension was not loaded.
ExtensionNotFound – The extension could not be imported.
ExtensionMissingEntryPoint – The extension does not have a extension_setup function.
ExtensionFailed – The extension setup function had an execution error.
-
extensions
¶ A read-only mapping of extension name to extension.
- Type
Mapping[
str
,types.ModuleType
]
-
await
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[
fortnitepy.FriendMessage
,fortnitepy.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
-
await
get_context
(message, *, cls=<class 'fortnitepy.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[
fortnitepy.FriendMessage
,fortnitepy.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 toContext
's interface.
- Returns
The invocation context. The type of this can change via the
cls
parameter.- Return type
-
await
accept_friend
(user_id)[source]¶ 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 occured while requesting to accept this friend.
- Returns
Object of the friend you just added.
- Return type
Friend
-
add_command
(command)[source]¶ Adds a
Command
or its subclasses into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.
-
add_event_handler
(event, coro)[source]¶ Registers a coroutine as an event handler. You can register as many coroutines as you want to a single event.
-
await
add_friend
(user_id)[source]¶ 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 occured while requesting to add this friend.
-
await
block_user
(user_id)[source]¶ 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.
-
blocked_users
¶ A list of the users client has as blocked.
- Type
List[
BlockedUser
]
-
command
(*args, **kwargs)[source]¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.
-
event
(event_or_coro=None)[source]¶ 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 formatevent_<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!')
-
await
fetch_active_ltms
(region)[source]¶ 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 occured while requesting.
- Returns
List of internal playlist names. Returns an empty list of none LTMs are for the specified region.
- Return type
List[
str
]
-
await
fetch_avatars
(users)[source]¶ 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 occured while requesting.
- Returns
A dict containing avatars mapped to their user id.
- Return type
Dict[
str
,Avatar
]
-
await
fetch_battlepass_level
(user_id, *, season, start_time=None, end_time=None)[source]¶ This function is a coroutine.
Fetches a users battlepass level.
- Parameters
user_id (
str
) – The user id to fetch the battlepass level for.season (
int
) –The season number 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 seasons end timestamp in epoch seconds.start_time (Optional[Union[
int
,datetime.datetime
,SeasonStartTimestamp
]]) – The UTC start time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to Noneend_time (Optional[Union[
int
,datetime.datetime
,SeasonEndTimestamp
]]) – The UTC end time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to None
- Raises
Forbidden – User has private career board.
HTTPException – An error occured while requesting.
- Returns
The users 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
]
-
await
fetch_blocklist
()[source]¶ This function is a coroutine.
Retrieves the blocklist with an api call.
- Raises
HTTPException – An error occured while fetching blocklist.
- Returns
List of ids
- Return type
List[
str
]
-
await
fetch_br_news
()[source]¶ This function is a coroutine.
Fetches news for the Battle Royale gamemode.
- Raises
HTTPException – An error occured when requesting.
- Returns
List[
BattleRoyaleNewsPost
]- Return type
-
await
fetch_br_playlists
()[source]¶ 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 occured while requesting.
- Returns
List containing all playlists registered on Fortnite.
- Return type
List[
Playlist
]
-
await
fetch_br_stats
(user_id, *, start_time=None, end_time=None)[source]¶ This function is a coroutine.
Gets Battle Royale stats 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
,SeasonStartTimestamp
]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to Noneend_time (Optional[Union[
int
,datetime.datetime
,SeasonEndTimestamp
]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to None
- Raises
- 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 occured while requesting.
- Returns
An object representing the stats for this user. If the user was not found
None
is returned.- Return type
StatsV2
-
await
fetch_item_shop
()[source]¶ 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 occured when requesting.
- Returns
Object representing the data from the current item shop.
- Return type
Store
-
await
fetch_leaderboard
(stat)[source]¶ 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 = fortnitepy.StatsV2.create_stat( 'wins', fortnitepy.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 useStatsV2.create_stat()
to create this string.- Raises
ValueError – You passed an invalid/non-accepted stat argument.
HTTPException – An error occured when requesting.
- Returns
List of dictionaries containing entry data. Example return:
{ 'account': '4480a7397f824fe4b407077fb9397fbb', 'value': 5082 }
- Return type
-
await
fetch_lightswitch_status
(service_id='Fortnite')[source]¶ 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 occured when requesting.
- Returns
True
if service is up elseFalse
- Return type
-
await
fetch_multiple_battlepass_levels
(users, season, *, start_time=None, end_time=None)[source]¶ This function is a coroutine.
Fetches multiple users battlepass level.
- Parameters
users (List[
str
]) – List of user ids.season (
int
) –The season number to request the battlepass levels 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 seasons end timestamp in epoch seconds.start_time (Optional[Union[
int
,datetime.datetime
,SeasonStartTimestamp
]]) – The UTC start time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to Noneend_time (Optional[Union[
int
,datetime.datetime
,SeasonEndTimestamp
]]) – The UTC end time of the window to get the battlepass level from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to None
- Raises
HTTPException – An error occured 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, he/she 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 users 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 permissions to requests their stats.
- Return type
-
await
fetch_multiple_br_stats
(user_ids, stats, *, start_time=None, end_time=None)[source]¶ 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 = [ fortnitepy.StatsV2.create_stat('placetop1', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'), fortnitepy.StatsV2.create_stat('kills', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'), fortnitepy.StatsV2.create_stat('matchesplayed', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo') ] # get the users and create a list of their ids. users = await self.fetch_users(['Ninja', 'DrLupo']) user_ids = [u.id for u in users] + ['NonValidUserIdForTesting'] 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.'.format(id)) # 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: 4735ce9132924caf8a5b17789b40f79c | Stats: {'keyboardmouse': {'defaultsolo': {'wins': 1888, 'kills': 40784, 'matchesplayed': 5775}}} # 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:
[ fortnitepy.StatsV2.create_stat('placetop1', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'), fortnitepy.StatsV2.create_stat('kills', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo'), fortnitepy.StatsV2.create_stat('matchesplayed', fortnitepy.V2Input.KEYBOARDANDMOUSE, 'defaultsolo') ]
start_time (Optional[Union[
int
,datetime.datetime
,SeasonStartTimestamp
]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to Noneend_time (Optional[Union[
int
,datetime.datetime
,SeasonEndTimestamp
]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to None
- Raises
HTTPException – An error occured 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 beNone
.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 requests their stats.
- Return type
Dict[
str
, Optional[StatsV2
]]
-
await
fetch_multiple_br_stats_collections
(user_ids, collection=None, *, start_time=None, end_time=None)[source]¶ 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
,SeasonStartTimestamp
]]) – The UTC start time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to Noneend_time (Optional[Union[
int
,datetime.datetime
,SeasonEndTimestamp
]]) – The UTC end time of the time period to get stats from. Must be seconds since epoch, :class:`datetime.datetime` or a constant from SeasonEndTimestamp Defaults to None
- Raises
HTTPException – An error occured while requesting.
- Returns
A mapping where
StatsCollection
is bound to its owners id. If a userid was not found then the value bound to that userid will beNone
.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 requests their stats.
- Return type
Dict[
str
, Optional[StatsCollection
]]
-
await
fetch_user
(user, *, cache=False, raw=False)[source]¶ This function is a coroutine.
Fetches a single user by the given id/displayname.
- Parameters
user (
str
) – Id or display namecache (
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 occured while requesting the user.
- Returns
The user requested. If not found it will return
None
- Return type
Optional[
User
]
-
await
fetch_user_by_display_name
(display_name, *, cache=False, raw=False)[source]¶ 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 occured while requesting the user.
- Returns
The user requested. If not found it will return
None
.- Return type
Optional[
User
]
-
await
fetch_user_by_email
(email, *, cache=False, raw=False)[source]¶ This function is a coroutine.
Fetches a single user by the email.
Warning
Because of epicgames throttling policy, you can only do this request three times in a timespan of 600 seconds. If you were to do more than three requests in that timespan, a
HTTPException
would be raised.- Parameters
email (
str
) – The email of the account you are requesting.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
This method does two api requests but with this set to False only one request will be done as long as the user is found in one of the caches.
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 occured while requesting the user.
- Returns
The user requested. If not found it will return
None
- Return type
Optional[
User
]
-
await
fetch_users
(users, *, cache=False, raw=False)[source]¶ 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 occured while requesting user information.
- Returns
Users requested. Only users that are found gets returned.
- Return type
List[
User
]
-
await
fetch_users_by_display_name
(display_name, *, raw=False)[source]¶ 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
- Raises
HTTPException – An error occured while requesting the user.
- Returns
A list containing all payloads found for this user.
- Return type
List[
User
]
-
friends
¶ A list of the clients friends.
- Type
List[
Friend
]
-
get_blocked_user
(user_id)[source]¶ 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)[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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
get_friend
(user_id)[source]¶ 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)[source]¶ 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)[source]¶ 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)[source]¶ 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, elseNone
-
get_presence
(user_id)[source]¶ 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)[source]¶ 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)[source]¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.
-
incoming_pending_friend_count
¶ The amount of active incoming pending friends the bot currently has received.
- Type
-
incoming_pending_friends
¶ A list of the clients incoming pending friends.
- Type
List[
IncomingPendingFriend
]
-
is_ready
()[source]¶ Specifies if the internal state of the client is ready.
- Returns
True
if the internal state is ready elseFalse
- Return type
-
await
join_party
(party_id)[source]¶ 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
-
outgoing_pending_friend_count
¶ The amount of active outgoing pending friends the bot has sent.
- Type
-
outgoing_pending_friends
¶ A list of the clients outgoing pending friends.
- Type
List[
OutgoingPendingFriend
]
-
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
oroutgoing
.
-
presences
¶ A list of the last presences from currently online friends.
- Type
List[
Presence
]
-
qualified_case_insensitive
¶ The qualified case insensitive. This means that the it will never return
None
as it checks inherited values. Could beNone
but only if the bot is not ultimately registered to the bot yet.- Type
-
register_connectors
(http_connector=None, ws_connector=None)[source]¶ 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 inevent_before_start()
.Warning
Connectors passed will not be closed on shutdown. You must close them yourself if you want a graceful shutdown.
- Parameters
http_connector (
aiohttp.BaseConnector
) – The connector to use for the http session.ws_connector (
aiohttp.BaseConnector
) – The connector to use for the websocket xmpp connection.
-
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.
-
await
remove_or_decline_friend
(user_id)[source]¶ 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.
-
await
restart
()[source]¶ 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 occured while logging in.
-
run
()[source]¶ This function starts the loop and then calls
start()
for you. If your program already has an asyncio loop setup, you should usestart()
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 occured while logging in.
-
await
search_sac_by_slug
(slug)[source]¶ 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 occured while requesting fortnite’s services.
- Returns
An ordered list of users who matched the exact or slightly modified slug.
- Return type
List[
SacSearchEntryUser
]
-
await
search_users
(prefix, platform)[source]¶ 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 otherusers which have display names that start with or match exactly to
Tfue
likeTfue_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 occured while requesting.
- Returns
An ordered list of users that matched the prefix.
- Return type
List[
UserSearchEntry
]
-
await
send_presence
(status, *, away=<AwayStatus.ONLINE: None>, to=None)[source]¶ This function is a coroutine.
Sends this status to all or one single friend.
- Parameters
status (Union[
str
,dict
]) – The status message instr
or full status indict
.away (
AwayStatus
) – The away status to use. Defaults toAwayStatus.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.
-
await
set_platform
(platform)[source]¶ This function is a coroutine.
Sets and updates the clients platform. This method is slow (~2-3s) as changing platform requires a full authentication refresh.
- Parameters
platform (
Platform
) – The platform to set.- Raises
HTTPException – An error occurred when requesting.
-
set_presence
(status, *, away=<AwayStatus.ONLINE: None>)[source]¶ This function is a coroutine.
Sends and sets the status. This status message will override all other presence statuses including party presence status.
-
start
(dispatch_ready=True)[source]¶ 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 occured while logging in.
-
await
unblock_user
(user_id)[source]¶ 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)[source]¶ 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 theevent_
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 <fortnitepy-events-api> for more information about the returning arguments.
- Return type
Any
-
await
wait_until_closed
()[source]¶ This function is a coroutine.
Waits until the client is fully closed.
-
await
wait_until_ready
()[source]¶ This function is a coroutine.
Waits until the internal state of the client is ready.
-
for ... in
walk_commands
()[source]¶ An iterator that recursively walks through all commands and subcommands.
-
await
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.
-
await
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 toinvoke()
.- Parameters
message (Union[
fortnitepy.FriendMessage
,fortnitepy.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.
-
fortnitepy.
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. Allevent_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.
Command¶
command()¶
-
fortnitepy.ext.commands.
command
(name=None, cls=None, **attrs)[source]¶ A decorator that transforms a function into a
Command
or if called withgroup()
,Group
.By default the
help
attribute is received automatically from the docstring of the function and is cleaned up with the use ofinspect.cleandoc
. If the docstring isbytes
, then it is decoded intostr
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
- Raises
TypeError – If the function is not a coroutine or is already a command.
group()¶
Command¶
-
class
fortnitepy.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.
-
callback
¶ The coroutine that is executed when the command is called.
-
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
-
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 theevent_command_error()
event. Defaults toTrue
.- Type
-
parent
¶ The parent command that this command belongs to.
None
if there isn’t one.- Type
Optional[
Command
]
-
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 fromCommandError
should be used. Note that if the checks fail thenCheckFailure
exception is raised to theevent_command_error()
event.- Type
List[Callable[…,
bool
]]
If
True
, the default help command does not show this in the help output.- Type
-
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 handlesMissingRequiredArgument
and default values in a regular matter rather than passing the rest completely raw. IfTrue
then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults toFalse
.- Type
-
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 expectinga
andb
). Otherwiseevent_command_error()
and local error handlers are called withTooManyArguments
. Defaults toTrue
.- Type
-
cooldown_after_parsing
¶ If
True
, cooldown processing is done after argument parsing, which calls converters. IfFalse
then cooldown processing is done first and then the converters are called second. Defaults toFalse
.- Type
-
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 theCommand
or subclass constructors, sans the name and callback.
-
await
__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.
-
clean_params
¶ Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
- Type
OrderedDict[
str
,typing.Parameter
]
-
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 beone two
.- Type
-
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
-
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 isa
.
-
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 beone two three
.- Type
-
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
. SeeBot.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
. SeeBot.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.
-
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 thehelp
attribute is used instead.- Type
-
await
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
-
Group¶
-
class
fortnitepy.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 inCommand
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 toFalse
.- 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)[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.
-
add_command
(command)[source]¶ Adds a
Command
or its subclasses into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.
-
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
. SeeBot.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)[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
. SeeBot.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.
-
await
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
-
clean_params
¶ Retrieves the parameter OrderedDict without the context or self parameters.
Useful for inspecting signature.
- Type
OrderedDict[
str
,typing.Parameter
]
-
command
(*args, **kwargs)[source]¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.
-
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.
-
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 beone two
.- Type
-
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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
group
(*args, **kwargs)[source]¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.
-
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
-
qualified_case_insensitive
¶ The qualified case insensitive. This means that the it will never return
None
as it checks inherited values. Could beNone
but only if the bot is not ultimately registered to the bot yet.- Type
-
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 beone two three
.- Type
-
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.
-
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.
-
reset_cooldown
(ctx)[source]¶ Resets the cooldown on this command.
- Parameters
ctx (
Context
) – The invocation context to reset the cooldown under.
-
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 isa
.
-
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 thehelp
attribute is used instead.- Type
-
GroupMixin¶
-
class
fortnitepy.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.-
case_insensitive
¶ The passed value telling if the commands should be case insensitive. Defaults to
None
. Usequalified_case_insensitive
to check if the command truly is case insensitive.- Type
Optional[
bool
]
-
qualified_case_insensitive
¶ The qualified case insensitive. This means that the it will never return
None
as it checks inherited values. Could beNone
but only if the bot is not ultimately registered to the bot yet.- Type
-
add_command
(command)[source]¶ Adds a
Command
or its subclasses into the internal list of commands.This is usually not called, instead the
command()
orgroup()
shortcut decorators are used instead.
-
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.
-
for ... in
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 subcommandbar
of the group commandfoo
. If a subcommand is not found thenNone
is returned just as usual.
-
command
(*args, **kwargs)[source]¶ A shortcut decorator that invokes
command()
and adds it to the internal command list viaadd_command()
.
-
group
(*args, **kwargs)[source]¶ A shortcut decorator that invokes
group()
and adds it to the internal command list viaadd_command()
.
-
Cogs¶
Cog¶
-
class
fortnitepy.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
ofCommand
s that are defined inside this cog.Note
This does not include subcommands.
-
for ... in
walk_commands
()[source]¶ An iterator that recursively walks through this cog’s commands and subcommands.
-
event_handlers
¶ A list of (name, function) event handler pairs that are defined in this cog.
- Type
-
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!')
-
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 theContext
.
-
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 theContext
.
-
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 theContext
.
-
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. Allevent_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.
-
await
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.
-
await
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¶
-
class
fortnitepy.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
-
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
-
Help Commands¶
HelpCommand¶
- command_not_found()
- get_bot_mapping()
- get_command_signature()
- get_destination()
- get_max_size()
- subcommand_not_found()
- awaitcommand_callback()
- awaitfilter_commands()
- awaithelp_command_error_handler()
- awaitprepare_help_command()
- awaitsend_bot_help()
- awaitsend_cog_help()
- awaitsend_command_help()
- awaitsend_error_message()
- awaitsend_group_help()
-
class
fortnitepy.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
]
Specifies if hidden commands should be shown in the output. Defaults to
False
.- Type
-
verify_checks
¶ Specifies if commands should have their
Command.checks
called and verified. Defaults toTrue
.- Type
-
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
-
get_bot_mapping
()[source]¶ Retrieves the bot mapping passed to
send_bot_help()
.
-
command_prefix
¶ The prefix used to invoke the help command.
-
invoked_with
¶ Similar to
Context.invoked_with
except properly handles the case whereContext.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 usingContext.send_help()
then it returns the internal command name of the help command.- Returns
The command name that triggered this invocation.
- Return type
-
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.
-
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 namedstring
.
-
await
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
andshow_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 tosorted()
that takes aCommand
as its sole parameter. Ifsort
is passed asTrue
then this will default as the command name.
- Returns
A list of commands that passed the filter.
- Return type
List[
Command
]
-
get_destination
()[source]¶ Returns either
fortnitepy.Friend
orfortnitepy.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.
-
await
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()
orcommand_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.
-
await
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.
-
await
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 callfilter_commands()
yourself.- Parameters
page (
int
) – The page to send.
-
await
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 seeCog.get_commands()
. The commands returned not filtered. To do the filtering you will have to callfilter_commands()
yourself.
-
await
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 seeGroup.commands
. The commands returned not filtered. To do the filtering you will have to callfilter_commands()
yourself.- Parameters
group (
Group
) – The group that was requested for help.
-
await
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.
-
await
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.
-
FortniteHelpCommand¶
-
class
fortnitepy.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. IfFalse
, none of the help output is DM’d.- Type
Optional[
bool
]
-
no_category_heading
¶ The text to use as heading if no category (cog) is found for the command. Defaults to
No Category
.- Type
The prefix to use for the help footer. Defaults to `` +``.
- Type
The suffix to use for the help footer. Defaults to
+
.- Type
The char to use for the help footer. Defaults to
=
.- Type
-
get_command_name
(command)[source]¶ Gets the name of a command.
This method can be overridden for custom text.
-
get_sub_command_name
(sub_command)[source]¶ Gets the name of a sub command.
This method can be overridden for custom text.
-
get_bot_header
(page_num, pages_amount)[source]¶ Gets the name of a sub command.
This method can be overridden for custom text.
Gets the text to appear in the footer when
send_bot_help()
is called.This method can be overridden for custom text.
-
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.
Gets the text to appear in the footer when
send_command_help()
is called.This method can be overridden for custom text.
-
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.
Gets the text to appear in the footer when
send_group_help()
is called.This method can be overridden for custom text.
-
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.
Gets the text to appear in the footer when
send_cog_help()
is called.This method can be overridden for custom text.
- Parameters
- 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
-
await
send_pages
()[source]¶ A helper utility to send the page output from
paginator
to the destination.
-
await
send_page
(page_num)[source]¶ A helper utility to send a page output from
paginator
to the destination.
-
get_destination
()[source]¶ Returns either
fortnitepy.Friend
orfortnitepy.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
fortnitepy.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.
-
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
- Raises
RuntimeError – The line was too big for the current
max_size
.
-
pages
¶ Returns the rendered list of pages.
-
Enums¶
Checks¶
-
fortnitepy.ext.commands.
check
(predicate)[source]¶ A decorator that adds a check to the
Command
or its subclasses. These checks could be accessed viaCommand.checks
.These checks should be predicates that take in a single parameter taking a
Context
. If the check returns aFalse
-like value then during invocation aCheckFailure
exception is raised and sent to theevent_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 toevent_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!')
-
fortnitepy.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 fromCheckFailure
.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 thecheck()
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!')
-
fortnitepy.ext.commands.
cooldown
(rate, per, type=<BucketType.default: 0>)[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 typeBucketType
.If a cooldown is triggered, then
CommandOnCooldown
is triggered inevent_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.
-
fortnitepy.ext.commands.
max_concurrency
(number, per=<BucketType.default: 0>, *, 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 tonumber
times per user.wait (
bool
) – Whether the command should wait for the queue to be over. If this is set toFalse
then instead of waiting until the command can run again, the command raisesMaxConcurrencyReached
to its error handler. If this is set toTrue
then the command waits until it can be executed.
-
fortnitepy.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())
-
fortnitepy.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.
-
fortnitepy.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 fromCheckFailure
.
-
fortnitepy.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 fromCheckFailure
.
-
fortnitepy.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 fromCheckFailure
.
Context¶
- awaitinvoke()
- awaitreinvoke()
- awaitsend()
- awaitsend_help()
-
class
fortnitepy.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
]
-
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
-
kwargs
¶ A dictionary of transformed arguments that were passed into the command. Similar to
args
, if this is accessed in theevent_command_error()
event then this dict could be incomplete.- Type
-
invoked_with
¶ The command name that triggered this invocation. Useful for finding out which alias called the command.
- Type
-
invoked_subcommand
¶ The subcommand (i.e.
Command
or its subclasses) that was invoked. If no valid subcommand was invoked then this is equal toNone
.
-
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
-
await
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.
-
await
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 regularinvoke()
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.
-
cog
¶ Returns the cog associated with this context’s command.
None
if it does not exist.- Type
Optional[
Cog
]
-
party
¶ The party this message was sent from.
None
if the message was not sent from a party.- Type
Optional[
fortnitepy.ClientParty
]
Optional[
fortnitepy.Friend
,fortnitepy.PartyMember
]: The author of the message.
-
me
¶ Union[
fortnitepy.ClientPartyMember
,fortnitepy.ClientUser
]: Similar tofortnitepy.ClientPartyMember
except that it returnsfortnitepy.ClientUser
when not sent from a party.
-
await
send
(content)[source]¶ This function is a coroutine.
Sends a message to the context destination.
- Parameters
content (
str
) – The contents of the message.
-
await
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 aCommand
.Note
Due to the way this function works, instead of returning something similar to
command_not_found()
this returnsNone
on bad input or no help command.
-
Converters¶
-
class
fortnitepy.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
fortnitepy
classes.Classes that derive from this should override the
convert()
method to do its conversion logic. This method must be a coroutine.-
await
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.
-
await
-
class
fortnitepy.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.
-
await
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.
-
await
-
class
fortnitepy.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.
-
await
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.
-
await
-
class
fortnitepy.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.
-
await
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.
-
await
-
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 passnumbers
with[1, 2, 3, 4, 5, 6]
andreason
withhello
.For more information, check Special Converters.
Exceptions¶
-
exception
fortnitepy.ext.commands.
CommandError
(message=None, *args)[source]¶ The base exception type for all command related errors.
This inherits from
fortnitepy.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
fortnitepy.ext.commands.
ConversionError
(converter, original)[source]¶ Exception raised when a Converter class raises non-CommandError.
This inherits from
CommandError
.-
converter
¶ The converter that failed.
-
original
¶ The original exception that was raised. You can also get this via the
__cause__
attribute.
-
-
exception
fortnitepy.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
-
-
exception
fortnitepy.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
fortnitepy.ext.commands.
UnexpectedQuoteError
(quote)[source]¶ An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from
ArgumentParsingError
.
-
exception
fortnitepy.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
.
-
exception
fortnitepy.ext.commands.
ExpectedClosingQuoteError
(close_quote)[source]¶ An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError
.
-
exception
fortnitepy.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
fortnitepy.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
-
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
fortnitepy.ext.commands.
PrivateMessageOnly
(message=None)[source]¶ Exception raised when an operation does not work outside of private message contexts.
This inherits from
CheckFailure
-
exception
fortnitepy.ext.commands.
PartyMessageOnly
(message=None)[source]¶ Exception raised when an operation does not work outside of party message contexts.
This inherits from
CheckFailure
-
exception
fortnitepy.ext.commands.
CheckFailure
(message=None, *args)[source]¶ Exception raised when the predicates in
Command.checks
have failed.This inherits from
CommandError
-
exception
fortnitepy.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
]
-
-
exception
fortnitepy.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
fortnitepy.ext.commands.
DisabledCommand
(message=None, *args)[source]¶ Exception raised when the command being invoked is disabled.
This inherits from
CommandError
-
exception
fortnitepy.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
fortnitepy.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 toTrue
.This inherits from
UserInputError
-
exception
fortnitepy.ext.commands.
UserInputError
(message=None, *args)[source]¶ The base exception type for errors that involve errors regarding user input.
This inherits from
CommandError
.
-
exception
fortnitepy.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
, andtype
similar to thecooldown()
decorator.- Type
Cooldown
-
-
exception
fortnitepy.ext.commands.
MaxConcurrencyReached
(number, per)[source]¶ Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError
.-
per
¶ The bucket type passed to the
max_concurrency()
decorator.- Type
BucketType
-
-
exception
fortnitepy.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
fortnitepy.ext.commands.
ExtensionError
(message=None, *args, name)[source]¶ Base exception for extension related errors.
This inherits from
FortniteException
.
-
exception
fortnitepy.ext.commands.
ExtensionAlreadyLoaded
(name)[source]¶ An exception raised when an extension has already been loaded.
This inherits from
ExtensionError
-
exception
fortnitepy.ext.commands.
ExtensionNotLoaded
(name)[source]¶ An exception raised when an extension was not loaded.
This inherits from
ExtensionError
-
exception
fortnitepy.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
fortnitepy.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
-
exception
fortnitepy.ext.commands.
ExtensionNotFound
(name)[source]¶ An exception raised when an extension is not found.
This inherits from
ExtensionError