### Install node-cs2 Source: https://github.com/sak0a/node-cs2/blob/master/README.md Install the package via npm. ```bash npm install node-cs2 ``` -------------------------------- ### Initialize node-cs2 Source: https://github.com/sak0a/node-cs2/blob/master/README.md Basic setup for connecting to the Game Coordinator using steam-user. ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const user = new SteamUser(); const cs2 = new NodeCS2(user); user.logOn({ accountName: 'your_username', password: 'your_password' }); user.on('loggedOn', () => { user.gamesPlayed([730]); // CS2/CS:GO app ID }); user.on('appLaunched', (appid) => { if (appid == 730) { cs2.helloGC(); } }); cs2.on('connectedToGC', async () => { // Inspect an item const item = await cs2.inspectItem('76561198057249394', '2569415699', '7115007497'); console.log('Item:', item); }); ``` -------------------------------- ### Basic Setup and Connection Source: https://context7.com/sak0a/node-cs2/llms.txt Establishes a connection to Steam and the CS2 Game Coordinator. Requires a steam-user instance and manages the GC connection lifecycle. ```APIDOC ## Basic Setup and Connection Establishes a connection to Steam and the CS2 Game Coordinator. The NodeCS2 instance requires a `steam-user` v4.2.0+ instance and automatically manages the GC connection lifecycle. ### Request Example ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const user = new SteamUser(); const cs2 = new NodeCS2(user); user.logOn({ accountName: 'your_username', password: 'your_password' }); user.on('loggedOn', () => { console.log('Logged into Steam'); user.gamesPlayed([730]); // CS2/CS:GO app ID }); user.on('appLaunched', (appid) => { if (appid == 730) { console.log('CS2/CS:GO launched'); cs2.helloGC(); } }); cs2.on('connectedToGC', () => { console.log('Connected to CS2/CS:GO Game Coordinator'); // Ready to use all API methods }); cs2.on('disconnectedFromGC', () => { console.log('Disconnected from Game Coordinator'); }); cs2.on('error', (err) => { console.error('CS2 Error:', err.message); }); ``` ``` -------------------------------- ### Complete Item Inspector Bot Implementation Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md A full example demonstrating Steam authentication, game launch, and sequential item inspection using node-cs2. ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const user = new SteamUser(); const cs2 = new NodeCS2(user); // Configuration const INSPECT_URLS = [ 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198857794835A45540551473D7523863830991655521' // Add more URLs... ]; // Setup user.logOn({ accountName: 'your_username', password: 'your_password' }); user.on('loggedOn', () => { user.gamesPlayed([730]); }); user.on('appLaunched', (appid) => { if (appid == 730) { cs2.helloGC(); } }); cs2.on('connectedToGC', async () => { console.log('Connected! Starting inspections...'); for (const url of INSPECT_URLS) { const match = url.match(/S(\d+)A(\d+)D(\d+)/); if (match) { const [, ownerId, assetId, classId] = match; try { const item = await cs2.inspectItem(ownerId, assetId, classId); console.log(`Item ${assetId}:`, { defindex: item.defindex, paintindex: item.paintindex, paintwear: item.paintwear, stickers: item.stickers?.length || 0 }); } catch (err) { console.error(`Failed to inspect ${assetId}:`, err.message); } // Wait between inspections await new Promise((resolve) => setTimeout(resolve, 1000)); } } }); cs2.on('error', (err) => { console.error('CS2 Error:', err); }); ``` -------------------------------- ### Inspect Item using Callback Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Inspects a specific CS2 item using its owner ID, asset ID, and class ID. This example uses a callback function to handle the result. ```javascript cs2.on('connectedToGC', () => { // Inspect an item cs2.inspectItem('76561198057249394', '2569415699', '7115007497', (item) => { if (!item) { console.log('Item not found or timed out'); return; } console.log('Item inspected:', { defindex: item.defindex, paintindex: item.paintindex, paintwear: item.paintwear, stickers: item.stickers, keychains: item.keychains, variations: item.variations }); }); }); ``` -------------------------------- ### Set Leaderboard Safe Name Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Sets a safe name for the leaderboard. Includes an example of how to handle potential errors during the process. ```javascript // Set safe name cs2.setLeaderboardSafeName('MySafeName123'); ``` ```javascript // With validation try { cs2.setLeaderboardSafeName('ValidName'); } catch (err) { console.error('Invalid name:', err.message); } ``` -------------------------------- ### Establish Connection to CS2 Game Coordinator Source: https://context7.com/sak0a/node-cs2/llms.txt Initializes the NodeCS2 instance and handles the connection lifecycle with the Steam Game Coordinator. ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const user = new SteamUser(); const cs2 = new NodeCS2(user); user.logOn({ accountName: 'your_username', password: 'your_password' }); user.on('loggedOn', () => { console.log('Logged into Steam'); user.gamesPlayed([730]); // CS2/CS:GO app ID }); user.on('appLaunched', (appid) => { if (appid == 730) { console.log('CS2/CS:GO launched'); cs2.helloGC(); } }); cs2.on('connectedToGC', () => { console.log('Connected to CS2/CS:GO Game Coordinator'); // Ready to use all API methods }); cs2.on('disconnectedFromGC', () => { console.log('Disconnected from Game Coordinator'); }); cs2.on('error', (err) => { console.error('CS2 Error:', err.message); }); ``` -------------------------------- ### Connect to CS2 Game Coordinator Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Establishes a connection to the CS2 Game Coordinator. Requires Steam user authentication and launching the CS2 game. ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const user = new SteamUser(); const cs2 = new NodeCS2(user); user.logOn({ accountName: 'your_username', password: 'your_password' }); user.on('loggedOn', () => { console.log('Logged into Steam'); user.gamesPlayed([730]); // CS2/CS:GO app ID }); user.on('appLaunched', (appid) => { if (appid == 730) { console.log('CS2/CS:GO launched'); cs2.helloGC(); } }); cs2.on('connectedToGC', () => { console.log('Connected to CS2/CS:GO Game Coordinator'); // Ready to use! }); ``` -------------------------------- ### Get Casket Contents Source: https://context7.com/sak0a/node-cs2/llms.txt Retrieves the contents of a casket (storage unit) item. Returns cached contents if already loaded, otherwise requests from the Game Coordinator. ```APIDOC ## getCasketContents ### Description Retrieves the contents of a casket (storage unit) item. Returns cached contents if already loaded, otherwise requests from the Game Coordinator. ### Method POST (Implicit, via internal library calls) ### Endpoint `/` (Internal Game Coordinator endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed directly to the function) ### Parameters - **casketId** (number) - Required - The ID of the casket. - **callback** (function) - Optional - A callback function to handle the response or error. ### Request Example ```javascript // Promise-based casket contents retrieval cs2.on('connectedToGC', async () => { try { const casketId = 1234567890; const items = await cs2.getCasketContents(casketId); console.log(`Casket contains ${items.length} items:`); items.forEach((item) => { console.log(`- Item ${item.id}: ${item.def_index}`); }); } catch (err) { if (err.message.includes('No casket matching')) { console.error('Casket not found in inventory'); } else if (err.message.includes('timed out')) { console.error('Loading casket contents timed out'); } } }); // Callback-based cs2.getCasketContents(casketId, (err, items) => { if (err) { console.error('Error:', err.message); return; } console.log('Casket items:', items); }); ``` ### Response #### Success Response (200) - **items** (array) - An array of item objects contained within the casket. #### Response Example ```json [ { "id": "1111111111", "def_index": 100, "quantity": 1 }, { "id": "2222222222", "def_index": 200, "quantity": 1 } ] ``` ``` -------------------------------- ### Get Casket Contents Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Retrieves the items contained within a specified casket (container item). Supports both callback and Promise-based usage. Requires the casket's item ID. ```javascript cs2.getCasketContents(casketId, callback); ``` -------------------------------- ### Migrate from globaloffensive Source: https://github.com/sak0a/node-cs2/blob/master/README.md Demonstrates the drop-in replacement capability for the globaloffensive package. ```javascript // Old const GlobalOffensive = require('globaloffensive'); // New - just change the require! const NodeCS2 = require('node-cs2'); // All your existing code works unchanged! const cs2 = new NodeCS2(steamUser); ``` -------------------------------- ### Instantiate NodeCS2 Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Creates a new instance of the NodeCS2 class. Requires an active steam-user instance. Ensure the steam-user version is compatible to avoid errors. ```javascript new NodeCS2(steamUser); ``` -------------------------------- ### Connection Methods Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Methods for establishing and managing the connection to the Game Coordinator. ```APIDOC ## POST /helloGC ### Description Sends a hello message to the Game Coordinator to establish a connection. ### Method POST ### Endpoint /helloGC ### Response #### Success Response (200) - **result** (undefined) - Returns undefined. ``` -------------------------------- ### Retrieve Casket Contents Source: https://context7.com/sak0a/node-cs2/llms.txt Gets the items contained within a specific casket. It prioritizes cached data and requests from the Game Coordinator if necessary. Handles 'Casket not found' and 'timed out' errors. ```javascript // Promise-based casket contents retrieval cs2.on('connectedToGC', async () => { try { const casketId = 1234567890; const items = await cs2.getCasketContents(casketId); console.log(`Casket contains ${items.length} items:`); items.forEach((item) => { console.log(`- Item ${item.id}: ${item.def_index}`); }); } catch (err) { if (err.message.includes('No casket matching')) { console.error('Casket not found in inventory'); } else if (err.message.includes('timed out')) { console.error('Loading casket contents timed out'); } } }); // Callback-based cs2.getCasketContents(casketId, (err, items) => { if (err) { console.error('Error:', err.message); return; } console.log('Casket items:', items); }); ``` -------------------------------- ### Handle XP Shop and Rewards Source: https://github.com/sak0a/node-cs2/blob/master/README.md Redeem rewards and listen for XP shop notifications. ```javascript // Redeem free reward await cs2.redeemFreeReward(generationTime, redeemableBalance, items); // Listen for XP shop updates cs2.on('xpShopNotification', (data) => { console.log('XP:', data.current_xp, 'Level:', data.current_level); }); ``` -------------------------------- ### openCrate Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Opens a crate using a key item. ```APIDOC ## openCrate ### Description Opens a crate item using a specified key item. ### Parameters - **toolItemId** (number) - Required - The ID of the key item. - **subjectItemId** (number) - Required - The ID of the crate item. - **forRental** (boolean) - Optional - Whether the item is for rental. - **pointsRemaining** (number) - Optional - Remaining points for the operation. ``` -------------------------------- ### Manage Premier Season Data Source: https://github.com/sak0a/node-cs2/blob/master/README.md Set the leaderboard name and listen for season summary updates. ```javascript // Set leaderboard safe name cs2.setLeaderboardSafeName('MySafeName'); // Listen for premier season data cs2.on('premierSeasonSummary', (summary) => { console.log('Premier season:', summary); }); ``` -------------------------------- ### Troubleshooting Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Addresses common issues encountered when using the library and provides solutions, including enabling debug mode. ```APIDOC ## Troubleshooting ### Common Issues #### "Item not found or timed out" - **Cause:** Item doesn't exist, owner is offline, or GC is slow - **Solution:** Verify item exists, check owner status, increase timeout #### "Failed to decode protobuf" - **Cause:** Malformed data received from GC - **Solution:** Retry operation, check network connection #### "Invalid SteamID" - **Cause:** Invalid SteamID format provided - **Solution:** Use valid SteamID64 or SteamID object #### "GC connection lost" - **Cause:** Network issues or GC restart - **Solution:** Reconnect to GC, check network ### Debug Mode Enable debug logging: ```javascript cs2.on('debug', (message) => { console.log('[CS2]', message); }); ``` This will log all GC messages and connection status changes. --- ``` -------------------------------- ### Send Hello GC Message Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Initiates the connection to the Game Coordinator by sending a 'hello' message. This method does not return any value. ```javascript cs2.helloGC(); ``` -------------------------------- ### Handle Connection Events Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listen for Game Coordinator connection status updates and session changes. ```javascript // GC connection status cs2.on('connectedToGC', () => { console.log('Connected to Game Coordinator'); }); cs2.on('disconnectedFromGC', () => { console.log('Disconnected from Game Coordinator'); }); cs2.on('gcConnectionStatus', (status) => { console.log('GC Status:', status); // 0 = HAVE_SESSION // 1 = GC_GOING_DOWN // 2 = NO_SESSION // 3 = NO_SESSION_IN_LOGON_QUEUE // 4 = NO_STEAM }); ``` -------------------------------- ### Connect with Sentry File Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Connects to Steam using a sentry file for authentication, which is recommended for security. The sentry file is saved after a successful login. ```javascript const SteamUser = require('steam-user'); const NodeCS2 = require('node-cs2'); const fs = require('fs'); const user = new SteamUser(); const cs2 = new NodeCS2(user); // Load sentry file if exists if (fs.existsSync('sentry.bin')) { user.logOn({ accountName: 'your_username', password: 'your_password', sentry: fs.readFileSync('sentry.bin') }); } else { user.logOn({ accountName: 'your_username', password: 'your_password' }); } // Save sentry file after login user.on('loggedOn', () => { if (user.sentry) { fs.writeFileSync('sentry.bin', user.sentry); } user.gamesPlayed([730]); }); ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listen to the debug event to capture internal library logs, including garbage collection messages. ```javascript // Enable debug logging cs2.on('debug', (message) => { console.log('[CS2 Debug]', message); }); // This will log all GC messages ``` -------------------------------- ### Listen for Premier Season Summary Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listens for the premier season summary, which includes account ID, season ID, and detailed data per week and per map. Useful for tracking player performance and rankings. ```javascript cs2.on('premierSeasonSummary', (summary) => { console.log('Premier Season Summary:'); console.log('Account ID:', summary.account_id); console.log('Season ID:', summary.season_id); console.log('Data per week:', summary.data_per_week); console.log('Data per map:', summary.data_per_map); // Process weekly data summary.data_per_week.forEach((week) => { console.log(`Week ${week.week_id}: Rank ${week.rank_id}, Matches: ${week.matches_played}`); }); // Process map data summary.data_per_map.forEach((map) => { console.log(`Map ${map.map_id}: ${map.wins}W-${map.losses}L, Kills: ${map.kills}`); }); }); ``` -------------------------------- ### Configuration and Timeouts Source: https://context7.com/sak0a/node-cs2/llms.txt Configuring timeouts for various asynchronous operations to handle network conditions. ```APIDOC ## Configuring Timeouts ### Description All async operations have configurable timeouts. Adjust these based on your use case and network conditions. ### Configuration Fields - **_inspectTimeout** (number) - Item inspection timeout (default: 10000ms) - **_casketTimeout** (number) - Casket loading timeout (default: 30000ms) - **_profileTimeout** (number) - Profile request timeout (default: 10000ms) - **_volatileItemTimeout** (number) - Volatile item timeout (default: 30000ms) - **_missionTimeout** (number) - Mission request timeout (default: 10000ms) - **_rewardTimeout** (number) - Reward redemption timeout (default: 10000ms) - **_crateTimeout** (number) - Crate opening timeout (default: 30000ms) - **_stickerTimeout** (number) - Sticker/patch/keychain operation timeout (default: 10000ms) ``` -------------------------------- ### Performance Considerations Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Provides guidance on optimizing performance, including managing timeouts and using batch operations effectively. ```APIDOC ## Performance Considerations ### Timeouts Default timeouts are conservative. Adjust based on your use case: - **Inspection:** 10s (usually fast) - **Casket Loading:** 30s (can be slow) - **Profile Requests:** 10s (usually fast) - **Volatile Items:** 30s (can be slow) - **Missions:** 10s (usually fast) - **Rewards:** 10s (usually fast) ### Batch Operations When inspecting multiple items, add delays between requests: ```javascript for (const item of items) { await cs2.inspectItem(item.owner, item.assetid, item.classid); await new Promise((resolve) => setTimeout(resolve, 1000)); // 1s delay } ``` ### Memory Management The library maintains minimal state. Inventory data is managed by `steam-user`. ``` -------------------------------- ### applyKeychain Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Applies a keychain to an item. ```APIDOC ## applyKeychain(itemId, keychainId, keychainSlot, callback) ### Description Applies a keychain to an item. ### Parameters #### Path Parameters - **itemId** (number) - Required - The ID of the item to apply keychain to - **keychainId** (number) - Required - The ID of the keychain item - **keychainSlot** (number) - Optional - The slot number for the keychain - **callback** (function) - Optional - Callback function (err, itemIds) => {} ### Response - If callback provided: undefined - If no callback: Promise - Resolves with array of item IDs ``` -------------------------------- ### Message Flow Diagram Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Illustrates the data flow from the application through node-cs2 to the Game Coordinator and back via an EventEmitter. ```text Application → NodeCS2 → steam-user → Game Coordinator ↓ EventEmitter ↓ Application Handlers ``` -------------------------------- ### Implement Event-Driven Item Tracking Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listen for inspectItemInfo and itemCustomizationNotification events to maintain a local state of tracked items. ```javascript class ItemTracker { constructor(cs2) { this.cs2 = cs2; this.items = new Map(); this.setupListeners(); } setupListeners() { this.cs2.on('inspectItemInfo', (item) => { this.items.set(item.itemid, item); this.onItemUpdate(item); }); this.cs2.on('itemCustomizationNotification', (itemIds, type) => { itemIds.forEach((id) => { if (this.items.has(id)) { this.onItemModified(id, type); } }); }); } onItemUpdate(item) { console.log('Item updated:', item.itemid); } onItemModified(itemId, type) { console.log('Item modified:', itemId, type); } } const tracker = new ItemTracker(cs2); ``` -------------------------------- ### Perform Crate and Item Actions Source: https://github.com/sak0a/node-cs2/blob/master/README.md Methods for opening crates and managing stickers, patches, and keychains. ```javascript // Open a crate await cs2.openCrate(toolItemId, subjectItemId); // Extract/encapsulate stickers await cs2.extractSticker(itemId, stickerSlot); await cs2.encapsulateSticker(stickerId); // Apply/remove patches await cs2.applyPatch(itemId, patchId, patchSlot); await cs2.removePatch(itemId, patchSlot); // Apply/remove keychains await cs2.applyKeychain(itemId, keychainId, keychainSlot); cs2.removeKeychain(itemId); ``` -------------------------------- ### Manage Volatile Items Source: https://github.com/sak0a/node-cs2/blob/master/README.md Load contents or claim rewards for temporary or rental items. ```javascript // Load volatile item contents const items = await cs2.loadVolatileItemContents(volatileItemId); // Claim volatile item reward await cs2.claimVolatileItemReward(defindex); ``` -------------------------------- ### Request Game Information Source: https://context7.com/sak0a/node-cs2/llms.txt Requests full match information using either a share code string or a details object. It also includes a listener for the 'matchList' event. ```javascript cs2.on('connectedToGC', () => { // Using share code string const shareCode = 'CSGO-xxxxx-xxxxx-xxxxx-xxxxx-xxxxx'; cs2.requestGame(shareCode); // Using details object cs2.requestGame({ matchId: '1234567890', outcomeId: '9876543210', token: 12345 }); // Listen for match list response cs2.on('matchList', (matches, fullResponse) => { console.log('Received', matches.length, 'matches'); matches.forEach((match) => { console.log('Match:', match); }); }); }); ``` -------------------------------- ### Listen for XP Shop Notifications Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listens for notifications from the XP Shop, providing updates on current XP, level, and pre/post-match status. ```javascript cs2.on('xpShopNotification', (data) => { console.log('XP Shop Update:'); console.log('Current XP:', data.current_xp); console.log('Current Level:', data.current_level); console.log('Prematch:', data.prematch); console.log('Postmatch:', data.postmatch); }); ``` -------------------------------- ### Inspect Items via Promise and Callback APIs Source: https://context7.com/sak0a/node-cs2/llms.txt Retrieves detailed item information including wear, stickers, and keychains. Supports both async/await and callback patterns, as well as parsing from inspect URLs. ```javascript // Promise-based inspection cs2.on('connectedToGC', async () => { try { const item = await cs2.inspectItem('76561198057249394', '2569415699', '7115007497'); console.log('Item Details:', { itemid: item.itemid, defindex: item.defindex, paintindex: item.paintindex, paintseed: item.paintseed, paintwear: item.paintwear, // Float value 0-1 rarity: item.rarity, quality: item.quality, musicindex: item.musicindex, petindex: item.petindex, style: item.style, upgrade_level: item.upgrade_level }); // Process stickers with all fields including highlight_reel and wrapped_sticker if (item.stickers) { item.stickers.forEach((sticker, index) => { console.log(`Sticker ${index}:`, { slot: sticker.slot, sticker_id: sticker.sticker_id, wear: sticker.wear, scale: sticker.scale, rotation: sticker.rotation, highlight_reel: sticker.highlight_reel, wrapped_sticker: sticker.wrapped_sticker }); }); } // Process keychains if (item.keychains) { item.keychains.forEach((keychain) => { console.log('Keychain:', keychain); }); } } catch (err) { console.error('Inspection failed:', err.message); } }); // Callback-based inspection cs2.inspectItem('76561198057249394', '2569415699', '7115007497', (item) => { if (!item) { console.log('Item not found or timed out'); return; } console.log('Item:', item); }); // Inspect from URL (parses S/M/A/D parameters automatically) const url = 'steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198857794835A45540551473D7523863830991655521'; const match = url.match(/S(\d+)A(\d+)D(\d+)/); if (match) { const [, ownerId, assetId, classId] = match; const item = await cs2.inspectItem(ownerId, assetId, classId); } ``` -------------------------------- ### Manage Player Profiles Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listen for profile updates or manually request a player profile. ```javascript // Player profile cs2.on('playersProfile', (profile) => { console.log('Profile received:', profile); }); // Request profile cs2.requestPlayersProfile('76561198057249394').then((profile) => { console.log('Profile:', profile); }); ``` -------------------------------- ### Basic Item Manipulation Source: https://context7.com/sak0a/node-cs2/llms.txt Perform basic item operations like renaming with name tags, permanent deletion, or crafting using recipes. Listen for 'craftingComplete' events. ```javascript cs2.on('connectedToGC', () => { // Rename an item using a name tag const nameTagId = 1234567890; const itemId = 9876543210; const newName = 'My Custom Weapon'; cs2.nameItem(nameTagId, itemId, newName); // Delete an item permanently cs2.deleteItem(itemId); // Craft items using a recipe const itemsToCraft = [1111111111, 2222222222, 3333333333]; const recipeId = 1; cs2.craft(itemsToCraft, recipeId); // Listen for crafting completion cs2.on('craftingComplete', (blueprint, itemIds) => { console.log('Crafting complete!'); console.log('- Recipe ID:', blueprint); console.log('- Result items:', itemIds); }); }); ``` -------------------------------- ### Enable Debug Logging Source: https://context7.com/sak0a/node-cs2/llms.txt Enable debug logging to view GC messages and connection status changes for troubleshooting. Also logs account data upon receipt. ```javascript const cs2 = new NodeCS2(steamUser); // Enable debug logging cs2.on('debug', (message) => { console.log('[CS2 Debug]', new Date().toISOString(), message); }); // Connection status changes cs2.on('connectionStatus', (status, proto) => { const statusNames = { 0: 'HAVE_SESSION', 1: 'GC_GOING_DOWN', 2: 'NO_SESSION', 3: 'NO_SESSION_IN_LOGON_QUEUE', 4: 'NO_STEAM' }; console.log('GC Status:', statusNames[status] || status); }); // Account data received cs2.on('accountData', (data) => { console.log('Account data:', data); }); ``` -------------------------------- ### Open Crate Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md Opens a crate using a tool item ID and a subject item ID. Optional parameters include whether it's for rental and remaining points. Supports callback or Promise-based return. ```javascript openCrate(toolItemId, subjectItemId, forRental, pointsRemaining, callback) ``` -------------------------------- ### redeemFreeReward Source: https://context7.com/sak0a/node-cs2/llms.txt Redeems a free reward from the XP shop system. ```APIDOC ## redeemFreeReward(generationTime, redeemableBalance, items, callback) ### Description Redeems a free reward from the XP shop system. ### Parameters - **generationTime** (number) - Required - The time the reward was generated. - **redeemableBalance** (number) - Required - The current balance available for redemption. - **items** (array) - Required - List of item IDs to redeem. - **callback** (function) - Optional - Callback function to handle the result. ``` -------------------------------- ### Manage Keychains Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Apply or remove keychains from items. ```javascript // Apply keychain to item const itemId = 1234567890; const keychainId = 9876543210; const keychainSlot = 0; // Optional await cs2.applyKeychain(itemId, keychainId, keychainSlot); // Without slot await cs2.applyKeychain(itemId, keychainId); // With callback cs2.applyKeychain(itemId, keychainId, keychainSlot, (err, itemIds) => { if (err) { console.error('Error:', err); return; } console.log('Keychain applied, items:', itemIds); }); ``` ```javascript // Remove keychain from item (fire-and-forget) const itemId = '1234567890'; cs2.removeKeychain(itemId); ``` -------------------------------- ### Inspect Items Source: https://github.com/sak0a/node-cs2/blob/master/README.md Retrieve item details using either promise or callback patterns. ```javascript // Promise style const item = await cs2.inspectItem(owner, assetid, classid); // Callback style cs2.inspectItem(owner, assetid, classid, (item) => { console.log(item); }); ``` -------------------------------- ### Listen for Matchmaking Search Stats Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Listens for matchmaking search statistics, providing information about the game server location, data center, number of players locked in, nearby players, and note level. ```javascript cs2.on('matchmakingSearchStats', (stats) => { console.log('Matchmaking Search Stats:'); console.log('Location ID:', stats.gs_location_id); console.log('Data Center ID:', stats.data_center_id); console.log('Locked In:', stats.num_locked_in); console.log('Found Nearby:', stats.num_found_nearby); console.log('Note Level:', stats.note_level); }); ``` -------------------------------- ### System Events Source: https://github.com/sak0a/node-cs2/blob/master/DETAILED_DOCUMENTATION.md This section details the system events emitted by the CS2 library, including matchmaking statistics, errors, and debug messages. ```APIDOC ## System Events ### `matchmakingSearchStats` Emitted when matchmaking search statistics are received. **Parameters:** - `stats` (Object) - Search statistics object --- ### `error` Emitted when an error occurs. **Parameters:** - `error` (Error) - Error object --- ### `debug` Emitted for debug messages. **Parameters:** - `message` (string) - Debug message ``` -------------------------------- ### Manage Patches Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Apply or remove patches from items. ```javascript // Apply patch to item const itemId = 1234567890; const patchId = 9876543210; const patchSlot = 0; // Optional await cs2.applyPatch(itemId, patchId, patchSlot); // Without slot await cs2.applyPatch(itemId, patchId); // With callback cs2.applyPatch(itemId, patchId, patchSlot, (err, itemIds) => { if (err) { console.error('Error:', err); return; } console.log('Patch applied, items:', itemIds); }); ``` ```javascript // Remove patch from item const itemId = 1234567890; const patchSlot = 0; await cs2.removePatch(itemId, patchSlot); // With callback cs2.removePatch(itemId, patchSlot, (err, itemIds) => { if (err) { console.error('Error:', err); return; } console.log('Patch removed, items:', itemIds); }); ``` -------------------------------- ### Redeem Free Reward from XP Shop Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Redeems a free reward from the XP Shop. Requires the generation time, redeemable balance, and a list of item IDs. Supports both async/await and callback patterns. ```javascript // Redeem free reward const generationTime = Date.now() / 1000; const redeemableBalance = 100; const items = [1234567890, 9876543210]; await cs2.redeemFreeReward(generationTime, redeemableBalance, items); ``` ```javascript // With callback cs2.redeemFreeReward(generationTime, redeemableBalance, items, (err, itemIds) => { if (err) { console.error('Error redeeming reward:', err); return; } console.log('Reward redeemed, items:', itemIds); }); ``` -------------------------------- ### Match Request Methods Source: https://context7.com/sak0a/node-cs2/llms.txt Methods to retrieve recent match history or live game data for players. ```APIDOC ## requestRecentGames(steamid) / requestLiveGames() / requestLiveGameForUser(steamid) ### Description Requests recent matches for a player, current live games, or a specific user's live game. ### Parameters #### Path Parameters - **steamid** (string) - Required - The Steam ID of the user. ``` -------------------------------- ### Open Crates Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Open a crate using a key, supporting both promise-based and callback-based patterns. ```javascript // Open a crate with a key const toolItemId = 1234567890; // Key item ID const subjectItemId = 9876543210; // Crate item ID await cs2.openCrate(toolItemId, subjectItemId); // With optional parameters await cs2.openCrate(toolItemId, subjectItemId, false, 100); // forRental, pointsRemaining // With callback cs2.openCrate(toolItemId, subjectItemId, (err, itemIds) => { if (err) { console.error('Error:', err); return; } console.log('Crate opened, items:', itemIds); }); ``` -------------------------------- ### Crate Opening API Source: https://github.com/sak0a/node-cs2/blob/master/RELEASE_NOTES.md Methods for opening crates within the game environment. ```APIDOC ## POST /openCrate ### Description Opens a crate using a key. Supports both Promise and callback patterns. ### Method POST ### Parameters #### Request Body - **crateId** (string) - Required - The ID of the crate to open - **keyId** (string) - Required - The ID of the key to use ### Response #### Success Response (200) - **status** (string) - Success status of the operation ``` -------------------------------- ### Open CS2 Crate Source: https://context7.com/sak0a/node-cs2/llms.txt Opens a CS2 crate using a specified key item. Supports both promise-based and callback-based operations, and allows for optional parameters like rental status and remaining points. Logs received item IDs or errors. ```javascript cs2.on('connectedToGC', async () => { const keyItemId = 1234567890; // Key item ID const crateItemId = 9876543210; // Crate item ID try { // Basic crate opening const itemIds = await cs2.openCrate(keyItemId, crateItemId); console.log('Crate opened! Received items:', itemIds); } catch (err) { console.error('Failed to open crate:', err.message); } // With optional parameters const forRental = false; const pointsRemaining = 100; await cs2.openCrate(keyItemId, crateItemId, forRental, pointsRemaining); // Callback-based cs2.openCrate(keyItemId, crateItemId, (err, itemIds) => { if (err) { console.error('Error:', err.message); return; } console.log('Received items:', itemIds); }); }); ``` -------------------------------- ### Premier Season & Leaderboards API Source: https://github.com/sak0a/node-cs2/blob/master/EXAMPLES.md Enables setting leaderboard names and listening for updates on Premier Season summaries and matchmaking statistics. ```APIDOC ## Premier Season & Leaderboards API ### Set Leaderboard Safe Name #### Description Sets a safe and valid name for the leaderboard. #### Method `cs2.setLeaderboardSafeName(name)` #### Parameters - **name** (string) - The desired safe name for the leaderboard. #### Request Example ```javascript cs2.setLeaderboardSafeName('MySafeName123'); // With validation try { cs2.setLeaderboardSafeName('ValidName'); } catch (err) { console.error('Invalid name:', err.message); } ``` ### Listen for Premier Season Summary #### Description Listens for summaries of the Premier Season, including performance data per week and per map. #### Method `cs2.on('premierSeasonSummary', (summary) => { ... });` #### Parameters - **summary** (object) - An object containing the Premier Season summary. - **account_id** (number) - The account ID. - **season_id** (number) - The season ID. - **data_per_week** (array) - Performance data aggregated per week. - **week_id** (number) - The week identifier. - **rank_id** (number) - The rank achieved during the week. - **matches_played** (number) - The number of matches played. - **data_per_map** (array) - Performance data aggregated per map. - **map_id** (number) - The map identifier. - **wins** (number) - Number of wins on the map. - **losses** (number) - Number of losses on the map. - **kills** (number) - Total kills on the map. #### Response Example ```javascript { "account_id": 123456789, "season_id": 1, "data_per_week": [ {"week_id": 1, "rank_id": 10, "matches_played": 5} ], "data_per_map": [ {"map_id": 1, "wins": 3, "losses": 2, "kills": 45} ] } ``` ### Listen for Matchmaking Search Stats #### Description Listens for statistics related to matchmaking search, providing insights into server locations and player counts. #### Method `cs2.on('matchmakingSearchStats', (stats) => { ... });` #### Parameters - **stats** (object) - An object containing matchmaking search statistics. - **gs_location_id** (number) - The game server location ID. - **data_center_id** (number) - The data center ID. - **num_locked_in** (number) - Number of players locked in. - **num_found_nearby** (number) - Number of players found nearby. - **note_level** (number) - The note level. ``` -------------------------------- ### Keychain Operations Source: https://context7.com/sak0a/node-cs2/llms.txt Methods to manage keychains on weapon items. ```APIDOC ## applyKeychain(itemId, keychainId, keychainSlot, callback) ### Description Applies a keychain to a weapon item. ### Parameters - **itemId** (number) - Required - The ID of the weapon item. - **keychainId** (number) - Required - The ID of the keychain item. - **keychainSlot** (number) - Optional - The slot number. - **callback** (function) - Optional - Callback function for the result. ## removeKeychain(itemId) ### Description Removes a keychain from a weapon item (fire-and-forget). ### Parameters - **itemId** (string) - Required - The ID of the weapon item. ``` -------------------------------- ### Request Player Profile Source: https://context7.com/sak0a/node-cs2/llms.txt Fetches detailed player profile information. Use the promise-based approach within a 'connectedToGC' event for asynchronous operations or the callback-based method for direct handling. Event listeners can also be set up for specific player profiles. ```javascript // Promise-based profile request cs2.on('connectedToGC', async () => { try { const profile = await cs2.requestPlayersProfile('76561198057249394'); console.log('Player Profile:', profile); } catch (err) { if (err.message.includes('Invalid SteamID')) { console.error('Invalid Steam ID provided'); } else if (err.message.includes('timed out')) { console.error('Profile request timed out'); } } }); // Callback-based with event listener cs2.requestPlayersProfile('76561198057249394', (err, profile) => { if (err) { console.error('Error:', err.message); return; } console.log('Profile:', profile); }); // Listen for specific profile events cs2.on('playersProfile#76561198057249394', (profile) => { console.log('Received profile for specific user:', profile); }); ``` -------------------------------- ### Open Crate Source: https://context7.com/sak0a/node-cs2/llms.txt Opens a crate using a key item. Returns the IDs of items received from the crate opening. ```APIDOC ## openCrate ### Description Opens a crate using a key item. Returns the IDs of items received from the crate opening. ### Method POST (Implicit, via internal library calls) ### Endpoint `/` (Internal Game Coordinator endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Parameters are passed directly to the function) ### Parameters - **toolItemId** (number) - Required - The ID of the key item used to open the crate. - **subjectItemId** (number) - Required - The ID of the crate item to be opened. - **forRental** (boolean) - Optional - Whether the opened item should be for rental. - **pointsRemaining** (number) - Optional - The remaining points for the operation. - **callback** (function) - Optional - A callback function to handle the response or error. ### Request Example ```javascript cs2.on('connectedToGC', async () => { const keyItemId = 1234567890; // Key item ID const crateItemId = 9876543210; // Crate item ID try { // Basic crate opening const itemIds = await cs2.openCrate(keyItemId, crateItemId); console.log('Crate opened! Received items:', itemIds); } catch (err) { console.error('Failed to open crate:', err.message); } // With optional parameters const forRental = false; const pointsRemaining = 100; await cs2.openCrate(keyItemId, crateItemId, forRental, pointsRemaining); // Callback-based cs2.openCrate(keyItemId, crateItemId, (err, itemIds) => { if (err) { console.error('Error:', err.message); return; } console.log('Received items:', itemIds); }); }); ``` ### Response #### Success Response (200) - **itemIds** (array) - An array of item IDs that were received from opening the crate. #### Response Example ```json [ "item_id_1", "item_id_2" ] ``` ``` -------------------------------- ### Request Game Data Source: https://context7.com/sak0a/node-cs2/llms.txt Request recent matches, current live games, or a specific user's live game. Listen for 'matchList' events to receive match data. ```javascript cs2.on('connectedToGC', () => { // Request recent games for a player cs2.requestRecentGames('76561198057249394'); // Request all current live games cs2.requestLiveGames(); // Request live game for specific user cs2.requestLiveGameForUser('76561198057249394'); // Listen for match data cs2.on('matchList', (matches, fullResponse) => { console.log('Matches received:', matches.length); matches.forEach((match) => { console.log('- Match ID:', match.matchid); }); }); }); ``` -------------------------------- ### Manage Volatile Items Source: https://context7.com/sak0a/node-cs2/llms.txt Handle volatile (rental) items by loading their contents with loadVolatileItemContents or claiming rewards with claimVolatileItemReward. Acknowledge rental expiration with acknowledgeRentalExpiration. Both async/await and callback patterns are supported. ```javascript cs2.on('connectedToGC', async () => { // Load volatile item contents const volatileItemId = 1234567890; try { const items = await cs2.loadVolatileItemContents(volatileItemId); console.log('Volatile item contains:', items.length, 'items'); items.forEach((item) => console.log('- Item:', item.id)); } catch (err) { console.error('Failed to load volatile item:', err.message); } // Claim volatile item reward const defindex = 12345; try { const itemIds = await cs2.claimVolatileItemReward(defindex); console.log('Reward claimed! Items:', itemIds); } catch (err) { console.error('Failed to claim reward:', err.message); } // Acknowledge rental expiration cs2.acknowledgeRentalExpiration(volatileItemId); // Callback-based cs2.loadVolatileItemContents(volatileItemId, (err, items) => { if (err) return console.error(err); console.log('Items:', items); }); }); ```