TradeOfferManager

Alex Corn edited this page Mar 7, 2018 · 58 revisions

TradeOfferManager is the root object that node-steam-tradeoffer-manager exports. You'll need to instantiate it.

Table of Contents

Example

// Steam integration is optional and is only used for instant polling
// === FOR node-steam 0.6.x ===
var Steam = require('steam');
var client = new Steam.SteamClient();
// === END FOR node-steam 0.6.x ===

// === FOR node-steam 1.0.x AND Steam.SteamUser ===
var Steam = require('steam');
var connection = new Steam.SteamClient();
var client = new Steam.SteamUser(connection);
// === END FOR node-steam 1.0.x AND Steam.SteamUser ===

// === FOR node-steam-user ===
var SteamUser = require('steam-user');
var client = new SteamUser();
// === END FOR node-steam-user ===

var TradeOfferManager = require('steam-tradeoffer-manager');
var manager = new TradeOfferManager({
    "steam": client,
    "domain": "example.com", // Fill this in with your own domain
    "language": "en"
});

ETradeOfferState

Every trade offer has a state which is a value from ETradeOfferState. As of v2.0.0, you can use TradeOfferManager.ETradeOfferState[state] to get the English name for a state.

EResult

Some errors include an eresult property on their Error object. As of v1.1.0, you can compare this to TradeOfferManager.EResult (that's a static property available from the root export of the module, not from an instantiated manager). As of v2.0.0, you can also use TradeOfferManager.EResult[result] to get the English name for an EResult.

Constructor([options])

  • options - Optional. An object containing any or all of the following options

Options

steam

Optional. See Steam Integration below.

community

Optional. A node-steamcommunity instance of v3.19.1 or later to use. If not provided, one will be created internally automatically.

domain

Optional. Your domain name, if you have one. Used to register a Steam Web API key. Defaults to localhost.

language

Optional. Specify a language code if you want item descriptions. Must be a 2-character language code like en or es.

pollInterval

Optional. The time, in milliseconds, between polls. If -1, timed polling is disabled.

Minimum 1000, default 30000 (30 seconds).

cancelTime

Optional. The time, in milliseconds, that a sent offer can remain Active until it's automatically canceled by the manager. This feature is disabled if omitted.

Note that this check is performed on polling, so it will only work as expected if timed polling is enabled. Also note that because polling is on a timer, offers will be canceled between cancelTime and cancelTime + pollInterval milliseconds after being created, assuming Steam is up.

pendingCancelTime

Optional. The time, in milliseconds, that a sent offer can remain CreatedNeedsConfirmation until it's automatically canceled by the manager. This feature is disabled if omitted. All documentation for cancelTime applies.

cancelOfferCount

Optional. Once we have this many outgoing Active offers, the oldest will be automatically canceled.

cancelOfferCountMinAge

Optional. If you're using cancelOfferCount, then offers must be at least this many milliseconds old in order to qualify for automatic cancellation.

globalAssetCache

Optional. If this is true and you specified a language, then descriptions which are obtained from the WebAPI are stored in the global object instead of in a property of TradeOfferManager. As a result, all TradeOfferManager objects running within the application will share the same description cache (can reduce memory usage).

Default false.

pollData

Optional. If passed, this will be assigned to pollData

dataDirectory

Optional. Controls where the asset cache and poll data (if savePollData is enabled) are saved.

Defaults to a platform-specific directory in the same form as node-steam-user. You can set this to null to disable all data persistence to disk.

gzipData

Optional. Set this to true if you want data that's persisted to dataDirectory to first be gzipped (default off, and probably doesn't need to be on as the files are typically very small and gzip won't do much)

savePollData

Optional. Set this to true if you want the module's poll data to be saved to disk automatically (requires dataDirectory to not be null) and retrieved on startup.

Steam Integration

node-steam-tradeoffer-manager can integrate with a Steam client instance. To do this, pass a supported Steam client to the constructor as the steam property. There are a few options here.

If provided, node-steam-tradeoffer-manager will be able to get trade offer feedback more quickly. The manager will automatically do a trade offer poll when it receives a notification from Steam of active incoming trade offers.

If using node-steam-user, the manager will also poll when Steam sends a notification of new items (for receivedOfferChanged or sentOfferChanged to be emitted more quickly when an offer is accepted).

Properties

pollInterval

v1.6.0 or later is required to use this property.

The interval, in milliseconds, at which the manager will poll Steam for trade offer info. You can change this at any time, although the change will only take effect after the next poll. This value is initially set in the constructor.

Set to -1 to disable timed polling. Minimum is 1000 ms.

cancelTime

v1.6.0 or later is required to use this property.

The time, in milliseconds, after which the manager will automatically cancel outgoing offers if they're not acted on. You can change this at any time. This value is initially set in the constructor.

Set to null to disable.

pendingCancelTime

v1.14.0 or later is required to use this property.

The time, in milliseconds, after which the manager will automatically cancel outgoing CreatedNeedsConfirmation offers if they're not acted on. You can change this at any time. This value is initially set in the constructor.

Set to null to disable.

cancelOfferCount

v1.16.0 or later is required to use this property.

Once we have this many outgoing Active offers, the oldest will be automatically canceled. You can change this at any time. This value is initially set in the constructor.

Set to null to disable.

cancelOfferCountMinAge

v1.16.0 or later is required to use this property.

If you're using cancelOfferCount, then offers must be at least this many milliseconds old in order to qualify for automatic cancellation. This value is initially set in the constructor.

Set to 0 to disable.

pollData

Set this to the most recent object received in the pollData event on startup or in the constructor to gracefully resume polling.

apiKey

A read-only property containing your account's API key once the callback of setCookies fires for the first time.

steamID

v1.6.0 or later is required to use this property.

A SteamID object containing the SteamID of the account we're logged in as. null until the first call to setCookies.

storage

v2.9.0 or later is required to use this property.

Assuming the dataDirectory constructor option wasn't null, you can access the file storage engine this way.

If you don't want to (or can't) save data to the disk, you can implement your own storage engine. To do this, simply add the following code:

