### start Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Starts the client and logs into the specified user. This is a blocking coroutine that should be called after all other setup. It dispatches the ready event when the client is ready. ```APIDOC ## start ### Description Starts the client and logs into the specified user. This is a blocking coroutine that should be called after all other setup. It dispatches the ready event when the client is ready. ### Method async def start(self, dispatch_ready: bool = True) -> None ### Parameters - **dispatch_ready** (bool) - Optional - Whether or not the client should dispatch the ready event when ready. ### Raises - **AuthException** - Raised if invalid credentials in any form was passed or some other misc failure. - **HTTPException** - A request error occurred while logging in. ### Notes - This function is blocking and everything after the line calling this function will never run. - If using this function instead of run(), always call it after everything else. - When the client is ready it will dispatch event_ready. ``` -------------------------------- ### Install fortnitepy on Windows Source: https://fortnitepy.readthedocs.io/en/stable/intro.html Install fortnitepy using the Windows Python launcher. Requires Python 3.5 or higher. ```bash py -3 -m pip install fortnitepy ``` -------------------------------- ### Install fortnitepy on Linux Source: https://fortnitepy.readthedocs.io/en/stable/intro.html Install fortnitepy using python3 on Linux. Requires Python 3.5 or higher. ```bash python3 -m pip install fortnitepy ``` -------------------------------- ### Example stats list for fetch_multiple_br_stats Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Example of a stats list parameter for fetch_multiple_br_stats, created using StatsV2.create_stat. ```python [ 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_client async function to start the fortnitepy client Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Starts the client and waits until it is ready, handling errors and optional callbacks. Raises TypeError if client is not a fortnitepy.Client instance. ```python async def _start_client(client: 'Client', *, shutdown_on_error: bool = True, after: Optional[MaybeCoro] = None, error_after: Optional[MaybeCoro] = None, ) -> None: loop = asyncio.get_event_loop() if not isinstance(client, Client): raise TypeError('client must be an instance of fortnitepy.Client') async def starter(): try: await client.start() except Exception as e: return e tasks = ( loop.create_task(starter()), loop.create_task(client.wait_until_ready()) ) try: done, pending = await asyncio.wait( tasks, return_when=asyncio.FIRST_COMPLETED ) except asyncio.CancelledError: for task in tasks: task.cancel() else: done_task = done.pop() e = done_task.result() if e is not None: await client.close() identifier = client.auth.identifier ``` -------------------------------- ### Basic check example using commands.check Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/core.html Example from the check decorator docstring showing how to create a basic check that verifies the command invoker's ID. ```python 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!') ``` -------------------------------- ### hello.py - Example extension with a command Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/extensions.html Defines a simple command 'hello' and registers it in the extension_setup function. The extension_setup function is called when the extension is loaded, and it adds the command to the bot. ```python from fortnitepy.ext import commands @commands.command() async def hello(ctx): await ctx.send('Hello {0.display_name}.'.format(ctx.author)) def extension_setup(bot): bot.add_command(hello) ``` -------------------------------- ### stats_get_v2 - Get stats for a user Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/http.html Asynchronous method to fetch stats for a single user, optionally filtered by start and end time. Uses StatsproxyPublicService and the GET HTTP method. ```python async def stats_get_v2(self, user_id: str, *, start_time: Optional[int] = None, end_time: Optional[int] = None) -> dict: params = {} if start_time: params['startTime'] = start_time if end_time: params['endTime'] = end_time r = StatsproxyPublicService( '/statsproxy/api/statsv2/account/{user_id}', user_id=user_id ) return await self.get(r, params=params) ``` -------------------------------- ### await Client.start() Source: https://fortnitepy.readthedocs.io/en/stable/api.html Starts the client. ```APIDOC ## await Client.start() ### Description Starts the client. ``` -------------------------------- ### basic_ext.py - Extension setup and teardown Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/extensions.html Demonstrates the extension_setup and cog_teardown entry points. extension_setup is called when the extension is loaded, and cog_teardown is called when it is unloaded, allowing for cleanup. ```python def extension_setup(bot): print('I am being loaded!') def cog_teardown(bot): print('I am being unloaded!') ``` -------------------------------- ### Get event handlers with get_listeners() Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/cogs.html Use Cog.get_listeners() to retrieve a list of tuples containing listener name and function. The example prints each listener name and its function. ```python >>> for name, func in cog.get_listeners(): ... print(name, '->', func) ``` -------------------------------- ### Get win percentage for Ninja in solo touch Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/stats.html Example of using the client to fetch a user's stats and calculate win percentage for a specific input and playlist. ```python async def get_ninja_touch_solo_winpercentage(): user = await client.fetch_user('Ninja') stats = await client.fetch_br_stats(user.id) return stats.get_winpercentage(stats.get_stats()['touch']['defaultsolo']) ``` -------------------------------- ### HelpCommand.prepare_help_command() Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/api.html Prepares the help command before it is invoked. This method can be overridden to perform setup actions. ```APIDOC ## HelpCommand.prepare_help_command() ### Description Prepares the help command before it is invoked. This method can be overridden to perform setup actions. ### Method prepare_help_command ### Parameters - **ctx** (Context) - Required - The invocation context. - **command** (Optional[str]) - Optional - The command name that was requested. ### Returns None ``` -------------------------------- ### Client initialization with configuration defaults Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Initializes the Client with configurable options such as status, platform, build, and XMPP settings. Sets up HTTP and XMPP clients, internal state, and event listeners. ```python self.status = kwargs.get('status', 'Battle Royale Lobby - {party_size} / {party_max_size}') # noqa self.away = kwargs.get('away', AwayStatus.ONLINE) self.avatar = kwargs.get('avatar', get_random_default_avatar()) # noqa self.platform = kwargs.get('platform', Platform.WINDOWS) self.net_cl = kwargs.get('net_cl', '') self.party_version = kwargs.get('party_version', 3) self.party_build_id = '1:{0.party_version}:{0.net_cl}'.format(self) self.default_party_config = kwargs.get('default_party_config', DefaultPartyConfig()) # noqa self.default_party_member_config = kwargs.get('default_party_member_config', DefaultPartyMemberConfig()) # noqa self.build = kwargs.get('build', '++Fortnite+Release-14.10-CL-14288110') # noqa self.os = kwargs.get('os', 'Windows/10.0.17134.1.768.64bit') self.service_host = kwargs.get('xmpp_host', 'prod.ol.epicgames.com') self.service_domain = kwargs.get('xmpp_domain', 'xmpp-service-prod.ol.epicgames.com') # noqa self.service_port = kwargs.get('xmpp_port', 5222) self.cache_users = kwargs.get('cache_users', True) self.fetch_user_data_in_events = kwargs.get('fetch_user_data_in_events', True) # noqa self.wait_for_member_meta_in_events = kwargs.get('wait_for_member_meta_in_events', True) # noqa self.kill_other_sessions = True self.accept_eula = True self.event_prefix = 'event_' self.auth = auth self.auth.initialize(self) self.http = HTTPClient( self, connector=kwargs.get('connector'), retry_config=kwargs.get('http_retry_config') ) self.http.add_header('Accept-Language', 'en-EN') self.xmpp = XMPPClient(self, ws_connector=kwargs.get('ws_connector')) self.party = None self._listeners = {} self._events = {} self._friends = {} self._pending_friends = {} self._users = {} self._blocked_users = {} self._presences = {} self._exception_future = self.loop.create_future() self._ready_event = asyncio.Event() self._closed_event = asyncio.Event() self._join_party_lock = LockEvent() self._internal_join_party_lock = LockEvent() self._reauth_lock = LockEvent() self._reauth_lock.failed = False self._refresh_task = None self._start_runner_task = None self._closed = False self._closing = False self._restarting = False self._first_start = True self._join_confirmation = False self._refresh_times = [] self.setup_internal() ``` -------------------------------- ### Get a list of commands from a cog Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/cogs.html Use Cog.get_commands() to retrieve a list of commands from a cog instance. The example shows retrieving the cog via bot.get_cog('Greetings') and printing command names. ```python >>> cog = bot.get_cog('Greetings') >>> commands = cog.get_commands() >>> print([c.name for c in commands]) ``` -------------------------------- ### Get Ninja's touch solo winpercentage using StatsV2.get_winpercentage Source: https://fortnitepy.readthedocs.io/en/stable/api.html Usage example for StatsV2.get_winpercentage. Fetches a user by name, retrieves their Battle Royale stats, and returns the winpercentage for the 'touch' 'defaultsolo' gamemode. The data dict must include 'matchesplayed' and 'wins'. ```python # gets ninjas winpercentage in solo on input touch async def get_ninja_touch_solo_winpercentage(): user = await client.fetch_user('Ninja') stats = await client.fetch_br_stats(user.id) return stats.get_winpercentage(stats.get_stats()['touch']['defaultsolo']) ``` -------------------------------- ### FortniteHelpCommand.__init__ Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/help.html Constructor for FortniteHelpCommand. Initializes the help command with various options for formatting and behavior. ```APIDOC ## FortniteHelpCommand.__init__ ### Description Initializes a new FortniteHelpCommand instance with configurable options for help output formatting and behavior. ### Method Constructor ### Parameters #### Options (keyword arguments) - **dm_help** (Optional[bool]) - Optional - If True, help output is sent via DM; otherwise sent to the channel. - **paginator** (Paginator) - Optional - The paginator used to paginate help output. - **commands_title** (str) - Optional - Title for commands section. Defaults to 'Commands:'. - **cog_title** (str) - Optional - Title for cog/category section. Defaults to 'Category:'. - **usage_title** (str) - Optional - Title for usage section. Defaults to 'Usage:'. - **description_title** (str) - Optional - Title for description section. Defaults to 'Description:'. - **help_title** (str) - Optional - Title for help section. Defaults to 'Help:'. - **sub_commands_title** (str) - Optional - Title for sub-commands section. Defaults to 'Sub Commands:'. - **no_category_heading** (str) - Optional - Heading text when no category is found. Defaults to 'No Category'. - **height** (int) - Optional - Maximum number of lines to fit. Defaults to 15. - **width** (int) - Optional - Maximum characters per line. Defaults to 60. - **indent** (int) - Optional - Indentation amount for commands and text. Defaults to 4. - **title_prefix** (str) - Optional - Prefix for help title. Defaults to ' +'. - **title_suffix** (str) - Optional - Suffix for help title. Defaults to '+'. - **title_char** (str) - Optional - Character used for help title. Defaults to '='. - **line_prefix** (str) - Optional - Prefix for all lines. Defaults to three spaces. - **line_suffix** (str) - Optional - Suffix for all lines. Defaults to empty string. - **footer_prefix** (str) - Optional - Prefix for help footer. Defaults to ' +'. - **footer_suffix** (str) - Optional - Suffix for help footer. Defaults to '+'. - **footer_char** (str) - Optional - Character used for help footer. Defaults to '='. ### Returns None ``` -------------------------------- ### Client.__init__ Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Initializes the Client instance with authentication and various configuration options. ```APIDOC ## Client.__init__ ### Description Initializes the Client instance with authentication and various configuration options. ### Method Constructor ### Parameters - **auth** (Auth) - Required - The authentication object. - **status** (str) - Optional - Default: 'Battle Royale Lobby - {party_size} / {party_max_size}'. The status message. - **away** (AwayStatus) - Optional - Default: AwayStatus.ONLINE. The away status. - **avatar** (Avatar) - Optional - Default: get_random_default_avatar(). The avatar. - **platform** (Platform) - Optional - Default: Platform.WINDOWS. The platform. - **net_cl** (str) - Optional - Default: ''. The network client. - **party_version** (int) - Optional - Default: 3. The party version. - **default_party_config** (DefaultPartyConfig) - Optional - Default: DefaultPartyConfig(). The default party configuration. - **default_party_member_config** (DefaultPartyMemberConfig) - Optional - Default: DefaultPartyMemberConfig(). The default party member configuration. - **build** (str) - Optional - Default: '++Fortnite+Release-14.10-CL-14288110'. The build identifier. - **os** (str) - Optional - Default: 'Windows/10.0.17134.1.768.64bit'. The operating system. - **xmpp_host** (str) - Optional - Default: 'prod.ol.epicgames.com'. The XMPP host. - **xmpp_domain** (str) - Optional - Default: 'xmpp-service-prod.ol.epicgames.com'. The XMPP domain. - **xmpp_port** (int) - Optional - Default: 5222. The XMPP port. - **cache_users** (bool) - Optional - Default: True. Whether to cache users. - **fetch_user_data_in_events** (bool) - Optional - Default: True. Whether to fetch user data in events. - **wait_for_member_meta_in_events** (bool) - Optional - Default: True. Whether to wait for member meta in events. - **connector** (aiohttp connector) - Optional - The connector for HTTP client. - **http_retry_config** (RetryConfig) - Optional - The retry configuration for HTTP client. - **ws_connector** (aiohttp connector) - Optional - The connector for WebSocket client. ### Returns None ``` -------------------------------- ### Get Ninja's touch solo KD using StatsV2.get_kd Source: https://fortnitepy.readthedocs.io/en/stable/api.html Usage example for StatsV2.get_kd. Fetches a user by name, retrieves their Battle Royale stats, and returns the KD for the 'touch' 'defaultsolo' gamemode. The data dict must include 'kills', 'matchesplayed', and 'wins'. ```python # gets ninjas kd in solo on input touch async def get_ninja_touch_solo_kd(): user = await client.fetch_user('Ninja') stats = await client.fetch_br_stats(user.id) return stats.get_kd(stats.get_stats()['touch']['defaultsolo']) ``` -------------------------------- ### Bot.__init__ Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/bot.html Initializes a new Bot instance with a command prefix, authentication, and optional help command, description, and owner IDs. ```APIDOC ## Bot.__init__ ### Description Initializes a new Bot instance with a command prefix, authentication, and optional help command, description, and owner IDs. ### Method Constructor ### Signature `def __init__(self, command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand] = _default, description: Optional[str] = None, **kwargs: Any) -> None` ### Parameters - **command_prefix** (Any) - Required - The command prefix used to trigger commands. - **auth** (Auth) - Required - The authentication object for the bot. - **help_command** (Optional[HelpCommand]) - Optional - The help command implementation to use. Defaults to `FortniteHelpCommand()`. Pass `None` to remove the help command. - **description** (Optional[str]) - Optional - The content prefixed into the default help message. - **kwargs** (Any) - Optional - Additional keyword arguments, including `case_insensitive`, `owner_id`, and `owner_ids`. ### Notes - `case_insensitive` defaults to `False` and does not carry over to groups. - `owner_id` and `owner_ids` cannot both be set. - `owner_ids` must be a collection (e.g., a set). ### Example ```python bot = Bot(command_prefix='!', auth=auth, description='My bot') ``` ``` -------------------------------- ### Client.run() Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Starts the event loop and calls start() for you. This is a blocking function and should be the last function to run. If you have an already running event loop, use start() instead. ```APIDOC ## Method: run() ### Description Starts the loop and then calls start() for you. This function is blocking and should be the last function to run. ### Usage If you have passed an already running event loop to the client, you should start the client with start() instead. ### Raises - **AuthException** - Raised if invalid credentials in any form were passed or some other misc failure. - **HTTPException** - A request error occurred while logging in. ### Notes - This function is blocking and should be the last function to run. ``` -------------------------------- ### fortnitepy.ext.commands.Bot.start Source: https://fortnitepy.readthedocs.io/en/stable/genindex.html Starts the bot. This method is part of the fortnitepy.ext.commands.Bot class. ```APIDOC ## fortnitepy.ext.commands.Bot.start ### Description Starts the bot. ### Method start() ### Parameters None documented. ### Returns None documented. ``` -------------------------------- ### fetch_multiple_br_stats example usage Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Example usage of fetch_multiple_br_stats. It creates a list of stats, fetches users, builds user_ids, calls the method, and prints the results. The example output shows the expected format. ```python 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. ``` -------------------------------- ### fortnitepy.Client.start Source: https://fortnitepy.readthedocs.io/en/stable/genindex.html Starts the client. This method is part of the fortnitepy.Client class. ```APIDOC ## fortnitepy.Client.start ### Description Starts the client. ### Method start() ### Parameters None documented. ### Returns None documented. ``` -------------------------------- ### Bot.run() Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/api.html Starts the event loop and calls start() for you. This function is blocking and should be the last function to run. ```APIDOC ## Bot.run() ### Description Starts the event loop and calls `start()` for you. This function is blocking and should be the last function to run. ### Method run() ### Parameters None ### Raises - **AuthException** – Raised if invalid credentials in any form was passed or some other misc failure. - **HTTPException** – A request error occurred while logging in. ### Notes - This function is blocking and should be the last function to run. - If you have passed an already running event loop to the client, you should start the client with `start()` instead. ``` -------------------------------- ### load_extension method Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/bot.html Loads an extension by name. The extension must have a global function 'extension_setup' that takes the bot as its single argument. Raises ExtensionAlreadyLoaded if the extension is already loaded, ExtensionNotFound if the module cannot be found, ExtensionMissingEntryPoint if the setup function is missing, and ExtensionFailed if the setup function fails. ```python def load_extension(self, name: str) -> None: """Loads an extension. An extension is a python module that contains commands, cogs, or listeners. An extension must have a global function, ``extension_setup`` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the ``bot``. Parameters ---------- name: :class:`str` The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. ``foo.test`` if you want to import ``foo/test.py``. Raises ------ 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. """ if name in self.__extensions: raise ExtensionAlreadyLoaded(name) spec = importlib.util.find_spec(name) if spec is None: raise ExtensionNotFound(name) self._load_from_module_spec(spec, name) ``` -------------------------------- ### load_extension(name: str) -> None Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/bot.html Loads an extension module. The extension must have a global function 'extension_setup' that takes the bot as its single argument. Raises ExtensionNotFound, ExtensionAlreadyLoaded, ExtensionMissingEntryPoint, or ExtensionFailed on errors. ```APIDOC ## load_extension(name: str) -> None ### Description Loads an extension. An extension is a Python module that contains commands, cogs, or listeners. The extension must have a global function `extension_setup` defined as the entry point, which takes a single argument, the `bot`. ### Method load_extension ### Parameters - **name** (str) - Required - The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g. `foo.test` if you want to import `foo/test.py`. ### Raises - **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. ### Example ```python await bot.load_extension('foo.test') ``` ``` -------------------------------- ### Get blocklist Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/http.html Sends a GET request to retrieve the client's blocklist. Uses the FriendsPublicService endpoint. ```python async def friends_get_blocklist(self) -> list: r = FriendsPublicService('/friends/api/v1/{client_id}/blocklist', client_id=self.client.user.id) return await self.get(r) ``` -------------------------------- ### Client._login method Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Authenticates the user, fetches account data, refreshes caches, accepts EULA if needed, connects to XMPP, and initializes the party. Returns False if authentication fails. ```python async def _login(self, priority: int = 0) -> None: log.debug('Running authenticating') ret = await self.auth._authenticate(priority=priority) if ret is False: return False tasks = [ self.http.account_get_by_user_id( self.auth.account_id, priority=priority ), self.http.account_graphql_get_clients_external_auths( priority=priority ), self.http.account_get_external_auths_by_id( self.auth.account_id, priority=priority ), ] data, ext_data, extra_ext_data, *_ = await asyncio.gather(*tasks) data['externalAuths'] = ext_data['myAccount']['externalAuths'] or [] data['extraExternalAuths'] = extra_ext_data self.user = ClientUser(self, data) state_fut = asyncio.ensure_future( self.refresh_caches(priority=priority) ) if self.auth.eula_check_needed() and self.accept_eula: await self.auth.accept_eula( priority=priority ) log.debug('EULA accepted') await state_fut await self.xmpp.run() log.debug('Connected to XMPP') await self.initialize_party(priority=priority) log.debug('Party created') ``` -------------------------------- ### Get Fortnite timeline Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/http.html Sends a GET request to retrieve the Fortnite timeline. Uses the FortnitePublicService endpoint. ```python async def fortnite_get_timeline(self) -> dict: r = FortnitePublicService('/fortnite/api/calendar/v1/timeline') return await self.get(r) ``` -------------------------------- ### Client.start method Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Starts the client and logs into the specified user. Blocking; call after everything else. Dispatches event_ready when ready. Raises AuthException or HTTPException on failure. ```python async def start(self, dispatch_ready: bool = True) -> None: """|coro| Starts the client and logs into the specified user. .. warning:: This functions is blocking and everything after the line calling this function will never run! If you are using this function instead of :meth:`run` you should always call it after everything else. When the client is ready it will dispatch :meth:`event_ready`. Parameters ---------- dispatch_ready: :class:`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. """ if self._first_start: self.register_methods() self._first_start = False if dispatch_ready: await self.dispatch_and_wait_event('before_start') _started_while_restarting = self._restarting pri = self._reauth_lock.priority if _started_while_restarting else 0 self._closed_event.clear() self._check_party_confirmation() if self._closed: self.http.create_connection() self._closed = False ret = await self._login(priority=pri) if ret is False: return self._set_ready() if dispatch_ready: self.dispatch_event('ready') async def waiter(task): done, pending = await asyncio.wait( (task, self._exception_future), return_when=asyncio.FIRST_COMPLETED ) try: exc = done.pop().exception() except asyncio.CancelledError: pass else: raise exc self._refresh_task = self.loop.create_task( self.auth.run_refresh_loop() ) await waiter(self._refresh_task) if not _started_while_restarting and self._restarting: async def runner(): while True: await asyncio.sleep(1) self._start_runner_task = self.loop.create_task(runner()) await waiter(self._start_runner_task) ``` -------------------------------- ### run_multiple: start multiple clients with all_ready_callback runner Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Sets up an event loop and starts multiple clients with a gap timeout to avoid throttling. It runs an all_ready_callback when all clients have started, and handles shutdown on error. This is part of the `run_multiple` function. ```python async def all_ready_callback_runner(): tasks = [loop.create_task(waiter(client)) for client in clients] await asyncio.gather(*tasks) if all(client.is_closed() for client in clients): return log.info('All clients started.') if all_ready_callback: if asyncio.iscoroutinefunction(all_ready_callback): asyncio.ensure_future(all_ready_callback()) else: all_ready_callback() asyncio.ensure_future(all_ready_callback_runner()) _before_start = _before_event(before_start) _before_close = _before_event(before_close) tasks = {} for i, client in enumerate(clients, 1): tasks[client] = loop.create_task(_start_client( client, shutdown_on_error=shutdown_on_error, after=ready_callback, error_after=error_callback )) if before_start is not None: client.add_event_handler('before_start', _before_start) if before_close is not None: client.add_event_handler('before_close', _before_close) # sleeping between starting to avoid throttling if i < len(clients): await asyncio.sleep(gap_timeout) log.debug('Starting all clients') return_when = (asyncio.FIRST_EXCEPTION if shutdown_on_error else asyncio.ALL_COMPLETED) done, pending = await asyncio.wait( list(tasks.values()), return_when=return_when ) done_task = done.pop() if pending and done_task.exception() is not None: raise done_task.exception() ``` -------------------------------- ### DefaultPartyConfig Usage Example Source: https://fortnitepy.readthedocs.io/en/stable/api.html Example showing how to configure DefaultPartyConfig with a list of partials for setting custom key and playlist. ```APIDOC ## DefaultPartyConfig ### Description A list of coroutines in the form of partials. This config will be automatically equipped by the party when a new party is created by the client. ### Example ```python from fortnitepy import ClientParty from functools import partial [ partial(ClientParty.set_custom_key, 'myawesomekey'), partial(ClientParty.set_playlist, 'Playlist_PlaygroundV2', region=fortnitepy.Region.EUROPE) ] ``` ### Attributes #### team_change_allowed - **Type**: bool - **Description**: Whether or not players are able to manually swap party team with another player. This setting only works if the client is the leader of the party. #### default_squad_assignment - **Type**: SquadAssignment - **Description**: The default squad assignment to use for new members and members not specified in manual squad assignments requests. #### position_priorities - **Type**: List[int] - **Description**: A list containing exactly 16 integers ranging from 0-16 with no duplicates. This is used for position assignments. #### reassign_positions_on_size_change - **Type**: bool - **Description**: Whether or not positions will be automatically reassigned when the party size changes. #### cls - **Type**: Type[ClientParty] - **Description**: The default party object used to represent the client's party. ``` -------------------------------- ### Initialize client with manual net_cl Source: https://fortnitepy.readthedocs.io/en/stable/faq.html Shows how to pass the net_cl keyword when initializing the client to fix the 'Incompatible net_cl' error. The comment notes that the auth parameter should be replaced with an authentication method like fortnitepy.AdvancedAuth or fortnitepy.EmailAndPasswordAuth. ```python # pass the netcl to with the net_cl keyword when initializing the client. client = fortnitepy.Client( auth=fortnitepy.Auth, // Here goes an authentication method like fortnitepy.AdvancedAuth or fortnitepy.EmailAndPasswordAuth net_cl='7605985' ) ``` -------------------------------- ### Example leaderboard entry return Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/api.html Example return value for fetch_leaderboard, showing a dictionary with 'account' and 'value' keys. ```json { 'account': '4480a7397f824fe4b407077fb9397fbb', 'value': 5082 } ``` -------------------------------- ### Bot.__init__ constructor Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/ext/commands/bot.html Initializes the Bot instance with command prefix, auth, help command, description, and other keyword arguments. Validates owner_id and owner_ids, sets up internal state, and registers event handlers for friend_message and party_message. ```python def __init__(self, command_prefix: Any, auth: Auth, *, help_command: Optional[HelpCommand] = _default, description: Optional[str] = None, **kwargs: Any) -> None: kwargs['case_insensitive'] = kwargs.get('case_insensitive', False) super().__init__(auth, **kwargs) self.command_prefix = command_prefix self.description = inspect.cleandoc(description) if description else '' self.owner_id = kwargs.get('owner_id') self.owner_ids = kwargs.get('owner_ids', set()) if self.owner_id and self.owner_ids: raise TypeError('Both owner_id and owner_ids are set.') if (self.owner_ids and not isinstance(self.owner_ids, collections.abc.Collection)): raise TypeError( 'owner_ids must be a collection not ' '{0.__class__!r}'.format(self.owner_ids) ) self.__cogs = {} self.__extensions = {} self._checks = [] self._check_once = [] self._help_command = None self._before_invoke = None self._after_invoke = None if help_command is _default: self.help_command = FortniteHelpCommand() else: self.help_command = help_command self.add_event_handler('friend_message', self.process_commands) self.add_event_handler('party_message', self.process_commands) ``` -------------------------------- ### run_multiple(clients: List['Client'], *, gap_timeout: float = 0.2, shutdown_on_error: bool = True, ready_callback: Optional[MaybeCoro] = None, error_callback: Optional[MaybeCoro] = None, all_ready_callback: Optional[MaybeCoro] = None, before_start: Optional[Awaitable] = None, before_close: Optional[Awaitable] = None) -> None Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Sets up an event loop and calls start_multiple() to start multiple clients. This function is blocking and should be the last function to run. Clients are started with a 0.2 second gap to avoid throttling by Epic Games. ```APIDOC ## run_multiple(clients: List['Client'], *, gap_timeout: float = 0.2, shutdown_on_error: bool = True, ready_callback: Optional[MaybeCoro] = None, error_callback: Optional[MaybeCoro] = None, all_ready_callback: Optional[MaybeCoro] = None, before_start: Optional[Awaitable] = None, before_close: Optional[Awaitable] = None) -> None ### Description This function sets up a loop and then calls :func:`start_multiple()` for you. If you already have a running event loop, you should start the clients with :func:`start_multiple()`. On shutdown, all clients will be closed gracefully. ### Method Function ### Signature ```python def run_multiple(clients: List['Client'], *, gap_timeout: float = 0.2, shutdown_on_error: bool = True, ready_callback: Optional[MaybeCoro] = None, error_callback: Optional[MaybeCoro] = None, all_ready_callback: Optional[MaybeCoro] = None, before_start: Optional[Awaitable] = None, before_close: Optional[Awaitable] = None ) -> None ``` ### Parameters - **clients** (List[:class:`Client`]) - Required - A list of the clients to start. - **gap_timeout** (float) - Optional - Time in seconds to wait between starting each client to avoid throttling. Defaults to 0.2. - **shutdown_on_error** (bool) - Optional - If True, shutdown all clients if any client raises an exception. Defaults to True. - **ready_callback** (Optional[MaybeCoro]) - Optional - Callback to run when a client is ready. - **error_callback** (Optional[MaybeCoro]) - Optional - Callback to run when a client encounters an error. - **all_ready_callback** (Optional[MaybeCoro]) - Optional - Callback to run when all clients are ready. - **before_start** (Optional[Awaitable]) - Optional - Awaitable to run before each client starts. - **before_close** (Optional[Awaitable]) - Optional - Awaitable to run before each client closes. ### Returns None ### Example ```python run_multiple([client1, client2], gap_timeout=0.5) ``` ``` -------------------------------- ### Get Fortnite content Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/http.html Sends a GET request to retrieve Fortnite game content. Uses the FortniteContentWebsite endpoint. ```python async def fortnitecontent_get(self) -> dict: r = FortniteContentWebsite('/content/api/pages/fortnite-game') return await self.get(r) ``` -------------------------------- ### Get a user from cache by user ID Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Tries to get a user from the user cache by the given user id. If not found, attempts to get a friend and creates a User from the friend's raw data, caching it if enabled. Returns None if not found. ```python def get_user(self, user_id: str) -> Optional[User]: """Tries to get a user from the user cache by the given user id. Parameters ---------- user_id: :class:`str` The id of the user. Returns ------- Optional[:class:`User`] The user if found, else ``None`` """ user = self._users.get(user_id) if user is None: friend = self.get_friend(user_id) if friend is not None: user = User(self, friend.get_raw()) if self.cache_users: self._users[user.id] = user return user ``` -------------------------------- ### HelpCommand.prepare_help_command(ctx, command=None) Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/api.html A low level coroutine method that can be used to prepare the help command before it does anything. The default implementation does nothing. Override this method to prepare state in your subclass before the command processes. ```APIDOC ## HelpCommand.prepare_help_command(ctx, command=None) ### Description A low level coroutine method that can be used to prepare the help command before it does anything. The default implementation does nothing. Override this method to prepare state in your subclass before the command processes. ### Method Coroutine ### Parameters - **ctx** (Context) - Required - The invocation context. - **command** (Optional[str]) - Optional - The argument passed to the help command. ### Notes - This is called inside the help command callback body, so all usual rules that happen inside apply here as well. ``` -------------------------------- ### Client.__init__ Source: https://fortnitepy.readthedocs.io/en/stable/_modules/fortnitepy/client.html Initializes a new fortnitepy client with the provided authentication and configuration options. This constructor sets up the event loop and prepares the client for connecting to Fortnite services. ```APIDOC ## Client.__init__ ### Description Initializes a new fortnitepy client with the provided authentication and configuration options. This constructor sets up the event loop and prepares the client for connecting to Fortnite services. ### Method Constructor ### Signature `__init__(self, auth, *, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any) -> None` ### Parameters - **auth** (:class:`Auth`) - Required - The authentication method to use. See available authentication methods in the documentation. - **loop** (Optional[:class:`asyncio.AbstractEventLoop`]) - Optional - The event loop to use for asynchronous operations. - **connector** (:class:`aiohttp.BaseConnector`) - Optional - The connector to use for connection pooling. - **ws_connector** (:class:`aiohttp.BaseConnector`) - Optional - The connector to use for websocket connection pooling. This could be the same as the above connector. - **status** (:class:`str`) - Optional - The status you want the client to send with its presence to friends. Defaults to: `Battle Royale Lobby - {party playercount} / {party max playercount}` - **away** (:class:`AwayStatus`) - Optional - The away status the client should use for its presence. Defaults to :attr:`AwayStatus.ONLINE`. - **platform** (:class:`.Platform`) - Optional - The platform you want the client to display as its source. Defaults to :attr:`Platform.WINDOWS`. - **net_cl** (:class:`str`) - Optional - The current net cl used by the current Fortnite build. Named **netCL** in official logs. Defaults to an empty string which is the recommended usage as of `v0.9.0` since you then won't need to update it when a new update is pushed by Fortnite. - **party_version** (:class:`int`) - Optional - The party version the client should use. This value determines which version should be able to join the party. If a user attempts to join the clients party with a different party version than the client, then an error will be visible saying something by the lines of "Their party of Fortnite is older/newer than yours". If you experience this error I recommend incrementing the default set value by one since the library in that case most likely has yet to be updated. Defaults to `3` (As of November 3rd 2020). - **default_party_config** (:class:`DefaultPartyConfig`) - Optional - The party configuration used when creating parties. If not specified, the client will use the default values specified in the data class. - **default_party_member_config** (:class:`DefaultPartyMemberConfig`) - Optional - The party member configuration used when creating parties. If not specified, the client will use the default values specified in the data class. - **http_retry_config** (Optional[:class:`HTTPRetryConfig`]) - Optional - The config to use for http retries. - **build** (:class:`str`) - Optional - The build used by Fortnite. Defaults to a valid but maybe outdated value. - **os** (:class:`str`) - Optional - The os version string to use in the user agent. Defaults to `Windows/10.0.17134.1.768.64bit` which is valid no matter which platform you have set. - **service_host** (:class:`str`) - Optional - The host used by Fortnite's XMPP services. - **service_domain** (:class:`str`) - Optional - The domain used by Fortnite's XMPP services. - **service_port** (:class:`int`) - Optional - The port used by Fortnite's XMPP services. - **cache_users** (:class:`bool`) - Optional - Whether or not the library should cache :class:`User` objects. Disable this if you are running a program with lots of users as this could potentially take a big hit on the memory usage. Defaults to `True`. - **fetch_user_data_in_events** (:class:`bool`) - Optional - Whether or not user data should be fetched in event processing. Disabling this might be useful for larger applications that deals with possibly being rate limited on their ip. Defaults to `True`. Warning: if disabled, display names, external auths and more might be missing or `None` on objects deriving from :class:`User`. :attr:`User.id` always will be available. Use :meth:`User.fetch()` to update all missing attributes. - **wait_for_member_meta_in_events** (:class:`bool`) - Optional - Whether or not the client should wait for party member meta (information about outfit, backpack etc.) before dispatching events like :func:`event_party_member_join()`. If disabled, member objects in the events won't have the correct meta. Defaults to `True`. ### Attributes - **loop** (:class:`asyncio.AbstractEventLoop`) - The event loop that client implements. - **user** (:class:`ClientUser`) - The user the client is logged in as. - **party** (:class:`ClientParty`) - The party the client is currently connected to. ``` -------------------------------- ### User invocation example Source: https://fortnitepy.readthedocs.io/en/stable/ext/commands/commands.html Shows how the user invokes the 'foo' command with the prefix '$' and argument 'abc'. ```text $foo abc ```