### TypeScript Example: Get Player Count and Info Source: https://github.com/baba33mrt/nationsapi/blob/V4/README.md Instantiate the API with your key and use async functions to fetch player data. It's recommended to store API keys in environment variables. Handle potential API errors by checking for an 'error' property in the response. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; // Il est fortement recommandé de stocker les clés d'API dans des variables d'environnement const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getPlayerInfo() { try { const playerCount = await ngApi.server.getPlayersCount(); console.log('Joueurs en ligne :', playerCount); const player = await ngApi.user.get('baba_33_mrt'); if ('error' in player) { console.error('Erreur lors de la récupération du joueur:', player.error); } else { console.log('Informations sur le joueur:', player); } } catch (error) { console.error('Une erreur inattendue est survenue:', error); } } getPlayerInfo(); ``` -------------------------------- ### Install and Initialize NationsAPI Source: https://context7.com/baba33mrt/nationsapi/llms.txt Install the package using npm, yarn, or pnpm. Initialize the API with your NationsGlory API key, preferably from an environment variable. The API is structured into modules like user, country, server, etc. ```typescript // Installation // npm install @baba33mrt/nationsapi // yarn add @baba33mrt/nationsapi // pnpm add @baba33mrt/nationsapi import NationsAPI from '@baba33mrt/nationsapi'; // Initialisation avec clé API (recommandé via variable d'environnement) const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); // Structure de l'API // ngApi.user - Gestion des utilisateurs // ngApi.country - Gestion des pays // ngApi.server - Données des serveurs // ngApi.oauth - Authentification OAuth // ngApi.ngisland - Gestion des îles NGIsland // ngApi.nabot - Chatbot Nabot // ngApi.webhooks - Gestion des webhooks ``` -------------------------------- ### Install NationsAPI with npm, yarn, or pnpm Source: https://github.com/baba33mrt/nationsapi/blob/V4/README.md Use your preferred package manager to install the NationsAPI library. ```bash # Avec npm npm install @baba33mrt/nationsapi # Avec yarn yarn add @baba33mrt/nationsapi # Avec pnpm pnpm add @baba33mrt/nationsapi ``` -------------------------------- ### Get Server Planning Source: https://context7.com/baba33mrt/nationsapi/llms.txt Fetch the event planning for a specific server and month. Requires an API key. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getServerPlanning() { const planning = await ngApi.server.getPlanning('blue', 12, 2024); if ('error' in planning) { console.error('Erreur:', planning.error); return; } console.log('Planning décembre 2024 (Blue):'); for (const event of planning) { console.log(` ${event.date}: ${event.description}`); } } getServerPlanning(); ``` -------------------------------- ### Server - Get Planning Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves the event planning for a specific server for a given month and year. ```APIDOC ## GET /api/server/planning ### Description Retrieves the event planning for a specific server for a given month and year. ### Method GET ### Endpoint `/api/server/planning` ### Parameters #### Query Parameters - **server** (string) - Required - The name of the server (e.g., 'blue', 'red'). - **month** (integer) - Required - The month for which to retrieve the planning (1-12). - **year** (integer) - Required - The year for which to retrieve the planning. ### Response #### Success Response (200) - **date** (string) - The date of the event (YYYY-MM-DD). - **description** (string) - A description of the event. ### Response Example ```json [ { "date": "2024-12-25", "description": "Christmas Event" } ] ``` ``` -------------------------------- ### Get Country Information Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves all information about a specific country on a given server. ```APIDOC ## GET /api/country/get ### Description Retrieves all information about a specific country on a given server. ### Method GET ### Endpoint `/api/country/get` ### Parameters #### Query Parameters - **server** (string) - Required - The server identifier (e.g., 'blue'). - **countryName** (string) - Required - The name of the country to retrieve information for. ### Request Example ```json { "server": "blue", "countryName": "France" } ``` ### Response #### Success Response (200) - **name** (string) - The name of the country. - **base_name** (string) - The base name of the country. - **empire_name** (string) - The empire name of the country. - **server** (string) - The server the country is on. - **server_type** (string) - The type of server. - **creation_date** (string) - The date the country was created. - **description** (string) - A description of the country. - **bank** (number) - The country's bank balance. - **leader** (string) - The leader of the country. - **count_members** (number) - The number of members in the country. - **members** (array) - A list of country members. - **power** (number) - The current power of the country. - **maxpower** (number) - The maximum power the country can achieve. - **count_claims** (number) - The number of claims the country has. - **mmr** (number) - The MMR (Matchmaking Rating) of the country. - **level** (number) - The level of the country. - **coords** (object) - The coordinates of the country. - **allies** (array) - A list of allied countries. - **enemies** (array) - A list of enemy countries. - **colonies** (array) - A list of colonies. - **flag** (string) - The country's flag in base64 format. #### Response Example ```json { "name": "France", "base_name": "France", "empire_name": "French Empire", "server": "blue", "server_type": "standard", "creation_date": "2023-01-01T10:00:00Z", "description": "A powerful nation.", "bank": 1000000, "leader": "King Louis XIV", "count_members": 50, "members": ["Player1", "Player2"], "power": 5000, "maxpower": 10000, "count_claims": 10, "mmr": 1500, "level": 10, "coords": {"x": 100, "z": 200}, "allies": ["Germany"], "enemies": ["UK"], "colonies": [], "flag": "R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" } ``` ``` -------------------------------- ### Get Player Utility Methods Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieve various player details including description, prime status, HTML and Markdown signatures, account creation date, last connection, and skills across all or specific servers. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getUserDetails() { const username = 'baba_33_mrt'; // Description du joueur const description = await ngApi.user.getDescription(username); if (typeof description === 'string') { console.log('Description:', description); } // Statut Prime const isPrime = await ngApi.user.getPrime(username); if (typeof isPrime === 'boolean') { console.log('Est Prime:', isPrime); } // Signature (HTML) const signature = await ngApi.user.getSignature(username); if (typeof signature === 'string') { console.log('Signature HTML:', signature); } // Signature convertie en Markdown const signatureMd = await ngApi.user.signatureToMD(username); if (typeof signatureMd === 'string') { console.log('Signature Markdown:', signatureMd); } // Date de création du compte const creationDate = await ngApi.user.getCreationDate(username); if (typeof creationDate === 'string') { console.log('Date de création:', creationDate); } // Dernière connexion const lastConnection = await ngApi.user.getLastConnection(username); if (typeof lastConnection === 'string') { console.log('Dernière connexion:', lastConnection); } // Compétences sur tous les serveurs const allSkills = await ngApi.user.getSkills(username); console.log('Compétences (tous serveurs):', allSkills); // Compétences sur un serveur spécifique const blueSkills = await ngApi.user.getSkills(username, 'blue'); console.log('Compétences (Blue):', blueSkills); // { miner: number, lumberjack: number, farmer: number, builder: number, hunter: number, engineer: number } } getUserDetails(); ``` -------------------------------- ### Get Player Information with NationsAPI Source: https://context7.com/baba33mrt/nationsapi/llms.txt Use the `user.get()` method to retrieve comprehensive player data, including profile details, skins, and server-specific information. Handle potential errors by checking the response structure. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getPlayerInfo() { const player = await ngApi.user.get('baba_33_mrt'); if ('error' in player) { console.error('Erreur:', player.error); return; } console.log('Nom d\'utilisateur:', player.username); console.log('Date de création:', player.created_at); console.log('Dernière connexion:', player.last_connection); console.log('Est Prime:', player.is_prime); console.log('Description:', player.description); console.log('Signature:', player.signature); console.log('Skin source:', player.skin.source); // Données par serveur for (const [serverName, serverData] of Object.entries(player.servers)) { console.log(` --- Serveur ${serverName} ---`); console.log('Pays:', serverData.country); console.log('Rang dans le pays:', serverData.country_rank); console.log('Power:', serverData.power, '/', serverData.max_power); console.log('En ligne:', serverData.online); console.log('Temps de jeu:', serverData.playtime); console.log('Groupes:', serverData.groups); if (serverData.skills && typeof serverData.skills === 'object') { console.log('Compétences:', serverData.skills); // { miner, lumberjack, farmer, builder, hunter, engineer } } } } getPlayerInfo(); ``` -------------------------------- ### Server - Get HDV Items Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves the list of items currently for sale on a server's auction house (HDV). ```APIDOC ## GET /api/server/hdv ### Description Retrieves the list of items currently for sale on a server's auction house (HDV). ### Method GET ### Endpoint `/api/server/hdv` ### Parameters #### Query Parameters - **server** (string) - Required - The name of the server (e.g., 'blue', 'red'). ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the item. - **name** (string) - The name of the item. - **price** (integer) - The price of the item. ### Response Example ```json [ { "id": 101, "name": "Sword of Power", "price": 5000 } ] ``` ``` -------------------------------- ### User API - Get Player Information Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves comprehensive information about a NationsGlory player, including profile details, skins, and server-specific data. ```APIDOC ## GET /api/user ### Description Retrieves all information about a NationsGlory player, including their profile, skins, and data on each server. ### Method GET ### Endpoint `/api/user/{username}` ### Parameters #### Path Parameters - **username** (string) - Required - The username of the player to retrieve. ### Request Example ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getPlayerInfo() { const player = await ngApi.user.get('baba_33_mrt'); if ('error' in player) { console.error('Erreur:', player.error); return; } console.log('Nom d\'utilisateur:', player.username); console.log('Date de création:', player.created_at); console.log('Dernière connexion:', player.last_connection); console.log('Est Prime:', player.is_prime); console.log('Description:', player.description); console.log('Signature:', player.signature); console.log('Skin source:', player.skin.source); // Données par serveur for (const [serverName, serverData] of Object.entries(player.servers)) { console.log(`\n--- Serveur ${serverName} ---`); console.log('Pays:', serverData.country); console.log('Rang dans le pays:', serverData.country_rank); console.log('Power:', serverData.power, '/', serverData.max_power); console.log('En ligne:', serverData.online); console.log('Temps de jeu:', serverData.playtime); console.log('Groupes:', serverData.groups); if (serverData.skills && typeof serverData.skills === 'object') { console.log('Compétences:', serverData.skills); // { miner, lumberjack, farmer, builder, hunter, engineer } } } } getPlayerInfo(); ``` ### Response #### Success Response (200) - **username** (string) - The player's username. - **created_at** (string) - The date the player account was created. - **last_connection** (string) - The date of the player's last connection. - **is_prime** (boolean) - Whether the player has a prime subscription. - **description** (string) - The player's description. - **signature** (string) - The player's signature. - **skin** (object) - Information about the player's skin. - **source** (string) - The source of the skin. - **servers** (object) - Data for each server the player is on. - **[serverName]** (object) - Server-specific data. - **country** (string) - The player's country on this server. - **country_rank** (number) - The player's rank within their country on this server. - **power** (number) - The player's current power. - **max_power** (number) - The player's maximum power. - **online** (boolean) - Whether the player is currently online on this server. - **playtime** (number) - The player's playtime on this server. - **groups** (array) - The groups the player belongs to on this server. - **skills** (object) - The player's skills on this server (optional). - **miner** (number) - **lumberjack** (number) - **farmer** (number) - **builder** (number) - **hunter** (number) - **engineer** (number) #### Response Example ```json { "username": "baba_33_mrt", "created_at": "2023-01-01T10:00:00Z", "last_connection": "2024-01-01T12:00:00Z", "is_prime": true, "description": "A test player.", "signature": "Hello!", "skin": { "source": "default" }, "servers": { "blue": { "country": "Testland", "country_rank": 1, "power": 10000, "max_power": 15000, "online": true, "playtime": 1000, "groups": ["admin"], "skills": { "miner": 5, "lumberjack": 3, "farmer": 4, "builder": 5, "hunter": 2, "engineer": 3 } } } } ``` ``` -------------------------------- ### Convert Flag to Buffer Source: https://context7.com/baba33mrt/nationsapi/llms.txt Converts a country's base64 flag string into a Buffer, suitable for image processing. This example demonstrates saving the buffer as a PNG file. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; import fs from 'fs'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function saveFlagAsImage() { const country = await ngApi.country.get('blue', 'France'); if ('error' in country) { console.error('Erreur:', country.error); return; } // Convertir le flag base64 en Buffer const flagBuffer = await ngApi.country.convertFlagToBuffer(country.flag); // Sauvegarder en fichier image fs.writeFileSync('flag_france.png', flagBuffer); console.log('Drapeau sauvegardé dans flag_france.png'); } saveFlagAsImage(); ``` -------------------------------- ### List NGIslands Source: https://context7.com/baba33mrt/nationsapi/llms.txt Get a paginated list of all NGIslands, including details like creator, description, and player counts. Requires an API key. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function listIslands() { // Première page const page1 = await ngApi.ngisland.getAllIslands(1); if ('error' in page1) { console.error('Erreur:', page1.error); return; } console.log('Page actuelle:', page1.current_page); console.log('Total de pages:', page1.total_pages); console.log('Total d\'îles:', page1.total_records); console.log(' Îles:'); for (const island of page1.data) { console.log(` ID: ${island.id}`); console.log(` Nom: ${island.name}`); console.log(` Créateur: ${island.creator}`); console.log(` Description: ${island.description}`); console.log(` Serveur: ${island.serverNumber}`); console.log(` Privée: ${island.isPrivate === 1 ? 'Oui' : 'Non'}`); console.log(` Mot de passe: ${island.password === 1 ? 'Oui' : 'Non'}`); console.log(` Joueurs en ligne: ${island.playersOnline}`); console.log(` Membres en ligne: ${island.membersOnline}`); console.log(` Taille: ${island.size}`); console.log(` Date de création: ${island.creationDate}`); console.log(` Votes: +${island.voteUp} / -${island.voteDown} (diff: ${island.voteDiff})`); console.log(` Visites: ${island.visit}`); console.log(` Membres: ${island.members}`); // Format: "#member1##member2#" } // Parcourir toutes les pages for (let page = 2; page <= page1.total_pages; page++) { const nextPage = await ngApi.ngisland.getAllIslands(page); if (!('error' in nextPage)) { console.log(` Page ${page}:`, nextPage.data.length, 'îles'); } } } listIslands(); ``` -------------------------------- ### Get Player Skin Image URLs Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieve URLs for 2D and 3D player head and body skins, as well as the raw skin source. Specify size and 3D rendering for head and body images. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getPlayerSkins() { const username = 'baba_33_mrt'; // URL de la tête 2D (taille 16-256 pixels) const head2d = await ngApi.user.getHead(username, false, 64); if (typeof head2d === 'string') { console.log('Tête 2D:', head2d); // https://skins.nationsglory.fr/face/username/64 } // URL de la tête 3D avec relief const head3d = await ngApi.user.getHead(username, true, 128); if (typeof head3d === 'string') { console.log('Tête 3D:', head3d); // https://skins.nationsglory.fr/face/3d/username/128 } // URL du corps 2D const body2d = await ngApi.user.getBody(username, false, 64); if (typeof body2d === 'string') { console.log('Corps 2D:', body2d); // https://skins.nationsglory.fr/body/username/64 } // URL du corps 3D avec relief const body3d = await ngApi.user.getBody(username, true, 128); if (typeof body3d === 'string') { console.log('Corps 3D:', body3d); // https://skins.nationsglory.fr/body/3d/username/128 } // Source du skin brut const skinSource = await ngApi.user.getSkin(username); if (typeof skinSource === 'string') { console.log('Source skin:', skinSource); } } getPlayerSkins(); ``` -------------------------------- ### Get Country Notations/Rankings Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves the notations or rankings for countries on a server, optionally filtered by week or specific country. ```APIDOC ## GET /api/country/notations ### Description Retrieves the notations or rankings for countries on a server. ### Method GET ### Endpoint `/api/country/notations` ### Parameters #### Query Parameters - **server** (string) - Required - The server identifier (e.g., 'blue'). - **week** (number) - Optional - The specific week number to retrieve notations for. Defaults to the previous week. - **country** (string) - Optional - The name of a specific country to get notations for. ### Response #### Success Response (200) - Returns an object containing country notations. The structure may vary based on the query parameters. #### Response Example (Default) ```json { "France": {"rank": 1, "score": 1000}, "Germany": {"rank": 2, "score": 950} } ``` #### Response Example (Specific Country) ```json { "France": {"rank": 1, "score": 1000} } ``` ``` -------------------------------- ### NGIsland - Get All Islands Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves a paginated list of all NGIsland islands. Allows fetching islands page by page. ```APIDOC ## GET /api/ngisland/islands ### Description Retrieves a paginated list of all NGIsland islands. This method allows fetching islands page by page. ### Method GET ### Endpoint `/api/ngisland/islands` ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. Defaults to 1. ### Response #### Success Response (200) - **current_page** (integer) - The current page number. - **total_pages** (integer) - The total number of pages available. - **total_records** (integer) - The total number of islands. - **data** (array) - An array of island objects. - **id** (integer) - The unique identifier of the island. - **name** (string) - The name of the island. - **creator** (string) - The username of the island's creator. - **description** (string) - A description of the island. - **serverNumber** (integer) - The server number the island belongs to. - **isPrivate** (integer) - Indicates if the island is private (1 for yes, 0 for no). - **password** (integer) - Indicates if the island has a password (1 for yes, 0 for no). - **playersOnline** (integer) - The number of players currently online on the island. - **membersOnline** (integer) - The number of members currently online on the island. - **size** (integer) - The size of the island. - **creationDate** (string) - The date the island was created. - **voteUp** (integer) - The number of upvotes. - **voteDown** (integer) - The number of downvotes. - **voteDiff** (integer) - The difference between upvotes and downvotes. - **visit** (integer) - The number of visits to the island. - **members** (string) - A string representing the island's members (format: "#member1##member2#"). ### Response Example ```json { "current_page": 1, "total_pages": 10, "total_records": 100, "data": [ { "id": 1, "name": "My Island", "creator": "Player1", "description": "A beautiful island.", "serverNumber": 1, "isPrivate": 0, "password": 0, "playersOnline": 5, "membersOnline": 10, "size": 1000, "creationDate": "2023-01-01", "voteUp": 50, "voteDown": 5, "voteDiff": 45, "visit": 1000, "members": "#member1##member2#" } ] } ``` ``` -------------------------------- ### Server - Get Players Count Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves the number of players connected to the game servers. Can be used for all servers or a specific server. ```APIDOC ## GET /api/server/playersCount ### Description Retrieves the number of players connected to the game servers. This method can be used to get the total player count across all servers or for a specific server. ### Method GET ### Endpoint `/api/server/playersCount` ### Parameters #### Query Parameters - **server** (string) - Optional - The name of the server to get the player count for (e.g., 'blue', 'red'). If not provided, it returns the total count for all servers. ### Response #### Success Response (200) - **count** (integer) - The number of players connected. ### Response Example ```json { "count": 1500 } ``` ``` -------------------------------- ### Get Country Notations and Rankings Source: https://context7.com/baba33mrt/nationsapi/llms.txt Fetches country notations and rankings for a server. Supports fetching for a default week (previous), a specific week number, or for a particular country. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getNotations() { // Notations avec semaine par défaut (semaine précédente) const notationsDefault = await ngApi.country.getNotations({ server: 'blue' }); console.log('Notations (défaut):', notationsDefault); // Notations pour une semaine spécifique const notationsWeek = await ngApi.country.getNotations({ server: 'blue', week: 100 }); console.log('Notations semaine 100:', notationsWeek); // Notations pour un pays spécifique const notationsCountry = await ngApi.country.getNotations({ server: 'blue', country: 'France' }); console.log('Notations France:', notationsCountry); } getNotations(); ``` -------------------------------- ### Get HDV Items Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieve a list of items available on a server's auction house (HDV). Requires an API key. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getHDVItems() { const hdvItems = await ngApi.server.getHDV('blue'); if ('error' in hdvItems) { console.error('Erreur:', hdvItems.error); return; } console.log('Objets en vente sur l\'HDV (Blue):'); for (const item of hdvItems) { console.log(` ID: ${item.id}`); console.log(` Nom: ${item.name}`); console.log(` Prix: ${item.price}`); console.log(' ---'); } } getHDVItems(); ``` -------------------------------- ### Get Country Information Source: https://context7.com/baba33mrt/nationsapi/llms.txt Fetches all details for a specific country on a given server. Handles potential errors during the API call. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getCountryInfo() { const country = await ngApi.country.get('blue', 'France'); if ('error' in country) { console.error('Erreur:', country.error); return; } console.log('Nom:', country.name); console.log('Nom de base:', country.base_name); console.log('Nom d\'empire:', country.empire_name); console.log('Serveur:', country.server); console.log('Type de serveur:', country.server_type); console.log('Date de création:', country.creation_date); console.log('Description:', country.description); console.log('Banque:', country.bank); console.log('Leader:', country.leader); console.log('Nombre de membres:', country.count_members); console.log('Membres:', country.members); console.log('Power:', country.power, '/', country.maxpower); console.log('Nombre de claims:', country.count_claims); console.log('MMR:', country.mmr); console.log('Level:', country.level); console.log('Coordonnées:', country.coords); console.log('Alliés:', country.allies); console.log('Ennemis:', country.enemies); console.log('Colonies:', country.colonies); console.log('Flag (base64):', country.flag.substring(0, 50) + '...'); } getCountryInfo(); ``` -------------------------------- ### Get Player Count Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieve the total number of players online across all servers or on a specific server. Requires an API key. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function getPlayerCount() { // Nombre de joueurs sur tous les serveurs const totalPlayers = await ngApi.server.getPlayersCount(); if ('error' in totalPlayers) { console.error('Erreur:', totalPlayers.error); return; } console.log('Joueurs totaux:', totalPlayers); // Nombre de joueurs sur un serveur spécifique const bluePlayers = await ngApi.server.getPlayersCount('blue'); if (!('error' in bluePlayers)) { console.log('Joueurs Blue:', bluePlayers); } const redPlayers = await ngApi.server.getPlayersCount('red'); if (!('error' in redPlayers)) { console.log('Joueurs Red:', redPlayers); } } getPlayerCount(); ``` -------------------------------- ### User Utility Methods Source: https://context7.com/baba33mrt/nationsapi/llms.txt Provides various utility methods to retrieve specific player information such as description, prime status, signature, creation date, last connection, and skills. ```APIDOC ## GET /api/user/getDescription ### Description Retrieves the player's description. ### Method GET ### Endpoint `/api/user/getDescription` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **description** (string) - The player's description. ## GET /api/user/getPrime ### Description Checks if the player has Prime status. ### Method GET ### Endpoint `/api/user/getPrime` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **isPrime** (boolean) - True if the player has Prime status, false otherwise. ## GET /api/user/getSignature ### Description Retrieves the player's signature in HTML format. ### Method GET ### Endpoint `/api/user/getSignature` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **signature** (string) - The player's signature in HTML. ## GET /api/user/signatureToMD ### Description Converts the player's signature to Markdown format. ### Method GET ### Endpoint `/api/user/signatureToMD` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **signatureMd** (string) - The player's signature in Markdown format. ## GET /api/user/getCreationDate ### Description Retrieves the date when the player's account was created. ### Method GET ### Endpoint `/api/user/getCreationDate` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **creationDate** (string) - The account creation date. ## GET /api/user/getLastConnection ### Description Retrieves the date of the player's last connection. ### Method GET ### Endpoint `/api/user/getLastConnection` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. ### Response #### Success Response (200) - **lastConnection** (string) - The date of the last connection. ## GET /api/user/getSkills ### Description Retrieves the player's skills. Can be filtered by server. ### Method GET ### Endpoint `/api/user/getSkills` ### Parameters #### Query Parameters - **username** (string) - Required - The username of the player. - **server** (string) - Optional - The specific server to get skills for (e.g., 'blue'). If not provided, skills for all servers are returned. ### Response #### Success Response (200) - **skills** (object) - An object containing the player's skills. Structure: `{ miner: number, lumberjack: number, farmer: number, builder: number, hunter: number, engineer: number }`. #### Response Example ```json { "skills": { "miner": 10, "lumberjack": 8, "farmer": 12, "builder": 9, "hunter": 7, "engineer": 11 } } ``` ``` -------------------------------- ### Manage OAuth Services Source: https://context7.com/baba33mrt/nationsapi/llms.txt Create, modify, check access tokens, and delete OAuth services for authentication. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function manageOAuthService() { // Créer un nouveau service OAuth const createResult = await ngApi.oauth.createService( 'Mon Application', 'https://monapp.com/callback' ); console.log('Service créé:', createResult); // Modifier un service OAuth existant const patchResult = await ngApi.oauth.patchService( 'https://monapp.com/new-callback', 'contact@monapp.com', 'Mon Application v2' ); console.log('Service modifié:', patchResult); // Vérifier un token d'accès const checkResult = await ngApi.oauth.checkAccessToken( 'access_token_ici', 'client_secret_ici' ); if ('error' in checkResult) { console.error('Token invalide:', checkResult.error); } else { console.log('Token valide:', checkResult); } // Supprimer le service OAuth const deleteResult = await ngApi.oauth.deleteService(); console.log('Service supprimé:', deleteResult); } manageOAuthService(); ``` -------------------------------- ### List Countries on a Server Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves lists of created and available countries on a given server. ```APIDOC ## GET /api/country/list ### Description Retrieves lists of created and available countries on a given server. ### Method GET ### Endpoint `/api/country/list` ### Parameters #### Query Parameters - **server** (string) - Required - The server identifier (e.g., 'blue'). ### Response #### Success Response (200) - **claimed** (array) - A list of created countries. Each object contains: - **name** (string) - The name of the created country. - **availables** (array) - A list of available countries. Each object contains: - **name** (string) - The name of the available country. - **x** (number) - The x-coordinate of the available country. - **z** (number) - The z-coordinate of the available country. #### Response Example ```json { "claimed": [ {"name": "France"}, {"name": "Germany"} ], "availables": [ {"name": "Spain", "x": 50, "z": 75}, {"name": "Italy", "x": -25, "z": 100} ] } ``` ``` ```APIDOC ## GET /api/country/created ### Description Retrieves a list of only the created countries on a given server. ### Method GET ### Endpoint `/api/country/created` ### Parameters #### Query Parameters - **server** (string) - Required - The server identifier (e.g., 'blue'). ### Response #### Success Response (200) - Returns an array of country names that are created. #### Response Example ```json ["France", "Germany"] ``` ``` ```APIDOC ## GET /api/country/availables ### Description Retrieves a list of only the available countries on a given server. ### Method GET ### Endpoint `/api/country/availables` ### Parameters #### Query Parameters - **server** (string) - Required - The server identifier (e.g., 'blue'). ### Response #### Success Response (200) - Returns an array of available countries. Each object contains: - **name** (string) - The name of the available country. - **x** (number) - The x-coordinate of the available country. - **z** (number) - The z-coordinate of the available country. #### Response Example ```json [ {"name": "Spain", "x": 50, "z": 75}, {"name": "Italy", "x": -25, "z": 100} ] ``` ``` -------------------------------- ### List Countries on a Server Source: https://context7.com/baba33mrt/nationsapi/llms.txt Retrieves all countries on a server, including both created and available ones. Also shows how to fetch only created or only available countries. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function listCountries() { // Récupérer tous les pays (créés et disponibles) const allCountries = await ngApi.country.getCountries('blue'); if ('error' in allCountries) { console.error('Erreur:', allCountries.error); return; } console.log('Pays créés:'); for (const claimed of allCountries.claimed) { console.log(' -', claimed.name); } console.log('\nPays disponibles:'); for (const available of allCountries.availables) { console.log(` - ${available.name} (x: ${available.x}, z: ${available.z})`); } // Récupérer uniquement les pays créés const createdCountries = await ngApi.country.getCreatedCountries('blue'); if (!('error' in createdCountries)) { console.log('\nPays créés (filtré):', createdCountries.length); } // Récupérer uniquement les pays disponibles const availableCountries = await ngApi.country.getAvailablesCountries('blue'); if (!('error' in availableCountries)) { console.log('Pays disponibles (filtré):', availableCountries.length); } } listCountries(); ``` -------------------------------- ### Register and Manage Webhooks Source: https://context7.com/baba33mrt/nationsapi/llms.txt Register URLs to receive notifications for country creation, disbandment, and leader changes. Includes listing, retrieving, and removing webhooks. ```typescript import NationsAPI from '@baba33mrt/nationsapi'; const ngApi = new NationsAPI(process.env.NATIONSGLORY_API_KEY); async function manageWebhooks() { // Enregistrer un webhook pour la création de pays const createWebhook = await ngApi.webhooks.createCountry( 'https://monapp.com/webhook/country-created' ); console.log('Webhook création pays:', createWebhook); // Enregistrer un webhook pour la dissolution de pays const disbandWebhook = await ngApi.webhooks.disbandCountry( 'https://monapp.com/webhook/country-disbanded' ); console.log('Webhook dissolution pays:', disbandWebhook); // Enregistrer un webhook pour le changement de leader const leaderWebhook = await ngApi.webhooks.changeLeader( 'https://monapp.com/webhook/leader-changed' ); console.log('Webhook changement leader:', leaderWebhook); // Lister tous les webhooks enregistrés const allWebhooks = await ngApi.webhooks.getAllWebhooks(); if ('error' in allWebhooks) { console.error('Erreur:', allWebhooks.error); return; } console.log(' Tous les webhooks:'); for (const webhook of allWebhooks) { console.log(` ID: ${webhook.id}`); console.log(` URL: ${webhook.url}`); console.log(` Event: ${webhook.eventType}`); console.log(' ---'); } // Récupérer un webhook spécifique const specificWebhook = await ngApi.webhooks.getWebhook(123); if (!('error' in specificWebhook)) { console.log('Webhook 123:', specificWebhook); } // Supprimer un webhook const removeResult = await ngApi.webhooks.removeWebhook(123); console.log('Webhook supprimé:', removeResult); } manageWebhooks(); ``` -------------------------------- ### API Webhooks - Event Listening Source: https://context7.com/baba33mrt/nationsapi/llms.txt Register URLs to receive notifications for country events. ```APIDOC ## API Webhooks - Écouter les événements ### Description L'API Webhooks permet d'enregistrer des URLs pour recevoir des notifications lors d'événements de pays. ### Methods - `createCountry(url: string)`: Registers a webhook for country creation events. - `disbandCountry(url: string)`: Registers a webhook for country disbandment events. - `changeLeader(url: string)`: Registers a webhook for leader change events. - `getAllWebhooks()`: Retrieves a list of all registered webhooks. - `getWebhook(webhookId: number)`: Retrieves a specific webhook by its ID. - `removeWebhook(webhookId: number)`: Removes a webhook by its ID. ### Request Example (createCountry) ```typescript const createWebhook = await ngApi.webhooks.createCountry( 'https://monapp.com/webhook/country-created' ); console.log('Webhook création pays:', createWebhook); ``` ### Response Example (createCountry) ```json { "id": 1, "url": "https://monapp.com/webhook/country-created", "eventType": "COUNTRY_CREATED" } ``` ### Request Example (getAllWebhooks) ```typescript const allWebhooks = await ngApi.webhooks.getAllWebhooks(); console.log(allWebhooks); ``` ### Response Example (getAllWebhooks) ```json [ { "id": 1, "url": "https://monapp.com/webhook/country-created", "eventType": "COUNTRY_CREATED" }, { "id": 2, "url": "https://monapp.com/webhook/country-disbanded", "eventType": "COUNTRY_DISBANDED" } ] ``` ### Request Example (getWebhook) ```typescript const specificWebhook = await ngApi.webhooks.getWebhook(123); console.log(specificWebhook); ``` ### Response Example (getWebhook) ```json { "id": 123, "url": "https://monapp.com/webhook/leader-changed", "eventType": "LEADER_CHANGED" } ``` ### Request Example (removeWebhook) ```typescript const removeResult = await ngApi.webhooks.removeWebhook(123); console.log('Webhook supprimé:', removeResult); ``` ### Response Example (removeWebhook) ```json { "message": "Webhook with ID 123 deleted successfully." } ``` ```