manager.storage.on('save', function(filename, contents, callback) {
	// filename is the name of the file, as a string
	// contents is a Buffer containing the file's contents
	// callback is a function which you MUST call on completion or error, with a single error argument

	// For example:
	someStorageSystem.saveFile(filename, contents, function(err) {
		callback(err);
	});
});

manager.storage.on('read', function(filename, callback) {
	// filename is the name of the file, as a string
	// callback is a function which you MUST call on completion or error, with an error argument and a Buffer argument

	// For example:
	someStorageSystem.readFile(filename, function(err, file) {
		if(err) {
			callback(err);
			return;
		}

		callback(null, file);
	});
});

In this manner, you can save data to a database, a cloud service, or anything else you choose.

Methods

setCookies(cookies[, familyViewPin][, callback])

  • cookies - An array of cookies in name=value form. This is the format used by node-steam, node-steam-user, and node-steamcommunity, so any of those modules can be used to get cookies.
  • familyViewPin - Optional. If your account has Family View enabled, you need to supply your PIN here. Once you've set cookies initially, you can use parentalUnlock if you need to re-authenticate for any reason.
  • callback - Optional. Will be called once the API key is retrieved and the module is ready for use. The first argument will be null on success or an Error object on failure. You'll get an Access Denied error if your account is limited.

v2.1.0 or later is required to use familyViewPin.

Sets node-steam-tradeoffer-manager's internal cookie buffer and retrieves your API key, registering one if needed. Therefore, usage of this module constitutes agreement to the Steam Web API terms.

Read more about how cookies work and interact with other modules.

shutdown()

v1.7.0 or later is required to use this method.

Stops polling, removes the Steam client reference, and clears cookies. Suitable for use if you want to log out of your bot's account but not terminate the process.

parentalUnlock(pin[, callback])

  • pin - Your 4-digit PIN code
  • callback - Optional. Called on completion with a single argument which is null on success or an Error object on failure. Error is Incorrect PIN if your PIN was wrong.

If your account has Family View enabled, you'll need to call this right after each setCookies call to unlock the session for trading. You don't need to wait for the setCookies callback to call this.

You need to supply your PIN directly to setCookies the first time you call it. On subsequent calls, you have a choice of providing it to either setCookies or calling parentalUnlock.

createOffer(partner[, token])

  • partner - A trade URL, a SteamID object, or a string which can parse into a SteamID (STEAM_0:0:23071901, [U:1:46143802], 76561198006409530).
  • token - Your trade partner's access token, if needed

Creates a new empty TradeOffer and returns it to you. You can pass either a SteamID (as an object or a string) or a trade URL to partner. If you pass a trade URL, then your trade partner's SteamID (and access token, if present) will be extracted from the URL.

