### Complete Client Usage Example Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Demonstrates the complete setup and usage of the fnbr.js Client, including authentication, event handling, and API calls. ```javascript const { Client, Enums } = require('fnbr'); const client = new Client({ auth: { refreshToken: 'your-refresh-token' }, partyConfig: { privacy: Enums.PartyPrivacy.PRIVATE, maxSize: 4 } }); client.on('ready', () => { console.log(`Logged in as ${client.user.self.displayName}`); }); client.on('friend:message', (message) => { console.log(`${message.author.displayName}: ${message.content}`); if (message.content.toLowerCase() === 'ping') { message.reply('Pong!'); } }); client.on('friend:online', (friend) => { console.log(`${friend.displayName} came online`); }); client.on('friend:offline', (friend) => { console.log(`${friend.displayName} went offline`); }); client.on('friend:presence', (before, after) => { console.log(`${after.user.displayName} status: ${after.status}`); }); (async () => { try { await client.login(); const stats = await client.getBRStats('username'); console.log(`Wins: ${stats.stats['br_kill_total']}`); await client.invite('friend-name'); } catch (error) { console.error(error); } })(); ``` -------------------------------- ### Initial Setup Endpoints Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Endpoints for initial game setup, including EULA verification and access grants. ```APIDOC ## Initial Setup Endpoints ### INIT_EULA #### Description EULA verification. ### Method POST ### Endpoint `https://eulatracking-public-service-prod-m.ol.epicgames.com/eulatracking/api/public/agreements/fn` ### INIT_GRANTACCESS #### Description Grant game access. ### Method POST ### Endpoint `https://fngw-mcp-gc-livefn.ol.epicgames.com/fortnite/api/game/v2/grant_access` ``` -------------------------------- ### Install fnbr.js Source: https://github.com/fnbrjs/fnbr.js/blob/main/docs/general/welcome.md Install the fnbr.js library using npm. This is the first step to using the library in your project. ```bash npm i fnbr ``` -------------------------------- ### Complete fnbr.js Client Configuration Example Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md A comprehensive example demonstrating authentication, debugging, caching, party defaults, behavior settings, and timeouts. Requires a refresh token from environment variables. ```javascript const { Client, Enums } = require('fnbr'); const client = new Client({ // Authentication auth: { refreshToken: process.env.FORTNITE_REFRESH_TOKEN }, // Debugging debug: console.log, httpDebug: (msg) => console.log(`[HTTP] ${msg}`), // Caching cacheSettings: { users: { maxLifetime: 3600, sweepInterval: 600 }, presences: { maxLifetime: 1800, sweepInterval: 300 } }, // Party defaults partyConfig: { privacy: Enums.PartyPrivacy.FRIENDS, maxSize: 16, chatEnabled: true, joinConfirmation: false }, // Behavior platform: 'WIN', language: 'en', defaultStatus: 'Battle Royale', defaultOnlineType: 'online', savePartyMemberMeta: true, // Timeouts xmppConnectionTimeout: 20000, friendOnlineConnectionTimeout: 5000, friendOfflineTimeout: 600000 }); await client.login(); ``` -------------------------------- ### Usage Example: Get Current Tournaments Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Demonstrates fetching current tournaments and iterating through their details, including event windows. ```javascript const tournaments = await client.tournaments.get(); tournaments.forEach(tournament => { console.log(`Tournament: ${tournament.displayInfo.titleLine1}`); tournament.eventWindows.forEach(window => { console.log(` Window: ${window.windowId}`); }); }); ``` -------------------------------- ### Install fnbr.js Source: https://github.com/fnbrjs/fnbr.js/blob/main/README.md Install the fnbr.js library using npm. This is the first step to using the library in your Node.js project. ```bash npm install fnbr ``` -------------------------------- ### Example: Log Total Number of Available Tournaments Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches all available tournaments, including past ones, and logs the total count. ```javascript const allTournaments = await client.tournaments.getData('en', true); console.log(`${allTournaments.length} tournaments available`); ``` -------------------------------- ### Get DM Conversation (Usage Example) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/ChatManager.md Provides an example of how to get a direct message conversation ID, creating it if it doesn't exist. ```javascript async function getDMConversation(userId) { const conversation = await client.chat.createDMConversation(userId, true); return conversation.conversationId; } ``` -------------------------------- ### Example: Log Session Name and Duration Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches session metadata and logs the session's friendly name and duration in milliseconds. ```javascript const metadata = await client.tournaments.getSessionMetadata('session-id'); console.log(`Session: ${metadata.friendlyName}`); console.log(`Duration: ${metadata.lengthInMS}ms`); ``` -------------------------------- ### Basic Client Usage Source: https://github.com/fnbrjs/fnbr.js/blob/main/docs/general/welcome.md This example demonstrates how to create a new client instance, listen for friend messages, and log in to Fortnite services. It includes handling 'ping' messages and logging the display name upon successful login. ```javascript const { Client } = require('fnbr'); const client = new Client(); client.on('friend:message', (message) => { console.log(`Message from ${message.author.displayName}: ${message.content}`); if (message.content.toLowerCase().startsWith('ping')) { message.reply('Pong!'); } }); client.on('ready', () => { console.log(`Logged in as ${client.user.self.displayName}`); }); client.login(); ``` -------------------------------- ### Example: Log User and Tokens Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Iterates through fetched event tokens to log the user's display name and their associated tokens. ```javascript const tokens = await client.tournaments.getEventTokens('user-id-or-name'); tokens.forEach(token => { console.log(`User: ${token.user.displayName}`); console.log(`Tokens:`, token.tokens); }); ``` -------------------------------- ### Usage Example: Get Tournament Results Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md An asynchronous function to fetch tournament results for a given event and window ID, then logs each entry's rank, name, and score. ```javascript async function getTournamentResults(eventId, windowId) { const results = await client.tournaments.getWindowResults( eventId, windowId, false, 0 ); results.entries.forEach((entry, rank) => { console.log(`${rank + 1}. ${entry.accountName}: ${entry.score} points`); }); } ``` -------------------------------- ### get Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches current and past Battle Royale tournaments based on specified language, region, and platform. ```APIDOC ## get(language?, region?, platform?) ### Description Fetches the current and past Battle Royale tournaments. ### Method `public async get(language?: Language, region?: Region, platform?: FullPlatform): Promise` ### Parameters #### Query Parameters - **language** (Language) - Optional - Defaults to 'en' - Language for tournament data - **region** (Region) - Optional - Defaults to 'EU' - Region code (EU, NAE, NAW, BR, ME, ASIA, OCE) - **platform** (FullPlatform) - Optional - Defaults to 'Windows' - Platform (Windows, PS4, XboxOne, etc) ### Response #### Success Response - Returns an array of Tournament objects. #### Throws - `EpicgamesAPIError` ### Example ```javascript const tournaments = await client.tournaments.get('en', 'NAE', 'Windows'); tournaments.forEach(tournament => { console.log(`${tournament.displayInfo.titleLine1}`); console.log(`Event Windows: ${tournament.eventWindows.length}`); }); ``` ``` -------------------------------- ### Example: Log Tournament Titles and Event Windows Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Iterates through fetched tournaments to log their titles and the number of associated event windows. ```javascript const tournaments = await client.tournaments.get('en', 'NAE', 'Windows'); tournaments.forEach(tournament => { console.log(`${tournament.displayInfo.titleLine1}`); console.log(`Event Windows: ${tournament.eventWindows.length}`); }); ``` -------------------------------- ### Usage Example: Check Tournament Eligibility Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches event tokens for the current user and logs their tournament division and points. ```javascript const tokens = await client.tournaments.getEventTokens(client.user.self.id); tokens.forEach(token => { console.log(`Division: ${token.tokens.division}`); console.log(`Points: ${token.tokens.points}`); }); ``` -------------------------------- ### Get Storefront Keychain Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the storefront keychain, returning an array of keychain values. ```typescript public async getStorefrontKeychain(): Promise ``` ```javascript const keychain = await client.getStorefrontKeychain(); ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/errors.md Demonstrates robust error handling for various fnbr.js operations, including adding friends, getting stats, and joining parties. It uses instanceof checks for specific errors and a general catch for API or unknown errors. ```javascript const { Client, EpicgamesAPIError, UserNotFoundError, DuplicateFriendshipError, StatsPrivacyError, PartyNotFoundError } = require('fnbr'); const client = new Client(); async function safeAddFriend(username) { try { await client.friend.add(username); console.log(`Added ${username}`); } catch (error) { if (error instanceof UserNotFoundError) { console.log(`${username} does not exist`); } else if (error instanceof DuplicateFriendshipError) { console.log(`Already friends with ${username}`); } else if (error instanceof EpicgamesAPIError) { console.log(`API Error: ${error.code} - ${error.message}`); } else { console.error('Unknown error:', error); } } } async function safeGetStats(username) { try { const stats = await client.getBRStats(username); return stats; } catch (error) { if (error instanceof UserNotFoundError) { console.log(`${username} not found`); } else if (error instanceof StatsPrivacyError) { console.log(`${username}'s stats are private`); } else { console.error('Unknown error:', error); } return null; } } async function safeJoinParty(partyId) { try { await client.joinParty(partyId); console.log('Joined party'); } catch (error) { if (error instanceof PartyNotFoundError) { console.log('Party not found'); } else if (error instanceof PartyMaxSizeReachedError) { console.log('Party is full'); } else { console.error('Unknown error:', error); } } } ``` -------------------------------- ### Example: Log Tournament Window Results Page Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches tournament window results for a given event and window ID, then logs the retrieved page number. ```javascript const results = await client.tournaments.getWindowResults( 'event-123', 'window-456', true, 0 ); console.log(`Results retrieved for page ${results.page}`); ``` -------------------------------- ### Send Secure Message (Usage Example) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/ChatManager.md Illustrates sending a secure message by first ensuring message signing is configured, then sending the whisper message. ```javascript async function sendSecureMessage(user, message) { // Ensure keypair is set up and registered await client.chat.ensureMessageSigning(); // Send message const messageId = await client.chat.whisperUser(user, { body: message }); console.log(`Message sent: ${messageId}`); } ``` -------------------------------- ### Get Storefronts Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the current storefront data for Fortnite. Supports specifying a language code for localized content. ```javascript const storefronts = await client.getStorefronts('en'); ``` -------------------------------- ### GET Request Pattern Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Standard structure for making GET requests to Fortnite API endpoints. Requires an access token for authorization and specifies JSON content acceptance. ```text GET {ENDPOINT}/{path}?query=params Headers: Authorization: Bearer {access_token} Accept: application/json ``` -------------------------------- ### Send Direct Message (Usage Example) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/ChatManager.md Demonstrates sending a direct message using the chat manager. This can be done directly or via the friend manager. ```javascript // Via friend manager const message = await client.friend.sendMessage('friend-name', 'Hello!'); // Or directly via chat manager const messageId = await client.chat.whisperUser('user-id-or-name', { body: 'Hello there!' }); ``` -------------------------------- ### Send Party Chat Message (Usage Example) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/ChatManager.md Shows how to send a message within a party chat. It checks if a party exists and then sends the message to all party members. ```javascript if (client.party) { const messageId = await client.chat.sendMessageInConversation( `p-${client.party.id}`, { body: 'Everyone ready?' }, client.party.members.map(m => m.id), ConversationType.Party ); } ``` -------------------------------- ### Getting Collection Size Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Structures.md Demonstrates how to retrieve the number of items currently in a collection, such as the total number of friends. ```javascript // Size console.log(`Friends: ${client.friend.list.size}`); ``` -------------------------------- ### Manage Blocklist and Get Global Profile Stats Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/UserManager.md Illustrates managing the user blocklist by blocking and unblocking a user, and then retrieving global profile statistics for a user. The size of the blocklist is logged after modification. ```javascript // Manage blocklist await client.user.block('ToxicUser'); console.log(client.user.blocklist.size); // Number of blocked users await client.user.unblock('ToxicUser'); // Get global profile stats const profile = await client.user.fetchGlobalProfile('TestUser'); console.log(profile.globalStats); ``` -------------------------------- ### Search Users by Display Name Prefix Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/UserManager.md Find users whose display names start with a specified prefix. You can optionally filter by platform. ```javascript const results = await client.user.search('test', 'epic'); results.forEach(result => { console.log(result.user.displayName); }); ``` -------------------------------- ### Get User Tokens for Multiple Users Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Retrieves tournament tokens for a list of user IDs and logs their division and points. ```javascript async function getTeamTokens(userIds) { const tokens = await client.tournaments.getEventTokens(userIds); tokens.forEach(playerTokens => { console.log(`${playerTokens.user.displayName}:`); console.log(` Arena Division: ${playerTokens.tokens.division}`); console.log(` Points: ${playerTokens.tokens.points}`); }); } ``` -------------------------------- ### Get Tournament Session Metadata Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches and logs metadata for a given tournament session ID. Handles 'MatchNotFoundError' specifically. ```javascript async function getMatchInfo(sessionId) { try { const metadata = await client.tournaments.getSessionMetadata(sessionId); console.log({ name: metadata.friendlyName, duration: metadata.lengthInMS, compressed: metadata.isCompressed, live: metadata.isLive, timestamp: metadata.timestamp }); } catch (error) { if (error instanceof MatchNotFoundError) { console.log('Match not found'); } } } ``` -------------------------------- ### Get Game Data with fnbr.js Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Retrieve Battle Royale stats, server status, news, tournament information, and Save The World profile data. Requires display names or language/region codes for specific data. ```javascript // Battle Royale stats const stats = await client.getBRStats('DisplayName'); console.log(`Wins: ${stats.stats['br_kill_total']}`); // Server status const status = await client.getFortniteServerStatus(); console.log(`Server: ${status.status}`); // News const news = await client.getBRNews('en'); // Tournaments const tournaments = await client.tournaments.get('en', 'NAE', 'Windows'); // Save The World const stwProfile = await client.stw.getProfile('DisplayName'); console.log(`Power Level: ${stwProfile.powerLevel}`); ``` -------------------------------- ### Get STW World Info Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/STWManager.md Fetches current Save The World world information, including active missions and mission alerts, for a specified language. Returns STWWorldInfoData. ```typescript public async getWorldInfo(language?: Language): Promise ``` ```javascript const worldInfo = await client.stw.getWorldInfo('en'); console.log(`Theaters:`, worldInfo.theaters); console.log(`Active Missions:`, worldInfo.missions); console.log(`Mission Alerts:`, worldInfo.missionAlerts); ``` ```javascript async function getMissionAlerts() { const worldInfo = await client.stw.getWorldInfo('en'); // Get mission alerts worldInfo.missionAlerts.forEach(alert => { console.log(`${alert.theater}: ${alert.missionName}`); console.log(`Difficulty: ${alert.difficulty}`); console.log(`Rewards:`, alert.rewards); }); // Get available missions worldInfo.missions.forEach(mission => { console.log(`${mission.type}: ${mission.name}`); }); } ``` -------------------------------- ### Configure Client with Device Auth Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Initialize the client using device authentication credentials. This method is persistent and device-specific. ```javascript const client = new Client({ auth: { deviceAuth: { accountId: 'xxx', deviceId: 'yyy', secret: 'zzz' } } }); ``` -------------------------------- ### Client Constructor Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Initializes a new Client instance. Configuration options can be provided to customize its behavior, such as authentication methods. ```APIDOC ## Constructor Client ### Description Initializes a new Client instance. Configuration options can be provided to customize its behavior, such as authentication methods. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (ClientOptions) - Optional - Configuration options for the client. Defaults to `{}`. ``` -------------------------------- ### Authentication with Device Auth File Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Initializes the client using device authentication details stored in a JSON file. ```javascript const client = new Client({ auth: { deviceAuth: './device_auth.json' } }); ``` -------------------------------- ### Basic fnbr.js Client Usage Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Initialize the client, log in, and handle 'ready' and 'friend:message' events. Ensure you have a valid refresh token. ```javascript const { Client, Enums } = require('fnbr'); const client = new Client({ auth: { refreshToken: 'your-refresh-token' } }); client.on('ready', () => { console.log(`Logged in as ${client.user.self.displayName}`); }); client.on('friend:message', (message) => { console.log(`${message.author.displayName}: ${message.content}`); if (message.content.toLowerCase() === 'ping') { message.reply('Pong!'); } }); await client.login(); ``` -------------------------------- ### Get Fortnite Server Status Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the current server status for Fortnite, indicated as 'UP' or 'DOWN'. ```javascript const status = await client.getFortniteServerStatus(); console.log(status.status); ``` -------------------------------- ### Basic Authentication with Console Prompt Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Initializes the client with authentication options that prompt the user for an authorization code. ```javascript const client = new Client({ auth: { // Console will prompt for authorization code } }); ``` -------------------------------- ### Get Mutual Friends Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/FriendManager.md Retrieves a list of mutual friends between the current user and a specified display name. ```APIDOC ## Get Mutual Friends ### Description Retrieves a list of mutual friends between the current user and a specified display name. ### Method GET (assumed, based on action) ### Endpoint /friend/getMutual ### Parameters #### Query Parameters - **displayName** (string) - Required - The display name of the user to find mutual friends with. ### Response #### Success Response (200) - **mutualFriends** (array) - A list of friend objects representing mutual friends. ``` -------------------------------- ### Get Creator Code Data Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches data for a Support-A-Creator code using its slug. Returns a CreatorCode object. ```typescript public async getCreatorCode(code: string): Promise ``` ```javascript const sac = await client.getCreatorCode('nickname'); ``` -------------------------------- ### initParty(createNew?, forceNew?) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Initializes the client's party. This method can create a new party or ensure a new one is created if one already exists, based on the provided flags. ```APIDOC ## initParty(createNew?, forceNew?) ### Description Initializes the client's party. This method can create a new party or ensure a new one is created if one already exists, based on the provided flags. ### Method `public async initParty(createNew: boolean = true, forceNew: boolean = true): Promise` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **createNew** (boolean) - Optional - Whether to create a new party if none exists. Defaults to `true`. - **forceNew** (boolean) - Optional - Whether to force create a new party even if already in one. Defaults to `true`. ### Request Example ```javascript await client.initParty(true, true); ``` ### Response #### Success Response `Promise` #### Response Example None ### Throws: - `EpicgamesAPIError` ``` -------------------------------- ### static consoleQuestion Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Prompts the user for input on the console and returns the input as a string. This is a static method. ```APIDOC ## static consoleQuestion(question) ### Description Prompts the user for input on the console. ### Parameters #### Path Parameters - **question** (string) - Required - The question to display to the user ### Returns Promise ### Example ```javascript const code = await Client.consoleQuestion('Enter authorization code: '); ``` ``` -------------------------------- ### Get Epic Games Server Status Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Retrieves the current server status for all Epic Games services from status.epicgames.com. ```javascript const status = await client.getEpicgamesServerStatus(); ``` -------------------------------- ### Configure Client with Environment Variables Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Use environment variables for authentication refresh tokens, auth clients, and platform settings. Provides fallback values if environment variables are not set. ```javascript const client = new Client({ auth: { refreshToken: process.env.FORTNITE_REFRESH_TOKEN, authClient: process.env.AUTH_CLIENT || 'fortniteAndroidGameClient' }, platform: process.env.PLATFORM || 'WIN' }); ``` -------------------------------- ### login() Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Logs the client into the Fortnite services. Requires valid authentication details to be configured. It may prompt for an authorization code if not provided. ```APIDOC ## login() ### Description Logs the client into the Fortnite services. Requires valid authentication details to be configured. It may prompt for an authorization code if not provided. ### Method `public async login(): Promise` ### Endpoint N/A (SDK Method) ### Parameters None ### Request Example ```javascript const client = new Client({ auth: { refreshToken: 'your-refresh-token' } }); await client.login(); ``` ### Response #### Success Response `Promise` #### Response Example None ### Throws: - `EpicgamesAPIError` — Authentication or API error ``` -------------------------------- ### Get Pending Friend Requests Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/FriendManager.md Retrieves a list of pending friend requests, distinguishing between incoming and outgoing requests. ```APIDOC ## Get Pending Friend Requests ### Description Retrieves a list of pending friend requests, distinguishing between incoming and outgoing requests. ### Method GET (assumed, based on action) ### Endpoint /friend/pendingList ### Parameters None ### Response #### Success Response (200) - **pendingRequests** (array) - A list of pending friend request objects, each indicating if it's `IncomingPendingFriend` or `OutgoingPendingFriend` and including `displayName`. ``` -------------------------------- ### Get Mutual Friends Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/FriendManager.md Fetches friends shared with a specific user. The target user must be in the friend list. ```javascript const mutualFriends = await client.friend.getMutual('DisplayName'); console.log(`Mutual friends: ${mutualFriends.length}`); ``` -------------------------------- ### createParty(config?) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Creates a new party with specific configuration options, such as privacy settings, maximum size, and chat enablement. ```APIDOC ## createParty(config?) ### Description Creates a new party with specific configuration options, such as privacy settings, maximum size, and chat enablement. ### Method `public async createParty(config?: PartyConfig): Promise` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **config** (PartyConfig) - Optional - Party configuration options. ### Request Example ```javascript await client.createParty({ privacy: Enums.PartyPrivacy.PRIVATE, maxSize: 4, chatEnabled: true }); ``` ### Response #### Success Response `Promise` #### Response Example None ### Throws: - `EpicgamesAPIError` ``` -------------------------------- ### Get Radio Stations Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the current Fortnite Battle Royale radio stations. Returns an array of RadioStation objects. ```typescript public async getRadioStations(): Promise ``` ```javascript const stations = await client.getRadioStations(); ``` -------------------------------- ### Get All Online Friends Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Filter the friend list to retrieve only those who are currently online. The result is a `Set` containing online friends. ```javascript const online = client.friend.list.filter(f => f.isOnline); console.log(`${online.size} friends online`); ``` -------------------------------- ### Fetch Single User and Multiple Users Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/UserManager.md Demonstrates fetching a single user's details and then fetching multiple users using their identifiers. Assumes a client object is already initialized. ```javascript // Fetch a single user const user = await client.user.fetch('TestUser'); console.log(user.displayName, user.id, user.level); // Fetch multiple users const users = await client.user.fetchMultiple(['user1', 'user2', 'user3']); ``` -------------------------------- ### Create New Party Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Creates a new party with specified configuration options such as privacy, maximum size, and chat enablement. If no configuration is provided, default settings will be used. ```javascript await client.createParty({ privacy: Enums.PartyPrivacy.PRIVATE, maxSize: 4, chatEnabled: true }); ``` -------------------------------- ### Initialize Party Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Initializes the client's party, with options to create a new party if none exists or force the creation of a new one even if already in a party. Defaults to creating a new party. ```javascript await client.initParty(true, true); ``` -------------------------------- ### AuthOptions Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/types.md Configuration options for setting up authentication, allowing various methods and flags to be specified. ```APIDOC ## AuthOptions ### Description Configuration options for authentication. ### Fields - **deviceAuth** (DeviceAuthResolveable) - Optional - Device auth object, function, or file path - **exchangeCode** (AuthStringResolveable) - Optional - Exchange code for authentication - **authorizationCode** (AuthStringResolveable) - Optional - Authorization code (prompts console by default) - **refreshToken** (AuthStringResolveable) - Optional - Refresh token for re-authentication - **launcherRefreshToken** (AuthStringResolveable) - Optional - Launcher refresh token - **checkEULA** (boolean) - Optional - Default: true - Check if EULA has been accepted - **killOtherTokens** (boolean) - Optional - Default: true - Kill other active sessions - **createLauncherSession** (boolean) - Optional - Default: false - Create launcher auth session - **authClient** (AuthClient) - Optional - Default: 'fortniteAndroidGameClient' - Fortnite auth client type ``` -------------------------------- ### Wait Until Client is Ready Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Pauses execution until the client has fully initialized and is ready to process requests. A default timeout of 10 seconds is applied. ```javascript await client.waitUntilReady(); ``` -------------------------------- ### Get Battle Royale Event Flags Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the current Battle Royale event flags. Supports specifying a language, defaulting to 'en'. ```typescript public async getBREventFlags(language?: Language): Promise ``` ```javascript const flags = await client.getBREventFlags('en'); ``` -------------------------------- ### Authentication with Refresh Token Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Initializes the client using a provided refresh token for authentication. ```javascript const client = new Client({ auth: { refreshToken: 'your-refresh-token' } }); ``` -------------------------------- ### Configure Client with Custom Caching Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Set up custom caching intervals for user and presence data. Adjust `maxLifetime` and `sweepInterval` to control cache behavior. ```javascript const client = new Client({ cacheSettings: { users: { maxLifetime: 3600, // 1 hour sweepInterval: 600 // Sweep every 10 minutes }, presences: { maxLifetime: 1800, // 30 minutes sweepInterval: 300 // Sweep every 5 minutes } } }); ``` -------------------------------- ### Get Client's Current Party Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the client's current party object. Returns undefined if the client is not currently in a party. ```javascript const party = await client.getClientParty(); console.log(party?.id); ``` -------------------------------- ### Get STW News Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/STWManager.md Fetches the current Save The World news for a specified language. Returns an array of STWNewsMessage objects and can throw EpicgamesAPIError. ```typescript public async getNews(language?: Language): Promise ``` ```javascript const news = await client.stw.getNews('en'); news.forEach(message => { console.log(`${message.title}`); console.log(`${message.body}`); }); ``` ```javascript async function getSaveTheWorldNews() { const news = await client.stw.getNews('en'); news.forEach(message => { console.log(`=== ${message.title} ===`); console.log(message.body); if (message.image) { console.log(`Image: ${message.image}`); } console.log(''); }); } ``` ```javascript async function getMultiLanguageNews() { const languages = ['en', 'de', 'fr', 'es', 'ja']; for (const lang of languages) { const news = await client.stw.getNews(lang); console.log(`${lang.toUpperCase()}: ${news.length} messages`); } } ``` -------------------------------- ### Configure Client with Debug Logging Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Enable debug logging for the client, HTTP requests, and XMPP communication. Provide callback functions to `debug`, `httpDebug`, and `xmppDebug`. ```javascript const client = new Client({ debug: console.log, httpDebug: (msg) => console.log(`[HTTP] ${msg}`), xmppDebug: (msg) => console.log(`[XMPP] ${msg}`) }); ``` -------------------------------- ### Get STW Profile Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/STWManager.md Fetches the Save The World profile for a player using their user ID or display name. Handles UserNotFoundError and EpicgamesAPIError. ```typescript public async getProfile(user: string): Promise ``` ```javascript const profile = await client.stw.getProfile('user-id-or-name'); console.log(`Power Level: ${profile.powerLevel}`); console.log(`Humans Defeated: ${profile.humansDefeated}`); ``` ```javascript async function getSTWStats(username) { try { const profile = await client.stw.getProfile(username); console.log(`Username: ${profile.user.displayName}`); console.log(`Power Level: ${profile.powerLevel}`); console.log(`Heroes: ${profile.heroes.length}`); console.log(`Schematics: ${profile.schematics.length}`); console.log(`Survivors: ${profile.survivors.length}`); return profile; } catch (error) { if (error instanceof UserNotFoundError) { console.log('User not found'); } else { console.error('Error:', error); } } } ``` ```javascript async function compareProfiles(user1, user2) { const profile1 = await client.stw.getProfile(user1); const profile2 = await client.stw.getProfile(user2); console.log(`${profile1.user.displayName}`) console.log(` Power Level: ${profile1.powerLevel}`); console.log(` Heroes: ${profile1.heroes.length}`); console.log(`${profile2.user.displayName}`) console.log(` Power Level: ${profile2.powerLevel}`); console.log(` Heroes: ${profile2.heroes.length}`); } ``` -------------------------------- ### Login with Authorization Code and Device Auth Source: https://github.com/fnbrjs/fnbr.js/blob/main/docs/general/auth.md This snippet demonstrates how to log in to fnbr.js. It first attempts to load existing device authentication from a file. If not found, it prompts the user for an authorization code. It also sets up an event listener to save newly created device authentication tokens. ```javascript const { readFile, writeFile } = require('fs').promises; const { Client } = require('fnbr'); (async () => { let auth; try { auth = { deviceAuth: JSON.parse(await readFile('./deviceAuth.json')) }; } catch (e) { auth = { authorizationCode: async () => Client.consoleQuestion('Please enter an authorization code: ') }; } const client = new Client({ auth }); client.on('deviceauth:created', (da) => writeFile('./deviceAuth.json', JSON.stringify(da, null, 2))); await client.login(); console.log(`Logged in as ${client.user.self.displayName}`); })(); ``` -------------------------------- ### Get Creative Island Data Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches a creative island's data using its code. Requires the island code as a string and returns CreativeIslandData. ```typescript public async getCreativeIsland(code: string): Promise ``` ```javascript const island = await client.getCreativeIsland('1234-5678-9012'); ``` -------------------------------- ### Get Battle Royale News Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the current Battle Royale news. Allows specifying a language and providing a custom payload for personalized news. ```typescript public async getBRNews(language?: Language, customPayload?: any): Promise ``` ```javascript const news = await client.getBRNews('en'); ``` -------------------------------- ### BR_REPLAY_METADATA Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Accesses replay metadata storage for Fortnite. ```APIDOC ## GET BR_REPLAY_METADATA ### Description Access replay metadata storage for Fortnite. ### Method GET ### Endpoint https://datastorage-public-service-live.ol.epicgames.com/api/v1/access/fnreplaysmetadata/public ### Parameters #### Query Parameters - **matchId** (string) - Required - The ID of the match. ### Request Example ```http GET https://datastorage-public-service-live.ol.epicgames.com/api/v1/access/fnreplaysmetadata/public?matchId=... Headers: Authorization: Bearer {access_token} Accept: application/json ``` ### Response #### Success Response (200) - **metadata** (object) - Replay metadata. #### Response Example { "example": "{ \"gameVersion\": \"...\", \"mapName\": \"...\" }" } ``` -------------------------------- ### getStorefronts Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches the available storefront content for Fortnite, allowing retrieval of item shop and other featured content details. ```APIDOC ## getStorefronts(language?) ### Description Fetches the current Fortnite storefronts. This includes data about the item shop and other featured content. ### Method `public async getStorefronts(language?: Language): Promise` ### Parameters #### Path Parameters - **language** (Language) - Optional - The language code for the storefront content. Defaults to 'en'. ### Returns - Array of storefront objects ### Throws - `EpicgamesAPIError` ### Example ```javascript const storefronts = await client.getStorefronts('en'); ``` ``` -------------------------------- ### BR_REPLAY Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Accesses the replay data storage for Fortnite. ```APIDOC ## GET BR_REPLAY ### Description Access replay data storage for Fortnite. ### Method GET ### Endpoint https://datastorage-public-service-live.ol.epicgames.com/api/v1/access/fnreplays/public ### Parameters #### Query Parameters - **matchId** (string) - Required - The ID of the match. ### Request Example ```http GET https://datastorage-public-service-live.ol.epicgames.com/api/v1/access/fnreplays/public?matchId=... Headers: Authorization: Bearer {access_token} Accept: application/json ``` ### Response #### Success Response (200) - **replayData** (object) - Replay data. #### Response Example { "example": "{ \"data\": \"...\" }" } ``` -------------------------------- ### Recommended Configuration for Lobby Bot Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Settings optimized for a lobby bot, enabling party creation, friend fetching, XMPP/STOMP connections, and saving party member metadata. ```javascript const client = new Client({ createParty: true, forceNewParty: true, fetchFriends: true, connectToXMPP: true, connectToSTOMP: true, savePartyMemberMeta: true }); ``` -------------------------------- ### BR_TOURNAMENTS_DOWNLOAD Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Downloads tournament data for Fortnite. ```APIDOC ## GET BR_TOURNAMENTS_DOWNLOAD ### Description Download tournament data for Fortnite. ### Method GET ### Endpoint https://events-public-service-live.ol.epicgames.com/api/v1/events/Fortnite/download ### Parameters #### Query Parameters - **region** (string) - Required - Game region (e.g., EU, NAE, NAW, BR, ME, ASIA, OCE) - **lang** (string) - Optional - Language code (e.g., en, de, fr, es) ### Request Example ```http GET https://events-public-service-live.ol.epicgames.com/api/v1/events/Fortnite/download?region=NAE&lang=en Headers: Authorization: Bearer {access_token} Accept: application/json ``` ### Response #### Success Response (200) - **data** (string) - Tournament data in a downloadable format. #### Response Example { "example": "...tournament data..." } ``` -------------------------------- ### Get Battle Royale Stats Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches Battle Royale v2 stats for one or multiple players. Supports specifying a time range and filtering stats for multiple users. ```typescript public async getBRStats(user: string, startTime?: number, endTime?: number): Promise public async getBRStats(user: string[], startTime?: number, endTime?: number, stats?: string[]): Promise ``` ```javascript const stats = await client.getBRStats('user-id-or-name'); const multiple = await client.getBRStats(['user1', 'user2'], undefined, undefined, ['s21_social_bp_level']); ``` -------------------------------- ### Get Battle Royale Account Level Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches Battle Royale account level data for one or multiple users for a specific season. Requires user identifiers and the season number. ```typescript public async getBRAccountLevel(user: string | string[], seasonNumber: number): Promise ``` ```javascript const levels = await client.getBRAccountLevel(['user1', 'user2'], 21); ``` -------------------------------- ### Manage Parties with fnbr.js Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/README.md Create a new party with specified privacy and maximum size, invite a friend by display name, or join an existing party using its ID. Access current party details like size and max size if a party is active. ```javascript // Create party await client.createParty({ privacy: Enums.PartyPrivacy.PRIVATE, maxSize: 4 }); // Invite friend await client.invite('DisplayName'); // Join party await client.joinParty('party-id'); // Access current party if (client.party) { console.log(`Party size: ${client.party.size}/${client.party.maxSize}`); } ``` -------------------------------- ### Handle Party Member Join Event Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Structures.md Listen for the 'party:member:joined' event to log the display name of the joining member and send them a welcome message. ```javascript client.on('party:member:joined', (member) => { console.log(`${member.displayName} joined`); // Send welcome message await member.sendMessage('Welcome to the party!'); }); ``` -------------------------------- ### Get Tournament Metadata Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Retrieves metadata for a specific tournament session using its session ID. It logs details such as the tournament's name, duration, compression status, live status, and timestamp. ```APIDOC ## getMatchInfo(sessionId) ### Description Retrieves metadata for a specific tournament session using its session ID. It logs details such as the tournament's name, duration, compression status, live status, and timestamp. ### Method `async function` ### Parameters #### Path Parameters - **sessionId** (string) - Required - The unique identifier for the tournament session. ### Response #### Success Response Logs tournament metadata to the console. #### Response Example ```json { "name": "Example Tournament", "duration": 3600000, "compressed": false, "live": true, "timestamp": 1678886400 } ``` ### Error Handling - **MatchNotFoundError**: Logs 'Match not found' if the provided sessionId does not correspond to an existing match. ``` -------------------------------- ### Get Party by ID Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Fetches a party using its unique ID. Optionally, raw party data can be returned instead of a formatted Party object. This method can throw errors if the party is not found or if there are permission issues. ```javascript const party = await client.getParty('party-id-here'); ``` -------------------------------- ### Create Party using epicgamesRequest Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/endpoints.md Use the `epicgamesRequest` method to create a new party. This requires a POST request with party configuration data and the appropriate authentication. ```javascript const party = await client.http.epicgamesRequest({ method: 'POST', url: `${Endpoints.BR_PARTY}/parties`, data: { /* config */ } }, AuthSessionStoreKey.Fortnite); ``` -------------------------------- ### Default Authentication Options Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Configures authentication, including authorization code retrieval, EULA checking, token management, and client type. ```typescript auth: { authorizationCode: async () => consoleQuestion('Please enter an authorization code: '), checkEULA: true, killOtherTokens: true, createLauncherSession: false, authClient: 'fortniteAndroidGameClient' } ``` -------------------------------- ### Recommended Configuration for Low Memory Bot Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/configuration.md Optimized settings for a low memory footprint bot, disabling user and presence caching and reducing XMPP keep-alive frequency. ```javascript const client = new Client({ cacheSettings: { users: { maxLifetime: 0, // Don't cache users sweepInterval: 0 }, presences: { maxLifetime: 0, // Don't cache presences sweepInterval: 0 } }, xmppKeepAliveInterval: 60 // Less frequent keep-alives }); ``` -------------------------------- ### Iterating and Finding in Collections Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Structures.md Demonstrates how to iterate over and find specific items within friend and party member collections. ```javascript // Iterate client.friend.list.forEach(friend => { /* ... */ }); client.party.members.forEach(member => { /* ... */ }); // Find const friend = client.friend.list.find(f => f.displayName === 'Name'); const member = client.party.members.get(memberId); ``` -------------------------------- ### waitUntilReady(timeout?) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/Client.md Pauses execution until the client is fully initialized and ready to perform operations. A timeout can be specified to limit the waiting period. ```APIDOC ## waitUntilReady(timeout?) ### Description Pauses execution until the client is fully initialized and ready to perform operations. A timeout can be specified to limit the waiting period. ### Method `public async waitUntilReady(timeout: number = 10000): Promise` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **timeout** (number) - Optional - How long to wait in milliseconds. Defaults to `10000`. ### Request Example ```javascript await client.waitUntilReady(); ``` ### Response #### Success Response `Promise` #### Response Example None ``` -------------------------------- ### getWindowResults Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/TournamentManager.md Fetches the results for a specific tournament window, with options to include live sessions and paginate results. ```APIDOC ## getWindowResults(eventId, eventWindowId, showLiveSessions?, page?) ### Description Fetches the results for a tournament window. ### Method `public async getWindowResults( eventId: string, eventWindowId: string, showLiveSessions?: boolean, page?: number ): Promise` ### Parameters #### Path Parameters - **eventId** (string) - Required - Tournament's event ID - **eventWindowId** (string) - Required - Tournament window's ID #### Query Parameters - **showLiveSessions** (boolean) - Optional - Defaults to false - Whether to show live sessions - **page** (number) - Optional - Defaults to 0 - Results page index ### Response #### Success Response - Returns TournamentWindowResults with leaderboard and player data. #### Throws - `EpicgamesAPIError` ### Example ```javascript const results = await client.tournaments.getWindowResults( 'event-123', 'window-456', true, 0 ); console.log(`Results retrieved for page ${results.page}`); ``` ``` -------------------------------- ### search(prefix, platform?) Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/api-reference/UserManager.md Searches for users based on a display name prefix. An optional platform parameter can be provided to filter results by platform ('epic', 'psn', 'xbl', 'switch'), defaulting to 'epic'. ```APIDOC ## search(prefix, platform?) ### Description Searches for users by display name prefix. ### Method GET (assumed) ### Endpoint `/users/search` (assumed) ### Parameters #### Query Parameters - **prefix** (string) - Required - Display name prefix to search for - **platform** (UserSearchPlatform) - Optional - Default: 'epic' - Platform to search ('epic', 'psn', 'xbl', 'switch') ### Request Example ```javascript const results = await client.user.search('test', 'epic'); results.forEach(result => { console.log(result.user.displayName); }); ``` ### Response #### Success Response (200) - **UserSearchResult[]** (array) - Array of UserSearchResult objects #### Response Example ```json [ { "user": { "id": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4", "displayName": "TestUser1" }, "platform": "epic" } ] ``` ``` -------------------------------- ### AuthOptions Interface Source: https://github.com/fnbrjs/fnbr.js/blob/main/_autodocs/types.md Outlines the configuration options available for authentication processes. It includes various methods for providing credentials and settings for session management. ```typescript interface AuthOptions { deviceAuth?: DeviceAuthResolveable; exchangeCode?: AuthStringResolveable; authorizationCode?: AuthStringResolveable; refreshToken?: AuthStringResolveable; launcherRefreshToken?: AuthStringResolveable; checkEULA?: boolean; killOtherTokens?: boolean; createLauncherSession?: boolean; authClient?: AuthClient; } ```