fnbr.js

repository·main·Indexed 41 days ago

https://github.com/fnbrjs/fnbr.js

An object-oriented library for interacting with Epic Games' Fortnite HTTP and XMPP services. Version 4.3.1 provides a high-level API to manage Fortnite parties, fetch Battle Royale player statistics and account levels, monitor server status, and handle social interactions via a Client class.

Tokens
9.1K
Snippets
22
Records
39
Agent score
50%

What's inside fnbr.js

  1. Quickstart: Create a Fortnite client and handle messages

    main

    To get started, import Client from fnbr, instantiate it, and listen for events like friend:message or ready. Call client.login() to authenticate and start the session. The client.user.self object provides information about the logged-in user.

    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();
  2. Preferred authentication method using Device Auth

    main

    fnbr.js avoids email/password authentication due to captcha issues. The recommended workflow is to use an authorization code to perform an initial login, which then generates a device auth.

    Once a device auth is generated, it consists of an accountId, deviceId, and secret. Unlike authorization codes, device auths do not expire and can be reused for subsequent logins. You can create multiple device auths for a single account.

    const { readFile, writeFile } = require('fs').promises;
    const { Client } = require('fnbr');
    
    (async () => {
      let auth;
      try {
        // Attempt to load existing device auth from a file
        auth = { deviceAuth: JSON.parse(await readFile('./deviceAuth.json')) };
      } catch (e) {
        // If no file exists, prompt the user for a one-time authorization code
        auth = { authorizationCode: async () => Client.consoleQuestion('Please enter an authorization code: ') };
      }
    
      const client = new Client({ auth });
    
      // Listen for the 'deviceauth:created' event to save the new device auth for future use
      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}`);
    })();
  3. Basic usage of the fnbr Client

    main

    The Client class is the primary entry point for interacting with Fortnite's HTTP and XMPP services. You can listen to events like friend:message to handle incoming messages and ready to confirm successful login. Use client.login() to authenticate.

    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();
  4. Configure Client authentication options

    main

    When instantiating a Client, you can provide an auth object in the configuration. The auth object supports two primary modes:

    1. Device Auth Mode: Pass an object containing deviceAuth. The deviceAuth object must contain accountId, deviceId, and secret.
      • Example: { deviceAuth: { accountId: '...', deviceId: '...', secret: '...' } }
    2. Authorization Code Mode: Pass an object containing authorizationCode. This must be an asynchronous function that returns the 32-character code (e.g., using Client.consoleQuestion).
      • Example: { authorizationCode: async () => '...' }
  5. Get Support-A-Creator (SAC) information

    main

    Use getCreatorCode(code) to fetch data associated with a Support-A-Creator slug. This returns a CreatorCode object which includes information about the code and the owner of the code.

    Errors:

    • CreatorCodeNotFoundError: The provided code was not found.
    try {
      const creatorCode = await client.getCreatorCode('mycode123');
      console.log('Owner:', creatorCode.owner.displayName);
    } catch (e) {
      if (e instanceof CreatorCodeNotFoundError) {
        console.error('Invalid code');
      }
    }
  6. Manage parties: create, join, invite, and leave

    main

    The Client class provides high-level methods to manage Fortnite parties:

    • createParty(config?): Creates a new party. If the client is already in a party, it will leave the current one first. You can pass a PartyConfig to customize settings like maxSize and joinability.
    • joinParty(id): Joins an existing party using its unique ID.
    • invite(friend): Sends a party invitation to a specific friend (using their ID or display name).
    • sendRequestToJoin(friend): Sends a request to a friend to join their party. If they accept, the client will receive an invite.
    • leaveParty(createNew?): Leaves the current party. If createNew is true (default), the client will immediately attempt to create a new party.
    • getClientParty(): Fetches the current party the client is associated with.
    • getParty(id, raw?): Fetches a specific party by ID. Setting raw: true returns the raw data; otherwise, it returns a Party instance.
    // Create a new party
    await client.createParty({ maxSize: 4, joinability: 'OPEN' });
    
    // Invite a friend
    await client.invite('FriendDisplayName');
    
    // Join a specific party
    await client.joinParty('party-id-123');
    
    // Leave the current party
    await client.leaveParty();
  7. Initialize and login with the Client class

    main

    The Client class is the primary entrypoint for interacting with Fortnite services. You can initialize it with an optional ClientOptions object and then call .login() to authenticate. By default, if no authentication method is provided in the config, the client will prompt for an authorization code in the console.

    Common configuration options include:

    • platform: The platform to emulate (e.g., 'WIN').
    • auth: Configuration for authentication (e.g., checkEULA, authClient).
    • partyConfig: Settings for the client's party (e.g., privacy, maxSize, joinability).
    • cacheSettings: Settings for managing the lifetime and sweeping of user and presence caches.
    import { Client } from 'fnbrjs';
    
    const client = new Client({
      platform: 'WIN',
      auth: {
        checkEULA: true,
      },
      partyConfig: {
        privacy: 'PUBLIC',
        maxSize: 16,
      }
    });
    
    await client.login();
    console.log('Client is ready!');
  8. Download and parse Blurl streams (Radio/News)

    main

    The downloadBlurlStream(id) method allows you to download and parse .blurl files, which are used for Fortnite radio stations or news videos. It returns a structured object containing language-specific stream URLs and metadata.

    Returns: An object containing:

    • languages: An array of stream objects, each containing a url, language, and variants (audio/video options).
    • data: Metadata including duration, subtitles, aspectratio, etc.
    const stream = await client.downloadBlurlStream('stream-id-here');
    console.log(stream.data.duration);
    console.log(stream.languages[0].url);
  9. Manage client lifecycle: login, logout, and restart

    main

    The Client class provides methods to manage the connection state:

    • login(): Authenticates the client, fetches the user's own profile, connects to XMPP and STOMP services, and initializes the party service.
    • logout(): Revokes all tokens, disconnects XMPP and STOMP, and clears all internal caches.
    • restart(): A convenience method that performs a logout and then a login using the existing refresh token.
    • waitUntilReady(timeout): A utility to wait for the 'ready' event to be emitted, with a default timeout of 10,000ms.
    // Logging in
    await client.login();
    
    // Waiting for readiness
    await client.waitUntilReady(5000);
    
    // Restarting the session
    await client.restart();
    
    // Logging out
    await client.logout();
  10. Manage party members with PartyMember methods

    main

    The PartyMember class provides methods to perform administrative actions on a member. Note that most of these methods require the client to have sufficient permissions (e.g., being the party leader) and will throw a PartyPermissionError if the action is unauthorized.

    Available Methods

    • kick(): Removes the member from the client's party. Throws PartyPermissionError if the client is not a member or not the leader.
    • promote(): Promotes the member. Throws PartyPermissionError if the client is not a member or not the leader.
    • hide(hide?: boolean): Hides or unhides the member. Defaults to true. Throws PartyPermissionError if the client is not the leader.
    • chatBan(): Bans the member from the party's chat.