Examples:

var offer = manager.createOffer("[U:1:46143802]"); // no trade token provided, must be friends or must use offer.setToken() before sending
var offer = manager.createOffer(new TradeOfferManager.SteamID("76561198006409530"), "KYworVTM"); // trade token provided
var offer = manager.createOffer("https://steamcommunity.com/tradeoffer/new/?partner=46143802"); // SteamID provided but no trade token
var offer = manager.createOffer("https://steamcommunity.com/tradeoffer/new/?partner=46143802&token=KYworVTM"); // SteamID and trade token both provided

Important: If you use a trade URL, make sure you verify the user's SteamID if the URL was user-provided. Users can give you trade URLs that don't belong to them, causing you to send unsolicited trade offers to random users!

getOffer(id, callback)

  • id - The ID of the trade offer, as a string or number
  • callback - You'll receive the TradeOffer object in this callback.
    • err - null on success, or an Error object on failure
    • offer - A TradeOffer object for the requested offer

Gets a TradeOffer object for a specific offer ID. As of v1.1.0, on failure, the err object may contain an eresult property.

getOffers(filter,[historicalCutoff,] callback)

  • filter - Required. A value from EOfferFilter
  • historicalCutoff - Optional. If filter is ActiveOnly and this is a Date object in the past, then offers which are either active or have a modification date after this date will be returned. Omit or pass null if filter is not ActiveOnly or if you only wish to get offers in Active state.
  • callback - Required.
    • err - null on success, or an Error object on failure
    • sent - An array of TradeOffer objects for offers sent by you matching the filter.
    • received - An array of TradeOffer objects for offers received by you matching the filter.

Retrieves a list of trade offers matching specific criteria. As of v1.1.0, on failure, the err object may contain an eresult property.

getInventoryContents(appid, contextid, tradableOnly, callback)

  • appid - The Steam App ID of the game for which you want to load your own inventory
  • contextid - The ID of the context within the app that you're loading the inventory for
  • tradableOnly - true to only include tradable items, false to include all
  • callback - Invoked when data is ready
    • err - null on success, or an Error object on failure
    • inventory - An array of the user's inventory items, as EconItem objects
    • currencies - An array of the user's currency items, as EconItem objects

v2.5.0 or later is required to use this method

Gets the contents of your own inventory. This method uses the newer /inventory/SteamID endpoint, which is less rate-limited than the older, deprecated /profiles/SteamID/inventory/json endpoint. However, the output data is slightly different. The only known difference right now is that app_data is not available. You will need to use other means to obtain that data if you need it. Don't rely on the older endpoint and the deprecated loadInventory method as it will likely be removed in the future.

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

  • steamID - Either a SteamID object or a string which can parse into one
  • appid - The Steam App ID of the game for which you want to load the user's inventory
  • contextid - The ID of the context within the app that you're loading the inventory for
  • tradableOnly - true to only include tradable items, false to include all
  • callback - Invoked when data is ready
    • err - null on success, or an Error object on failure
    • inventory - An array of the user's inventory items, as EconItem objects
    • currencies - An array of the user's currency items, as EconItem objects

v2.5.0 or later is required to use this method

Same as getInventoryContents, but can retrieve another user's inventory.

loadInventory(appid, contextid, tradableOnly, callback)

  • appid - The Steam App ID of the game for which you want to load your inventory
  • contextid - The ID of the context within the app that you're loading the inventory for
  • tradableOnly - true to only include tradable items, false to include all
  • callback - Invoked when data is ready
    • err - null on success, or an Error object on failure
    • inventory - An array of the user's inventory items, as EconItem objects
    • currencies - An array of the user's currency items, as EconItem objects

THIS METHOD IS DEPRECATED AS OF v2.5.0; USE getInventoryContents INSTEAD.

Retrieves the contents of your own inventory for a specific game and context.

loadUserInventory(steamID, appid, contextid, tradableOnly, callback)

  • steamID - Either a SteamID object or a string which can parse into one
  • appid - The Steam App ID of the game for which you want to load the user's inventory
  • contextid - The ID of the context within the app that you're loading the inventory for
  • tradableOnly - true to only include tradable items, false to include all
  • callback - Invoked when data is ready
    • err - null on success, or an Error object on failure
    • inventory - An array of the user's inventory items, as EconItem objects
    • currencies - An array of the user's currency items, as EconItem objects

