steam-tradeoffer-manager

repository·master·Indexed 20 days ago

https://github.com/doctormckay/node-steam-tradeoffer-manager

A self-contained manager for Steam trade offers designed for Node.js v4.0.0 or later. It provides a trade offers API to handle the complexities of implementing trade offers within an application, including the TradeOfferManager class for managing offers and the EconItem class for normalizing Steam economy item data. Key features include creating and retrieving trade offers, fetching inventory contents, and managing authentication via cookies.

Tokens
2.4K
Snippets
10
Records
12
Agent score
70%

What's inside steam-tradeoffer-manager

  1. Initialize TradeOfferManager

    master

    To use the library, instantiate the TradeOfferManager class. You can pass an optional options object to configure behavior such as polling intervals, data persistence, and language.

    Key Configuration Options:

    • steam: An instance of steam-user (optional, but enables automatic polling on new items).
    • community: An instance of steamcommunity (defaults to new SteamCommunity()).
    • domain: The domain to use for WebAPI requests (defaults to localhost).
    • language: The language for inventory and offer descriptions (e.g., 'en', 'zh', 'pt-BR').
    • pollInterval: How often to poll for updates in milliseconds (default: 30000).
    • dataDirectory: Path to save poll data for persistence.
    • savePollData: Boolean to enable saving poll data to disk.
    • useAccessToken: Boolean to enable using access tokens if an API key is unavailable (default: true).
    const TradeOfferManager = require('node-steam-tradeoffer-manager');
    
    const manager = new TradeOfferManager({
        language: 'en',
        pollInterval: 30000,
        savePollData: true
    });
  2. Retrieve Inventory Contents

    master

    You can fetch the inventory contents of yourself or another user.

    Get your own inventory

    getInventoryContents(appid, contextid, tradableOnly, callback)

    Get another user's inventory

    getUserInventoryContents(sid, appid, contextid, tradableOnly, callback)

    Parameters:

    • sid: The SteamID of the user (string or SteamID object).
    • appid: The Steam application ID.
    • contextid: The ID of the inventory context.
    • tradableOnly: Boolean; if true, only returns tradable items and currencies.
    • callback: (err, contents) => {}.
    manager.getInventoryContents(730, 2, true, (err, contents) => {
        if (err) return console.error(err);
        console.log('Inventory contents:', contents);
    });
  3. Get image URLs from an EconItem

    master

    The EconItem class provides methods to construct Steam's CDN URLs for item images using the icon_url and icon_url_large properties.

    • getImageURL(): Returns the standard size image URL.
    • getLargeImageURL(): Returns the large size image URL. If icon_url_large is not present, it falls back to the standard getImageURL().
    // Assuming 'item' is an instance of EconItem
    const smallImage = item.getImageURL();
    const largeImage = item.getLargeImageURL();
  4. Create a new TradeOffer

    master

    Use createOffer() to construct a new TradeOffer object to send to a partner. You can provide either a partner's SteamID or their full Trade URL.

    Parameters:

    • partner: The partner's SteamID (string or SteamID object) or their full Trade URL.
    • token: (Optional) The partner's trade token (required if they are not your friend).

    Returns: A TradeOffer instance configured as an outgoing offer (isOurOffer = true).

    // Using a SteamID
    const offer = manager.createOffer('76561198000000000');
    
    // Using a Trade URL
    const offerFromUrl = manager.createOffer('https://steamcommunity.com/tradeoffer/new/?partner=76561198000000000&token=abcdef123456');
  5. Authenticate with setCookies()

    master

    After instantiation, you must authenticate the manager using setCookies(). This method sets the cookies for the SteamCommunity instance and handles API key retrieval or access token fallback.

    Parameters:

    • cookies: An array of cookie objects (e.g., from steam-user).
    • familyViewPin: (Optional) A string PIN to unlock Family View.
    • callback: A callback function (err) => {} called once authentication and initial polling are complete.

    Note: If useAccessToken is enabled, the manager will attempt to extract an access token from the steamLoginSecure cookie to perform API requests if a WebAPI key is not present.

    manager.setCookies(cookies, (err) => {
        if (err) {
            console.error('Login failed:', err);
            return;
        }
        console.log('Logged in and polling started!');
    });
  6. Retrieve specific tags from an EconItem

    master

    You can use the getTag(category) method to find a specific tag associated with an item based on its category.

    • Parameter: category (string) - The category name to search for.
    • Returns: The tag object if found, or null if no tag matches the provided category or if no tags exist.
    const tag = item.getTag('Type');
    if (tag) {
      console.log(`Tag name: ${tag.name}`);
    }
  7. Retrieve Trade Offers

    master

    The manager provides several ways to fetch trade offers:

    Get all offers with getOffers()

    Fetches a list of both sent and received offers based on a filter.

    • filter: An EOfferFilter value (ActiveOnly, HistoricalOnly, or All).
    • historicalCutoff: (Optional) A Date object to filter historical offers.
    • callback: (err, sent, received) => {} where sent and received are arrays of TradeOffer objects.

    Get a specific offer with getOffer()

    Fetches a single offer by its numeric ID.

    • id: The numeric ID of the offer.
    • callback: (err, offer) => {} where offer is a TradeOffer object.

    Find offers containing specific items

    Use getOffersContainingItems(items, includeInactive, callback) to find offers that include specific items in their contents.

    const TradeOfferManager = require('node-steam-tradeoffer-manager');
    
    // Get all active offers
    manager.getOffers(TradeOfferManager.EOfferFilter.ActiveOnly, (err, sent, received) => {
        if (err) return console.error(err);
        console.log('Sent offers:', sent.length);
        console.log('Received offers:', received.length);
    });
  8. Reference: TradeOfferManager Enums

    master

    The TradeOfferManager class exports several enums used for filtering and identifying trade states:

    • SteamID: A utility for parsing and working with SteamIDs.
    • ETradeOfferState: Represents the current state of a trade offer.
    • EOfferFilter: Used in getOffers() to filter results:
      • ActiveOnly
      • HistoricalOnly
      • All
    • EResult: Represents the result of a trade operation.
    • EConfirmationMethod: Represents how a trade is confirmed.
    • ETradeStatus: Represents the status of a trade.
  9. Use the EconItem class to represent Steam items

    master

    The EconItem class is used to wrap and normalize Steam economy item data. When you instantiate an EconItem with an item object, it ensures that key identifiers like id, assetid, appid, classid, and instanceid are correctly typed (e.g., strings or integers) and that arrays like tags, actions, and descriptions are properly initialized.

    Key properties normalized by the constructor:

    • id / assetid: String representation of the item's unique ID.
    • appid: Integer.
    • amount: Integer (defaults to 1).
    • tradable, marketable, commodity: Boolean.
    • tags: An array of tag objects where name and category_name are normalized from localized fields.
    const EconItem = require('steam-tradeoffer-manager').EconItem;
    
    const itemData = {
      assetid: '123456789',
      appid: '753',
      classid: '987654321',
      icon_url: 'abcdef12345'
    };
    
    const item = new EconItem(itemData);
    console.log(item.assetid); // '123456789' (string)