### Install clashofclans.js Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/INDEX.md Install the clashofclans.js library using npm. This is the first step to using the library in your project. ```bash npm install clashofclans.js ``` -------------------------------- ### Client Setup with Custom Cache Store Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Initialize the Client with a custom cache store object that implements get, set, delete, and clear methods. The example uses a Map for storage and sets a default TTL of 1 hour. ```typescript // Custom cache store with 1-hour TTL const customStore = new Map(); const client = new Client({ keys: ['your_api_key'], cache: { set: (key, value, ttl) => { customStore.set(key, { value, expires: Date.now() + (ttl || 3600000) }); return true; }, get: (key) => { const item = customStore.get(key); if (!item || item.expires < Date.now()) return null; return item.value; }, delete: (key) => customStore.delete(key), clear: () => customStore.clear() } }); ``` -------------------------------- ### Minimal Client Setup Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Initialize the Client with only the required API key. ```typescript const client = new Client({ keys: ['your_api_key'] }); ``` -------------------------------- ### Client Setup with Caching Enabled Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Initialize the Client and enable the built-in caching mechanism. ```typescript // Enable caching const client = new Client({ keys: ['your_api_key'], cache: true }); ``` -------------------------------- ### Get Player Details Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Fetches detailed information for a specific player using their tag. The example logs the player's name, town hall level, trophies, and counts of troops, spells, and heroes. ```typescript public async getPlayer(playerTag: string, options?: OverrideOptions): Promise ``` ```typescript const player = await client.getPlayer('#PLAYERID'); console.log(`${player.name} - TH${player.townHallLevel}, ${player.trophies} trophies`); console.log(`Troops: ${player.troops.length}, Spells: ${player.spells.length}, Heroes: ${player.heroes.length}`); ``` -------------------------------- ### Clan Operations Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Provides examples for common clan-related operations, including searching for clans, retrieving a specific clan's details, listing members, fetching the war log, and getting capital raid season information. ```APIDOC ## Clan Operations ```typescript // Search clans const clans = await client.getClans({ name: 'Blue', minClanLevel: 5, limit: 50 }); // Get single clan const clan = await client.getClan('#8QU8J9LP'); // Get members const members = await client.getClanMembers('#8QU8J9LP', { limit: 50 }); // Get war log const wars = await client.getClanWarLog('#8QU8J9LP'); // Get capital raids const raids = await client.getCapitalRaidSeasons('#8QU8J9LP'); ``` ``` -------------------------------- ### Pagination Example Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Demonstrates how to fetch clan members with pagination and how to request the next page using the 'after' cursor. ```APIDOC ## Pagination List endpoints support cursor-based pagination: **Request:** ```typescript const members = await client.getClanMembers('#TAG', { limit: 50 }); // members has structure: ClanMember[] (direct) // RestManager.getClanMembers returns: // { body: { items: [...], paging: { after: "cursor", before: "cursor" } }, res: {...} } ``` **Next page:** ```typescript const nextPage = await client.getClanMembers('#TAG', { limit: 50, after: members.paging?.after }); ``` ``` -------------------------------- ### Client Setup with Custom Rate Limiter Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Initialize the Client with a custom QueueThrottler to manage request rates. Requires importing QueueThrottler. ```typescript // Custom rate limiter (10 requests/sec) const { Client, QueueThrottler } = require('clashofclans.js'); const client = new Client({ keys: ['your_api_key'], throttler: new QueueThrottler(100) }); ``` -------------------------------- ### Example Usage of request Method Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/rest-manager.md Demonstrates how to call the request method and access the response body and status. ```typescript const result = await handler.request('/clans/%238QU8J9LP', { cache: true }); console.log(result.body.name); console.log(result.res.status, result.res.path); ``` -------------------------------- ### Login with Email and Password Source: https://github.com/clashperk/clashofclans.js/blob/main/README.md This method should be called once when the application starts to authenticate using email and password. ```APIDOC ## Login with Email Password ### Description Authenticates the client using email and password credentials. This method should be called once when the application starts. ### Method `client.login({ email: 'developer@email.com', password: '***' })` ### Parameters #### Request Body - **email** (string) - Required - The developer's email address. - **password** (string) - Required - The developer's password. ``` -------------------------------- ### Import Client Class Source: https://github.com/clashperk/clashofclans.js/blob/main/README.md Import the Client class from the clashofclans.js library. Ensure Node.js 20 or newer is installed. ```javascript const { Client } = require('clashofclans.js'); ``` -------------------------------- ### Rate Limiting Handling Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Explains the API rate limits and provides an example of how to configure a throttler to manage request rates. ```APIDOC ## Rate Limiting All endpoints are subject to per-API-key rate limiting: - Default limit: ~10-15 requests per second per key - Exceeded: Returns 429 status with `requestThrottled` reason - Headers may include `Retry-After` (check error details) **Handling:** ```typescript const throttler = new QueueThrottler(100); // 10 req/sec const client = new Client({ keys, throttler }); ``` ``` -------------------------------- ### Redis Store Implementation Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md An example implementation of the `Store` interface using Redis. It handles serialization and deserialization of values and uses `setex` for time-to-live functionality. ```typescript // Redis store implementation class RedisStore { constructor(redisClient) { this.redis = redisClient; } async set(key, value, ttl) { await this.redis.setex(key, Math.ceil(ttl / 1000), JSON.stringify(value)); return true; } async get(key) { const value = await this.redis.get(key); return value ? JSON.parse(value) : null; } async delete(key) { return (await this.redis.del(key)) > 0; } async clear() { await this.redis.flushdb(); } } const client = new Client({ keys: ['your_key'], cache: new RedisStore(redisConnection) }); ``` -------------------------------- ### Login with Email and Password Source: https://github.com/clashperk/clashofclans.js/blob/main/README.md Log in to the API using email and password credentials. This method should be called once when the application starts. It then fetches clan information. ```javascript const client = new Client(); (async function () { // This method should be called once when application starts. await client.login({ email: 'developer@email.com', password: '***' }); const clan = await client.getClan('#2PP'); console.log(`${clan.name} (${clan.tag})`); })(); ``` -------------------------------- ### Get Clan War Leagues Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Fetches a list of all available leagues used in Clan Wars. ```typescript public async getWarLeagues(options?: SearchOptions): Promise ``` -------------------------------- ### Documentation Structure Overview Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/MANIFEST.txt This snippet provides a high-level overview of the documentation files and their primary content, guiding users to the most relevant sections for their needs. ```APIDOC ## Documentation Files This project provides comprehensive technical documentation for the Clash of Clans API wrapper. The documentation is organized into several files, each focusing on a specific aspect of the library: - **README.md**: General overview and module organization. - **INDEX.md**: Main entry point, quick start, and architecture. - **QUICK-REFERENCE.md**: A one-page cheat sheet for common operations. - **client.md**: Complete reference for the `Client` class, including all public methods. - **structures.md**: Documentation for data structure classes like `Clan`, `Player`, etc. - **rest-manager.md**: Details on the `RestManager` and low-level request handling. - **configuration.md**: Comprehensive guide to `ClientOptions`, `LoginOptions`, and other configuration settings. - **types.md**: All TypeScript type definitions, interfaces, and enums. - **endpoints.md**: Detailed reference for all HTTP endpoints, including parameters and status codes. - **errors.md**: Information on `HttpError`, reason codes, and error handling patterns. - **utilities.md**: Helper functions and utility classes. ``` -------------------------------- ### Error Handling Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Provides an example of how to handle potential HTTP errors when making API requests. ```APIDOC ## Error Handling This pattern demonstrates how to gracefully handle errors that may occur during API interactions, specifically focusing on `HttpError`. ### Usage Wrap your API calls in a `try...catch` block. Check the error type and reason for specific handling. ### Example ```typescript try { const clan = await client.getClan('#TAG'); } catch (err) { if (err instanceof HttpError && err.reason === 'notFound') { console.log('Clan not found'); } else { throw err; // Re-throw other errors } } ``` ``` -------------------------------- ### constructor(options?: ClientOptions) Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Initializes a new `Client` instance with optional configuration. This allows setting up API keys, caching, or custom throttlers for API requests. ```APIDOC ## `constructor(options?: ClientOptions)` ### Description Initializes a new `Client` instance with optional configuration. This allows setting up API keys, caching, or custom throttlers for API requests. ### Signature `constructor(options?: ClientOptions)` ### Parameters - **options** (`ClientOptions`) - Optional - Configuration options for the client ### Example ```typescript const { Client } = require('clashofclans.js'); // With API keys const client = new Client({ keys: ['your_api_key'] }); // With caching enabled const client = new Client({ cache: true }); // With custom throttler const { Client, QueueThrottler } = require('clashofclans.js'); const client = new Client({ throttler: new QueueThrottler(100) }); ``` ``` -------------------------------- ### Get Current Gold Pass Season Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves details about the current Gold Pass season, including start and end times. ```APIDOC ## GET /goldpass/seasons/current - Get Current Gold Pass Season ### Description Retrieves details about the current Gold Pass season, including start and end times. ### Method GET ### Endpoint /goldpass/seasons/current ``` -------------------------------- ### Get Builder Base Leagues Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Fetches a list of leagues specific to the Builder Base game mode. ```typescript public async getBuilderBaseLeagues(options?: SearchOptions): Promise ``` -------------------------------- ### Client Initialization with Request Options Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Example of initializing the client with custom request handler options, including setting the maximum number of connections, pipelining, and an error handler. ```typescript const client = new Client({ keys: ['your_key'], connections: 2, pipelining: 5, onError: ({ path, status, body }) => { console.error(`API Error: ${path} ${status}`, body); } }); ``` -------------------------------- ### Initialize and Fetch Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Shows the basic pattern for initializing the client and fetching data for a clan. ```APIDOC ## Initialize and Fetch This pattern demonstrates the fundamental steps of creating a client instance and retrieving data. ### Steps 1. **Initialize Client**: Create a new `Client` instance, providing your API keys. 2. **Fetch Data**: Use a client method (e.g., `getClan`) to retrieve specific data. ### Example ```typescript const client = new Client({ keys: ['YOUR_API_KEY'] }); const clan = await client.getClan('#8QU8J9LP'); console.log(`${clan.name} - Level ${clan.level}`); ``` ``` -------------------------------- ### Client Initialization and Options Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Demonstrates how to initialize the Clashofclans.js client with various configuration options. ```APIDOC ## Client Initialization ### Description Initializes a new client instance for interacting with the Clash of Clans API. ### Constructor `Client(options?: ClientOptions)` ### Parameters #### `options` (ClientOptions) - `keys` (string[]) - Required - API keys for authentication. - `baseURL` (string) - Optional - The API endpoint URL. Defaults to the official API endpoint. - `cache` (boolean | Store) - Optional - Enables or configures caching. Defaults to disabled. - `throttler` (Throttler | null) - Optional - Configures rate limiting. Defaults to none. - `retryLimit` (number) - Optional - Number of retries for 5XX errors. Defaults to 0. - `restRequestTimeout` (number) - Optional - Timeout in milliseconds for REST requests. Defaults to 0. ``` -------------------------------- ### Get Current Gold Pass Season Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves details about the current Gold Pass season, including start and end times. The client method returns the season object directly, while the rest method returns a paginated result. ```typescript client.getGoldPassSeason(options?: OverrideOptions): Promise rest.getGoldPassSeason(options?: OverrideOptions): Promise> ``` -------------------------------- ### GET /clans/{clanTag}/members - Get Clan Members Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of members for a specific clan, with support for pagination. ```APIDOC ## GET /clans/{clanTag}/members - Get Clan Members ### Description Retrieves a list of members for a specific clan, with support for pagination. ### Method GET ### Endpoint /clans/{clanTag}/members ### Parameters #### Path Parameters - **clanTag** (string) - Required - The unique tag of the clan (e.g., %238QU8J9LP). #### Query Parameters - **limit** (number) - Optional - Results per page (1-50) - **after** (string) - Optional - Pagination cursor - **before** (string) - Optional - Pagination cursor ### Response #### Success Response (200) - List of clan members with pagination #### Error Response - **404** — Clan not found ``` -------------------------------- ### Import & Initialize Client Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to import the necessary components from the clashofclans.js library and initialize the client, either with an API key or with email and password for login. ```APIDOC ## Import & Initialize ```typescript const { Client, QueueThrottler, Util } = require('clashofclans.js'); // With API key const client = new Client({ keys: ['your_api_key'], cache: true, throttler: new QueueThrottler(100) }); // With email/password const client = new Client(); await client.login({ email: 'dev@email.com', password: 'pass' }); ``` ``` -------------------------------- ### Get League Tiers List Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Fetch a paginated list of all league tiers. This endpoint is recommended over the deprecated 'Get Leagues' endpoint. ```typescript client.getLeaguesTiers(options?: SearchOptions): Promise rest.getLeagueTiers(options?: SearchOptions): Promise> ``` -------------------------------- ### Store Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/types.md Interface for custom cache implementations, defining methods for setting, getting, deleting, and clearing cache entries. ```APIDOC ## Store Custom cache implementation interface. ```typescript interface Store { set: (key: string, value: T, ttl?: number) => boolean | Promise; get: (key: string) => T | null | Promise; delete: (key: string) => boolean | Promise; clear: () => void | Promise; } ``` ``` -------------------------------- ### GET /clans/{clanTag}/capitalraidseasons - Get Capital Raids Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves the Capital Raid seasons for a specific clan, with support for pagination. ```APIDOC ## GET /clans/{clanTag}/capitalraidseasons - Get Capital Raids ### Description Retrieves the Capital Raid seasons for a specific clan, with support for pagination. ### Method GET ### Endpoint /clans/{clanTag}/capitalraidseasons ### Parameters #### Path Parameters - **clanTag** (string) - Required - The unique tag of the clan (e.g., %238QU8J9LP). #### Query Parameters - **limit** (number) - Optional - Results per page (default 10) - **after** (string) - Optional - Pagination cursor - **before** (string) - Optional - Pagination cursor ### Response #### Success Response (200) - Capital raid seasons with pagination #### Error Response - **404** — Clan not found ``` -------------------------------- ### Instantiate Client with API Keys Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Create a new Client instance with your API keys. Ensure you have obtained these from the Clash of Clans developer portal. ```typescript const { Client } = require('clashofclans.js'); // With API keys const client = new Client({ keys: ['your_api_key'] }); ``` -------------------------------- ### GET /clans/{clanTag}/warlog - Get Clan War Log Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves the war history for a specific clan, with support for pagination. ```APIDOC ## GET /clans/{clanTag}/warlog - Get Clan War Log ### Description Retrieves the war history for a specific clan, with support for pagination. ### Method GET ### Endpoint /clans/{clanTag}/warlog ### Parameters #### Path Parameters - **clanTag** (string) - Required - The unique tag of the clan (e.g., %238QU8J9LP). #### Query Parameters - **limit** (number) - Optional - Results per page (default 20) - **after** (string) - Optional - Pagination cursor - **before** (string) - Optional - Pagination cursor ### Response #### Success Response (200) - War history with pagination #### Error Response - **403** — War log is private or access denied - **404** — Clan not found ``` -------------------------------- ### GET /clans/{clanTag}/currentwar - Get Current Clan War Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves the details of the current clan war, including attacks. ```APIDOC ## GET /clans/{clanTag}/currentwar - Get Current Clan War ### Description Retrieves the details of the current clan war, including attacks. ### Method GET ### Endpoint /clans/{clanTag}/currentwar ### Parameters #### Path Parameters - **clanTag** (string) - Required - The unique tag of the clan (e.g., %238QU8J9LP). ### Response #### Success Response (200) - Current war details with attacks #### Error Response - **403** — Access denied (war is private or clan not in war) - **404** — Clan not found ``` -------------------------------- ### ClientOptions Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/types.md Configuration options for initializing the API client. ```APIDOC ## ClientOptions Client initialization configuration. ```typescript interface ClientOptions { keys?: string[]; baseURL?: string; retryLimit?: number; cache?: boolean | Store; restRequestTimeout?: number; throttler?: QueueThrottler | BatchThrottler | null; } ``` Used by: `Client` constructor ``` -------------------------------- ### Determine if Friendly War Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/utilities.md Determines if a war is friendly based on the duration between preparation start and war start times. Pass in Date objects for both times. ```typescript export function isFriendlyWar(preparationStartTime: Date, startTime: Date): boolean ``` ```typescript const war = await client.getClanWar('#CLAN_TAG'); if (isFriendlyWar(war.preparationStartTime, war.startTime)) { console.log('This is a friendly war'); } ``` -------------------------------- ### Get Builder Base Leagues (Client) Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of Builder Base leagues using the client interface. Options can be provided for filtering or pagination. ```typescript client.getBuilderBaseLeagues(options?: SearchOptions): Promise ``` -------------------------------- ### login Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/rest-manager.md Initializes the manager by creating API keys. Returns a promise that resolves with an array of API keys. ```APIDOC ## POST /login ### Description Initializes the manager by creating API keys. ### Method POST ### Endpoint /login ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (`LoginOptions`) - Required - Configuration for login operations. ### Request Example ```json { "email": "your_email@example.com", "password": "your_password" } ``` ### Response #### Success Response (200) - **apiKeys** (`string[]`) - An array of API keys. #### Response Example ```json [ "key1", "key2" ] ``` ``` -------------------------------- ### GET /clans/{clanTag}/currentwar/leaguegroup - Get CWL Group Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves the Clan War League (CWL) group details for a clan, including participating clans and rounds. ```APIDOC ## GET /clans/{clanTag}/currentwar/leaguegroup - Get CWL Group ### Description Retrieves the Clan War League (CWL) group details for a clan, including participating clans and rounds. ### Method GET ### Endpoint /clans/{clanTag}/currentwar/leaguegroup ### Parameters #### Path Parameters - **clanTag** (string) - Required - The unique tag of the clan (e.g., %238QU8J9LP). ### Response #### Success Response (200) - CWL group with participating clans and rounds #### Error Response - **404** — Clan not found or not in CWL ``` -------------------------------- ### Fetch League and Data Information Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Get data for various league tiers, war leagues, locations, labels, and the current Gold Pass season. ```typescript // League tiers const tiers = await client.getLeaguesTiers(); // Builder base leagues const bbLeagues = await client.getBuilderBaseLeagues(); // Capital leagues const capLeagues = await client.getCapitalLeagues(); // War leagues const warLeagues = await client.getWarLeagues(); // Locations const locations = await client.getLocations(); // Labels const clanLabels = await client.getClanLabels(); const playerLabels = await client.getPlayerLabels(); // Gold pass const goldPass = await client.getGoldPassSeason(); ``` -------------------------------- ### Get Location Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a specific game location by its ID. ```APIDOC ## GET /locations/{locationId} - Get Location ### Description Retrieves a specific game location by its ID. ### Method GET ### Endpoint /locations/{locationId} ### Parameters #### Path Parameters - **locationId** (number) - Required - The ID of the location to retrieve. ### Response #### Success Response (200) - **location** (APILocation) - The requested location object. ``` -------------------------------- ### Client Class Methods Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/MANIFEST.txt The `client.md` file provides a complete reference for the `Client` class, which is the main entry point for interacting with the API. It details over 40 public methods. ```APIDOC ## Client Class Reference (`client.md`) The `Client` class serves as the primary interface for developers to interact with the Clash of Clans API. It exposes a rich set of over 40 public methods, categorized for ease of use: - **Clan Operations**: Methods for retrieving clan information (e.g., `getClan`, `getClanMembers`). - **War Operations**: Methods related to clan wars (e.g., `getCurrentWar`, `getWarLog`). - **Player Operations**: Methods for fetching player data (e.g., `getPlayer`). - **Ranking Operations**: Access to leaderboards and rankings. - **League Operations**: Information about leagues and tournaments. - **Reference Data**: Methods to fetch static game data. Each method is documented with its signature, parameters, return types, and usage examples. ``` -------------------------------- ### Get Capital League Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a specific Capital league by its ID. ```APIDOC ## GET /capitalleagues/{leagueId} - Get Capital League ### Description Retrieves a specific Capital league by its ID. ### Method GET ### Endpoint /capitalleagues/{leagueId} ### Parameters #### Path Parameters - **leagueId** (number) - Required - The ID of the Capital league to retrieve. ### Response #### Success Response (200) - **league** (APICapitalLeague) - The requested Capital league object. ``` -------------------------------- ### Get War Leagues List Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Fetch a list of available War Leagues, supporting pagination with limit, after, and before cursors. Use this to find leagues for further queries. ```typescript client.getWarLeagues(options?: SearchOptions): Promise rest.getWarLeagues(options?: SearchOptions): Promise> ``` -------------------------------- ### Run Build and Development Commands Source: https://github.com/clashperk/clashofclans.js/blob/main/CLAUDE.md Common commands for building, testing, and linting the clashofclans.js library. Ensure you have the necessary environment variables configured for testing. ```bash npm run prepare # Clean dist/ and rebuild (rimraf + tsc + ESM wrapper) npm run build # TypeScript compile + generate ESM wrapper npm run lint:test # Run ESLint checks npm run lint:fix # Auto-fix ESLint issues npm test # Run Jest tests (TZ=UTC, loads .env) npm run test:watch # Jest in watch mode npm run test:bun # Run tests with Bun runtime ``` -------------------------------- ### Get Player League History Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Fetches the league history for a specific player. ```typescript // League history const history = await client.getLeagueHistory('#PLAYERID'); ``` -------------------------------- ### Authentication with Direct API Keys Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/INDEX.md Initialize the client using an array of direct API keys. This method is suitable for multi-key deployments. ```typescript const client = new Client({ keys: ['key1', 'key2', 'key3'] }); ``` -------------------------------- ### Login and Generate API Keys Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Initialize the client by logging in with your developer site credentials to create or retrieve API keys. This method returns an array of API keys. ```typescript const client = new Client(); const keys = await client.login({ email: 'developer@email.com', password: 'password' }); console.log('API Keys:', keys); ``` -------------------------------- ### Get Player Labels Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of player labels with optional pagination. ```APIDOC ## GET /labels/players - Get Player Labels ### Description Retrieves a list of player labels with optional pagination. ### Method GET ### Endpoint /labels/players #### Query Parameters - **limit** (number) - Optional - The maximum number of results to return. - **after** (string) - Optional - Used for pagination to fetch the next set of results. ``` -------------------------------- ### init Method Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/rest-manager.md Initializes the RequestHandler by creating API keys using email and password. Returns a promise that resolves with the generated API keys. ```typescript public async init(options: LoginOptions): Promise ``` -------------------------------- ### Get Clan Labels Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of clan labels with optional pagination. ```APIDOC ## GET /labels/clans - Get Clan Labels ### Description Retrieves a list of clan labels with optional pagination. ### Method GET ### Endpoint /labels/clans #### Query Parameters - **limit** (number) - Optional - The maximum number of results to return. - **after** (string) - Optional - Used for pagination to fetch the next set of results. ``` -------------------------------- ### Configuration Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Shows how to configure the client for rate limiting, caching, and request options. ```APIDOC ## Configuration ### Description Shows how to configure the client for rate limiting, caching, and request options. ### Rate Limiting #### `new QueueThrottler(delay: number)` Creates a new queue throttler with a specified delay between requests (in milliseconds). #### `new BatchThrottler(limit: number)` Creates a new batch throttler with a specified limit on requests per second. ### Caching #### `new Client({ cache: boolean | Store })` Initializes the client with caching enabled. Can use the built-in in-memory cache or a custom store implementation. ### Request Options #### `client.getClan(tag: string, options?: RequestOptions): Promise` Retrieves clan data. Supports options to control caching, force refresh, retry limits, rate limit ignoring, and request timeouts. #### `RequestOptions` - **cache** (boolean) - Optional - Whether to cache this request. - **force** (boolean) - Optional - Whether to bypass the cache and force a fresh request. - **retryLimit** (number) - Optional - Override the default retry count for this request. - **ignoreRateLimit** (boolean) - Optional - Whether to skip the throttler for this request. - **restRequestTimeout** (number) - Optional - Set a custom timeout for the REST request in milliseconds. ``` -------------------------------- ### Get League Tier Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves details for a specific League Tier by its ID. ```APIDOC ## GET /leaguetiers/{leagueId} - Get League Tier ### Description Retrieves details for a specific League Tier by its ID. ### Method GET ### Endpoint /leaguetiers/105000036 ``` -------------------------------- ### Get War League Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves details for a specific War League by its ID. ```APIDOC ## GET /warleagues/{leagueId} - Get War League ### Description Retrieves details for a specific War League by its ID. ### Method GET ### Endpoint /warleagues/48000001 ``` -------------------------------- ### Get League Group Info Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Retrieves information about a specific league group and season. ```typescript public async getLeagueGroup(leagueGroupTag: string, seasonId: string, options?: OverrideOptions): Promise ``` -------------------------------- ### Initialize Client and Fetch Clan Data Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Initialize the client with your API key and fetch clan data using its tag. Log the clan's name and level. ```typescript const client = new Client({ keys: ['api_key'] }); const clan = await client.getClan('#8QU8J9LP'); console.log(`${clan.name} - Level ${clan.level}`); ``` -------------------------------- ### Get Capital Leagues Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Retrieves a list of all available leagues for the Capital game mode. ```typescript public async getCapitalLeagues(options?: SearchOptions): Promise ``` -------------------------------- ### Get League Tiers Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Retrieves a list of all available league tiers within the game. ```typescript public async getLeaguesTiers(options?: SearchOptions): Promise ``` -------------------------------- ### login(options: LoginOptions): Promise Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Authenticates the client by creating or retrieving API keys from the Clash of Clans developer site using an email and password. It returns a promise that resolves with an array of API keys. ```APIDOC ## `login(options: LoginOptions): Promise` ### Description Initialize the client by creating API keys from email and password. ### Signature `public login(options: LoginOptions): Promise` ### Parameters - **options** (`LoginOptions`) - Required - Email, password, and optional key configuration - **options.email** (`string`) - Required - Developer site email address - **options.password** (`string`) - Required - Developer site password - **options.keyName** (`string`) - Optional - Name of API key(s) - **options.keyCount** (`number`) - Optional - Number of allowed API keys - **options.keyDescription** (`string`) - Optional - Description of API key(s) ### Returns `Promise` - Array of API keys created or existing ### Example ```typescript const client = new Client(); const keys = await client.login({ email: 'developer@email.com', password: 'password' }); console.log('API Keys:', keys); ``` ``` -------------------------------- ### Configuration Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Client options, authentication methods, caching strategies, and request configurations are detailed in the configuration documentation. ```APIDOC ## Configuration ### Description This section covers the various options available for configuring the `Client` instance, including authentication, caching, and other request-specific settings. ### Key Configuration Areas - **Client Options**: General settings for the client. - **Authentication**: How to provide API tokens. - **Caching**: Strategies for caching API responses. - **Request Configuration**: Settings related to HTTP requests. ### Reference - **[configuration.md](configuration.md)**: Comprehensive guide to client configuration options. ``` -------------------------------- ### Get Player Battle Log Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Retrieves the battle log history for a specific player. ```typescript // Battle log const battles = await client.getBattleLog('#PLAYERID'); ``` -------------------------------- ### Get Locations Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of all available game locations (countries). Supports pagination. ```APIDOC ## GET /locations - Get Locations ### Description Retrieves a list of all available game locations (countries). Supports pagination. ### Method GET ### Endpoint /locations ### Query Parameters - **limit** (number) - Optional - Maximum number of results to return. - **after** (string) - Optional - Pagination cursor for fetching subsequent results. ### Response #### Success Response (200) - **items** (Location[]) - A list of game location objects. ``` -------------------------------- ### Login with Email and Password to Create API Keys Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Authenticate with your developer email and password to create new API keys. You can specify the name, count, and description for the keys. ```typescript const client = new Client(); const keys = await client.login({ email: 'developer@email.com', password: 'password', keyName: 'clashofclans.js', keyCount: 3, keyDescription: 'API client for bot' }); console.log('Created keys:', keys); ``` -------------------------------- ### Get Capital Leagues Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of Capital leagues. Supports pagination and filtering. ```APIDOC ## GET /capitalleagues - Get Capital Leagues ### Description Retrieves a list of Capital leagues. Supports pagination and filtering. ### Method GET ### Endpoint /capitalleagues ### Query Parameters - **limit** (number) - Optional - Maximum number of results to return. - **after** (string) - Optional - Pagination cursor for fetching subsequent results. ### Response #### Success Response (200) - **items** (APICapitalLeague[]) - A list of Capital league objects. ``` -------------------------------- ### LoginOptions Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/configuration.md Options for the `client.login()` method to create API keys. This interface specifies the required email and password, along with optional parameters for naming, counting, and describing the generated API keys. ```APIDOC ## LoginOptions ### Description Options for the `client.login()` method to create API keys. This interface specifies the required email and password, along with optional parameters for naming, counting, and describing the generated API keys. ### Parameters #### Request Body - **email** (`string`) - Required - Email address for developer.clashofclans.com - **password** (`string`) - Required - Account password - **keyName** (`string`) - Optional - Name for created API key(s) (Default: Auto) - **keyCount** (`number`) - Optional - Number of keys to create (Default: 1) - **keyDescription** (`string`) - Optional - Description for created key(s) (Default: Auto) ### Request Example ```typescript const client = new Client(); const keys = await client.login({ email: 'developer@email.com', password: 'password', keyName: 'clashofclans.js', keyCount: 3, keyDescription: 'API client for bot' }); console.log('Created keys:', keys); ``` ``` -------------------------------- ### Get Builder Base League Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a specific Builder Base league by its ID. ```APIDOC ## GET /builderbaseleagues/{leagueId} - Get Builder Base League ### Description Retrieves a specific Builder Base league by its ID. ### Method GET ### Endpoint /builderbaseleagues/{leagueId} ### Parameters #### Path Parameters - **leagueId** (number) - Required - The ID of the Builder Base league to retrieve. ### Response #### Success Response (200) - **league** (APIBuilderBaseLeague) - The requested Builder Base league object. ``` -------------------------------- ### Pagination Pattern Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Demonstrates how to implement cursor-based pagination for list endpoints. ```APIDOC ## Pagination Pattern List endpoints support cursor-based pagination using the `after` cursor. ### Usage To fetch the next page of results, use the `after` cursor provided in the previous response's `paging` object. ### Example ```typescript // First page const members = await client.getClanMembers('#TAG', { limit: 50 }); // Next page (using the 'after' cursor from the previous response) const nextPage = await client.getClanMembers('#TAG', { limit: 50, after: response.body.paging?.after }); ``` ``` -------------------------------- ### Get War Leagues Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves a list of available War Leagues with pagination support. ```APIDOC ## GET /warleagues - Get War Leagues ### Description Retrieves a list of available War Leagues with pagination support. ### Method GET ### Endpoint /warleagues ### Query Parameters #### Query Parameters - **limit** (number) - Optional - Results per page - **after** (string) - Optional - Pagination cursor - **before** (string) - Optional - Pagination cursor ### Responses #### Success Response (200) - List of war leagues with pagination ``` -------------------------------- ### Initialize Client with Email/Password Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Initializes and logs in the clashofclans.js client using email and password credentials. ```typescript // With email/password const client = new Client(); await client.login({ email: 'dev@email.com', password: 'pass' }); ``` -------------------------------- ### Get Battle Log Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/endpoints.md Retrieves the recent battle log entries for a given player. ```APIDOC ## GET /players/{playerTag}/battlelog ### Description Retrieves the recent battle log entries for a given player. ### Method GET ### Endpoint /players/%23PLAYERID/battlelog ### Parameters #### Path Parameters - **playerTag** (string) - Required - The unique identifier of the player. ### Responses #### Success Response (200) - Recent battle log entries #### Error Responses - **404** - Player not found ``` -------------------------------- ### Get Clan Information Source: https://github.com/clashperk/clashofclans.js/blob/main/README.md Retrieves detailed information about a specific clan using its tag. ```APIDOC ## Get Clan Information ### Description Fetches detailed information about a clan based on its unique tag. ### Method `client.getClan('#2PP')` ### Parameters #### Path Parameters - **tag** (string) - Required - The unique tag of the clan (e.g., '#2PP'). ``` -------------------------------- ### LoginOptions Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/types.md Configuration options for logging in and creating API keys. ```APIDOC ## LoginOptions Credentials for creating API keys. ```typescript interface LoginOptions { email: string; password: string; keyName?: string; keyCount?: number; keyDescription?: string; } ``` Used by: `Client.login()`, `RestManager.login()` ``` -------------------------------- ### Basic Usage of clashofclans.js Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/INDEX.md Initialize the client with an API key and fetch clan, player, or war data. This snippet demonstrates fundamental operations. ```typescript const { Client } = require('clashofclans.js'); // Initialize with API key const client = new Client({ keys: ['your_api_key'] }); // Fetch clan const clan = await client.getClan('#8QU8J9LP'); console.log(`${clan.name} - Level ${clan.level}, ${clan.memberCount} members`); // Fetch player const player = await client.getPlayer('#PLAYERID'); console.log(`${player.name} - TH${player.townHallLevel}, ${player.trophies} trophies`); // Get clan war const war = await client.getClanWar('#8QU8J9LP'); war.clan.attacks.forEach(attack => { console.log(`${attack.attacker.name} → ${attack.defender.name}: ${attack.stars}⭐ ${attack.destruction}%`); }); ``` -------------------------------- ### Get Gold Pass Season Info Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Fetches information about the current Gold Pass season. ```typescript public async getGoldPassSeason(options?: OverrideOptions): Promise ``` -------------------------------- ### Utilities and Helpers Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Provides utility functions, cache stores, and constants for common tasks and game data. ```APIDOC ## Utilities and Helpers ### Description This module exposes various utility functions, helper classes, and constants that can be used to simplify common tasks when working with the library and game data. ### Included Components - **`Util`**: A collection of general utility functions. - **`CacheStore`**: A class for managing cached data. - **Constants**: Game data constants (e.g., troop names, spell types). - **Helpers**: Additional helper functions. ### Reference - **[utilities.md](utilities.md)**: Detailed documentation for all utility functions and helpers. ``` -------------------------------- ### Get Game Locations Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Retrieves a comprehensive list of all geographical locations recognized within the game. ```typescript public async getLocations(options?: SearchOptions): Promise ``` -------------------------------- ### Get Legend League Season IDs Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Fetches a list of season identifiers for the Legend League. ```typescript public async getLeagueSeasons(options?: SearchOptions): Promise ``` -------------------------------- ### Get Player Information Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Retrieves detailed information for a specific player using their player tag. ```typescript // Get player const player = await client.getPlayer('#PLAYERID'); ``` -------------------------------- ### Event System Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/README.md Details on how to subscribe to and handle events emitted by the client. ```APIDOC ## Event System ### Description The client utilizes the standard Node.js EventEmitter for emitting events. ### Available Events - `debug`: Emitted for debug information. - Parameters: `path` (string), `status` (number), `message` (string) - `error`: Emitted when an error occurs. - Parameters: `error` (unknown) - `rateLimited`: Emitted when the client is rate limited. - Parameters: `path` (string), `status` (number), `message` (string) ### Example ```typescript client.on('debug', (path: string, status: number, message: string) => {}); client.on('error', (error: unknown) => {}); client.on('rateLimited', (path: string, status: number, message: string) => {}); ``` ``` -------------------------------- ### Get Single Clan Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Retrieves detailed information for a specific clan using its clan tag. ```typescript // Get single clan const clan = await client.getClan('#8QU8J9LP'); ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Initializes the clashofclans.js client using an API key. Supports caching and rate limiting. ```typescript const { Client, QueueThrottler, Util } = require('clashofclans.js'); // With API key const client = new Client({ keys: ['your_api_key'], cache: true, throttler: new QueueThrottler(100) }); ``` -------------------------------- ### Instantiate Client with Caching Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Create a new Client instance with caching enabled to reduce redundant API calls. This can improve performance for frequently accessed data. ```typescript // With caching enabled const client = new Client({ cache: true }); ``` -------------------------------- ### RestManager Login Method Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/rest-manager.md Initializes the manager by creating API keys. Returns a promise that resolves with an array of API keys. ```typescript public login(options: LoginOptions): Promise ``` -------------------------------- ### Get Clan Capital Ranks Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/client.md Retrieves clan capital rankings. Accepts a location ID or 'global'. ```typescript public async getClanCapitalRanks(locationId: number | 'global', options?: SearchOptions): Promise ``` -------------------------------- ### Data Access Patterns Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates different ways to access player data using the client, RestManager, or RequestHandler. ```APIDOC ## Data Access Patterns ```typescript // Via Client (recommended) const player = await client.getPlayer('#TAG'); console.log(player.name, player.troops[0].name); // Via RestManager (raw API) const { body } = await client.rest.getPlayer('#TAG'); console.log(body.name, body.troops[0].name); // Via RequestHandler (lowest level) const result = await client.rest.requestHandler.request('/players/%23TAG'); console.log(result.body.name, result.res.status); ``` ``` -------------------------------- ### Troubleshooting Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Provides solutions for common issues like invalid API keys, rate limiting, network timeouts, IP blocking, and private war logs. ```APIDOC ## Troubleshooting **API Key invalid?** ```typescript // Check at developer.clashofclans.com client.setKeys(['new_key']); ``` **Rate limited?** ```typescript // Add throttler const client = new Client({ keys: ['key'], throttler: new QueueThrottler(200) // Slower }); ``` **Network timeout?** ```typescript // Increase timeout const clan = await client.getClan('#TAG', { restRequestTimeout: 15000 // 15 seconds }); ``` **IP blocked?** ```typescript // Whitelist IP at developer.clashofclans.com ``` **War log private?** ```typescript // Clan leader must enable "Public War Log" ``` ``` -------------------------------- ### Get Multiple Players Source: https://github.com/clashperk/clashofclans.js/blob/main/_autodocs/QUICK-REFERENCE.md Fetches information for multiple players simultaneously by providing an array of player tags. ```typescript // Get multiple players const players = await client.getPlayers(['#P1', '#P2', '#P3']); ```