v1.18.0 or later is required to use this method. THIS METHOD IS DEPRECATED AS OF v2.5.0; USE getUserInventoryContents INSTEAD.

Retrieves the contents of some other user's inventory for a specific game and context.

getOfferToken(callback)

  • callback - Called when requested data is available.
    • err - An Error object on failure, null on success
    • token - Your account's trade offer token, as a string

Retrieves the token part of your account's trade URL.

getOffersContainingItems(items, [includeInactive, ]callback)

  • items - Either a single item object (with appid, contextid, and assetid/id properties) or an array of item objects
  • includeInactive - Optional. If true, then offers which aren't Active or InEscrow will be checked. Default false.
  • callback - Required. Called when the requested data is ready.
    • err - An Error object on failure, or null on success
    • sent - An array of TradeOffer objects for offers you sent which contain the item(s)
    • received - An array of TradeOffer objects for offers you received which contain the item(s)

v1.22.0 or later is required to use this method

Finds offers which contain the given item(s). Any offer which contains at least one item you passed in will be returned. Might be useful to avoid sending duplicate offers, or to cancel previous ones.

doPoll()

Immediately performs a poll. Can be used even if timed polling is disabled to poll on your own schedule. Don't worry about spamming this method, node-steam-tradeoffer-manager will automatically limit polls to at most one per second.

Events

newOffer

  • offer - A TradeOffer object for the newly-received offer

Emitted when polling detects a new trade offer sent to us. Only emitted if polling is enabled.

sentOfferChanged

Emitted when an offer we sent changes state. This might mean that it was accepted/declined by the other party, that we cancelled it, or that we confirmed a pending offer via email. Only emitted if polling is enabled.

sentOfferCanceled

  • offer - A TradeOffer object for the canceled offer
  • reason - A string containing the reason why it was canceled
    • cancelTime - The cancelTime timeout was reached
    • cancelOfferCount - The cancelOfferCount limit was reached

v1.0.0 or later is required to use this event. v1.16.0 or later is required to use the reason argument.

Emitted when the manager automatically cancels an offer due to either your cancelTime constructor option or your cancelOfferCount constructor option. sentOfferChanged will also be emitted on next poll.

sentPendingOfferCanceled

  • offer - A TradeOffer object for the canceled offer

v1.14.0 or later is required to use this event

Emitted when the manager automatically cancels an offer due to your pendingCancelTime constructor option. sentOfferChanged will also be emitted on next poll.

unknownOfferSent

  • offer - A TradeOffer object for the offer that was sent

v1.10.0 or later is required to use this event

Emitted when the manager finds a trade offer that was sent by us, but that wasn't sent via node-steam-tradeoffer-manager (i.e. it's not in the poll data, so this will emit for all sent offers on every startup if you don't restore poll data).

You could use this to cancel offers that error when you call send() but actually go through later, because of how awful Steam is.

receivedOfferChanged

Emitted when an offer we received changes state. This might mean that it was cancelled by the other party, or that we accepted/declined it. Only emitted if polling is enabled.

realTimeTradeConfirmationRequired

  • offer - A TradeOffer object for the offer that needs to be confirmed

v2.3.0 or later is required to use this event

Emitted when polling reveals that we have a new trade offer that was created from a real-time trade session that requires confirmation. See real-time trades for more information.

realTimeTradeCompleted

  • offer - A TradeOffer object for the offer that has completed

v2.3.0 or later is required to use this event

Emitted when polling reveals that a trade offer that was created from a real-time trade is now Accepted, meaning that the trade has completed. See real-time trades for more information.

pollFailure

  • err - An Error object

v0.1.7 or later is required to use this event

Emitted when there's a problem polling the API. You can use this to alert users that Steam is currently down or acting up, if you wish.

pollSuccess

v1.8.5 or later is required to use this event

Emitted when a poll succeeds.

pollData

  • pollData - The new poll data

Emitted when new poll data is available. See the Polling page for more information.

offerList

  • filter - The EOfferFilter value that was used to get this list
  • sent - An array of TradeOffer objects for offers we sent
  • received - An array of TradeOffer objects for offers we received

v2.0.0 or later is required to use this event

Emitted whenever a getOffers call succeeds, regardless of the source of the call. Note that if filter is EOfferFilter.ActiveOnly then there may have been a historical cutoff provided so there may also be some historical offers present in the output.