Exemple #1
0
        public async Task GetUserBackpackAssets()
        {
            var apiKey  = "API KEY";
            var json    = "SESSION JSON CONTENT";
            var steamId = 76561198000000000;

            // App Id of the App or Game to retrieve backpack assets
            var appId = AppIds.TeamFortress2;

            var webSession   = JsonConvert.DeserializeObject <WebSession>(json);
            var webAccess    = new SteamWebAccess(webSession);
            var webApi       = new SteamWebAPI(apiKey, webAccess);
            var userBackpack = await Backpack.GetBackpack(webApi, new SteamID(webSessionJson), appId);

            var assets = userBackpack.GetAssets();

            foreach (var asset in assets)
            {
                // Do something with asset

                var assetId  = asset.AssetId;
                var amount   = asset.Amount;
                var defIndex = asset.DefinitionIndex;

                var assetDescription = await userBackpack.GetAssetDescription(asset);

                // Do something with assetDescription

                var assetName       = assetDescription.Name;
                var isAssetTradable = assetDescription.IsTradable;
            }
        }
Exemple #2
0
        public async Task GetUserInventoryAssets()
        {
            var webSessionJson = "SESSION JSON CONTENT";
            var steamId        = 76561198000000000;

            var webSession    = JsonConvert.DeserializeObject <WebSession>(webSessionJson);
            var webAccess     = new SteamWebAccess(webSession);
            var userInventory = await UserInventory.GetInventory(webAccess, new SteamID(webSessionJson));

            // App Id of the App or Game to retrieve assets
            var appId = AppIds.DotA2;

            // Context Id of the App inventory context to retrieve assets
            var contextId = ContextIds.DotA2.Backpack;

            var assets = await userInventory.GetAssets(appId, contextId);

            foreach (var asset in assets)
            {
                // Do something with asset

                var assetId = asset.AssetId;
                var amount  = asset.Amount;

                var assetDescription = await userInventory.GetAssetDescription(asset);

                // Do something with assetDescription

                var assetName       = assetDescription.Name;
                var isAssetTradable = assetDescription.IsTradable;
            }
        }
Exemple #3
0
        public async Task CreateANewTradeOffer()
        {
            var apiKey         = "API KEY";
            var json           = "SESSION JSON CONTENT";
            var partnerSteamId = 76561198000000000;

            var webSession        = JsonConvert.DeserializeObject <WebSession>(json);
            var webAccess         = new SteamWebAccess(webSession);
            var webApi            = new SteamWebAPI(apiKey, webAccess);
            var tradeOfferManager = new TradeOfferManager(webApi, webAccess, TradeOfferOptions.Default);

            if (!await tradeOfferManager.ValidateAccess(new SteamID(partnerSteamId)))
            {
                // Can't propose a trade offer to this user
                // Maybe inventory is private
                return;
            }

            // Get partner inventory
            var partnerInventory = await tradeOfferManager.GetPartnerInventory(new SteamID(partnerSteamId));

            // Get all partner dota2 assets
            var partnerDota2Assets = await partnerInventory.GetAssets(AppIds.DotA2);

            // We don't want to give any asset xD
            var ourAssets = new Asset[0];

            var newTradeOfferItemsList = new NewTradeOfferItemsList(ourAssets, partnerDota2Assets.Cast <Asset>().ToArray());
            var tradeOfferMessage      = "Give me your Dota2 items";
            var sentTradeOfferId       = await tradeOfferManager.Send(new SteamID(partnerSteamId), newTradeOfferItemsList, tradeOfferMessage);

            // We can also get the trade offer
            var sentTradeOffer = await tradeOfferManager.GetTradeOffer(sentTradeOfferId);
        }
Exemple #4
0
 public static async Task <UserInventory> GetInventory(SteamWebAccess steamWebAccess, SteamID steamId)
 {
     return(new UserInventory(
                steamWebAccess,
                steamId,
                await GetInventoryOverview(steamWebAccess, steamId).ConfigureAwait(false),
                GetUserInventory));
 }
Exemple #5
0
 public TradeOfferManager(
     SteamWebAPI steamWebAPI,
     SteamWebAccess steamWebAccess,
     TradeOfferOptions tradeOfferOptions)
 {
     SteamWebAccess     = steamWebAccess ?? throw new ArgumentNullException(nameof(steamWebAccess));
     SteamWebAPI        = steamWebAPI ?? throw new ArgumentNullException(nameof(steamWebAPI));
     _tradeOfferOptions = tradeOfferOptions ?? TradeOfferOptions.Default;
 }
Exemple #6
0
        private static async Task <UserInventoryApp[]> GetInventoryOverview(
            SteamWebAccess steamWebAccess,
            SteamID steamId)
        {
            var   regex   = new Regex("var g_rgAppContextData = (.*?);");
            Match matched = null;

            for (var i = 0; i < 3; i++)
            {
                try
                {
                    var inventoryPageResponse = await steamWebAccess.FetchString(
                        new SteamWebAccessRequest(
                            string.Format(UserInventoryUrl, steamId.ConvertToUInt64()),
                            SteamWebAccessRequestMethod.Get,
                            null
                            )
                        ).ConfigureAwait(false);

                    if (!string.IsNullOrWhiteSpace(inventoryPageResponse))
                    {
                        matched = regex.Match(inventoryPageResponse);

                        if (matched.Success)
                        {
                            break;
                        }
                    }
                }
                catch (WebException)
                {
                    continue;
                }

                await Task.Delay(TimeSpan.FromSeconds(0.3)).ConfigureAwait(false);
            }

            if (matched?.Success != true ||
                matched.Groups.Count <= 1 ||
                !matched.Groups[1].Success ||
                string.IsNullOrWhiteSpace(matched.Groups[1].Value))
            {
                throw new UserInventoryFetchOverviewException(steamId);
            }

            try
            {
                var overviewResult =
                    JsonConvert.DeserializeObject <Dictionary <long, InventoryApp> >(matched.Groups[1].Value);

                return(overviewResult?.Values.Select(app => app.ToUserInventoryApp()).ToArray());
            }
            catch (Exception e)
            {
                throw new UserInventoryFetchOverviewException(steamId, e);
            }
        }
Exemple #7
0
        internal Trade(
            SteamID other,
            SteamWebAccess steamWebAccess,
            TradeOptions tradeOptions = null)
        {
            PartnerSteamId = other;

            _steamWebAccess = steamWebAccess ?? throw new ArgumentNullException(nameof(steamWebAccess));
            _tradeOptions = tradeOptions ?? TradeOptions.Default;
        }
Exemple #8
0
        protected override async Task <bool> GetGuestSession()
        {
            // Get a new SessionId
            SteamWebAccess = SteamMobileWebAccess.GetGuest();
            (await OperationRetryHelper.Default
             .RetryOperationAsync(() => SteamWebAccess.FetchBinary(new SteamWebAccessRequest(LoginInitializeUrl)))
             .ConfigureAwait(false)).Dispose();

            return(!string.IsNullOrWhiteSpace(SteamWebAccess?.Session?.SessionId));
        }
Exemple #9
0
 // ReSharper disable once TooManyDependencies
 internal UserInventory(
     SteamWebAccess steamWebAccess,
     SteamID steamId,
     UserInventoryApp[] inventoryApps,
     InventoryRetrieveDelegate getInventoryDelegate)
 {
     _steamWebAccess       = steamWebAccess;
     SteamId               = steamId;
     _getInventoryDelegate = getInventoryDelegate;
     _inventoryApps        = new List <UserInventoryApp>(inventoryApps ?? new UserInventoryApp[0]);
 }
Exemple #10
0
        public async Task ManageTradeOffers()
        {
            var apiKey = "API KEY";
            var json   = "SESSION JSON CONTENT";

            var webSession        = JsonConvert.DeserializeObject <WebSession>(json);
            var webAccess         = new SteamWebAccess(webSession);
            var webApi            = new SteamWebAPI(apiKey, webAccess);
            var tradeOfferManager = new TradeOfferManager(webApi, webAccess, TradeOfferOptions.Default);

            tradeOfferManager.TradeOfferReceived += (sender, args) =>
            {
                // Received new trade offer
                // Accept it right away if it is a gift
                if (!args.TradeOffer.IsOurOffer && args.TradeOffer.OurAssets.Length == 0)
                {
                    await tradeOfferManager.Accept(args.TradeOffer);
                }
            };

            tradeOfferManager.TradeOfferInEscrow += (sender, args) =>
            {
                // A trade offer is in escrow
                // If escrow is longer than 10 days, decline or cancel

                var escrowDuration = await tradeOfferManager.GetEscrowDuration(args.TradeOffer);

                if (escrowDuration.MyEscrowDuration > TimeSpan.FromDays(10))
                {
                    if (args.TradeOffer.IsOurOffer)
                    {
                        await tradeOfferManager.Cancel(args.TradeOffer);
                    }
                    else
                    {
                        await tradeOfferManager.Decline(args.TradeOffer);
                    }
                }
            };

            tradeOfferManager.StartPolling();

            // Wait for the end of program

            tradeOfferManager.Dispose();
        }
Exemple #11
0
        public static async Task <UserInventory> GetInventoryAlternate(SteamWebAccess steamWebAccess, SteamID steamId)
        {
            UserInventoryApp[] overview = null;

            try
            {
                overview = await GetInventoryOverview(steamWebAccess, steamId).ConfigureAwait(false);
            }
            catch (Exception)
            {
                // ignored
            }

            return(new UserInventory(
                       steamWebAccess,
                       steamId,
                       overview,
                       GetUserInventoryAlternate));
        }
Exemple #12
0
        public async Task GetUserInventoryApps()
        {
            var webSessionJson = "SESSION JSON CONTENT";
            var steamId        = 76561198000000000;

            var webSession    = JsonConvert.DeserializeObject <WebSession>(webSessionJson);
            var webAccess     = new SteamWebAccess(webSession);
            var userInventory = await UserInventory.GetInventory(webAccess, new SteamID(webSessionJson));

            foreach (var inventoryApp in userInventory.InventoryApps)
            {
                var appId   = inventoryApp.AppId;
                var appName = inventoryApp.Name;
                // Do something with appId and appName

                foreach (var appContext in inventoryApp.Contexts)
                {
                    var contextId   = appContext.ContextId;
                    var contextName = appContext.ContextName;

                    // Do something with appId, contextId and contextName
                }
            }
        }
Exemple #13
0
 public TradeManager(SteamWebAPI steamWebAPI, SteamWebAccess steamWebAccess, TradeOptions options = null)
 {
     _steamWebAPI    = steamWebAPI ?? throw new ArgumentNullException(nameof(steamWebAPI));
     _steamWebAccess = steamWebAccess ?? throw new ArgumentNullException(nameof(steamWebAccess));
     TradeOptions    = options;
 }
Exemple #14
0
        // ReSharper disable once ExcessiveIndentation
        // ReSharper disable once TooManyArguments
        private static async Task <UserAppInventory> GetUserInventoryAlternate(
            SteamWebAccess steamWebAccess,
            SteamID steamId,
            long appId,
            long contextId)
        {
            var startPosition     = 0;
            var assets            = new List <UserInventoryAsset>();
            var assetDescriptions = new List <UserInventoryAssetDescription>();
            var appInfos          = new List <UserInventoryApp>();

            do
            {
                var retrySuccess = false;

                for (var retry = 0; retry < 3; retry++)
                {
                    try
                    {
                        var response = await steamWebAccess.FetchObject <InventoryResponseV1>(
                            new SteamWebAccessRequest(
                                string.Format(UserInventoryV1Url, steamId.ConvertToUInt64(), appId,
                                              contextId),
                                SteamWebAccessRequestMethod.Get,
                                startPosition > 0
                                    ? QueryStringBuilder.FromDynamic(new
                        {
                            start = startPosition
                        })
                                    : null
                                )
                        {
                            Referer = TradeOfferManager.TradeOfferNewUrl
                        }
                            ).ConfigureAwait(false);

                        if (response?.Success == true)
                        {
                            retrySuccess = true;

                            foreach (var inventoryAsset in response.Assets)
                            {
                                var steamInventoryAsset = inventoryAsset.Value.ToSteamInventoryAsset(appId, contextId);

                                if (!assets.Contains(steamInventoryAsset))
                                {
                                    assets.Add(steamInventoryAsset);
                                }
                            }

                            foreach (var itemDescription in response.Descriptions)
                            {
                                var steamAssetDescription = itemDescription.Value.ToSteamAssetDescription();

                                if (!assetDescriptions.Contains(steamAssetDescription))
                                {
                                    assetDescriptions.Add(steamAssetDescription);
                                }
                            }

                            foreach (var app in response.Apps ?? new InventoryAppInfoV1[0])
                            {
                                appInfos.Add(app.ToSteamInventoryAsset());
                            }

                            if (!response.More)
                            {
                                return(new UserAppInventory(assets.ToArray(), assetDescriptions.ToArray(),
                                                            appInfos.ToArray()));
                            }

                            startPosition = response.MoreStart;

                            break;
                        }
                    }
                    catch (WebException)
                    {
                        // ignored
                    }
                }

                if (!retrySuccess)
                {
                    throw new UserInventoryFetchAssetsException(appId, contextId, steamId);
                }

                await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false);
            } while (true);
        }
Exemple #15
0
        // ReSharper disable once TooManyArguments
        // ReSharper disable once MethodTooLong
        // ReSharper disable once ExcessiveIndentation
        private static async Task <UserAppInventory> GetUserInventory(
            SteamWebAccess steamWebAccess,
            SteamID userSteamId,
            long appId,
            long contextId)
        {
            var startAssetId      = 0L;
            var assets            = new List <UserInventoryAsset>();
            var assetDescriptions = new List <UserInventoryAssetDescription>();

            do
            {
                var       retrySuccess  = false;
                Exception lastException = null;
                for (var retry = 0; retry < 3; retry++)
                {
                    try
                    {
                        var response = await steamWebAccess.FetchObject <InventoryResponseV2>(
                            new SteamWebAccessRequest(
                                string.Format(UserInventoryV2Url, userSteamId.ConvertToUInt64(),
                                              appId,
                                              contextId),
                                SteamWebAccessRequestMethod.Get,
                                startAssetId > 0
                                    ? QueryStringBuilder.FromDynamic(new
                        {
                            l = "english",
                            count = 2000,
                            start_assetid = startAssetId
                        })
                                    : QueryStringBuilder.FromDynamic(new
                        {
                            l = "english",
                            count = 2000
                        })
                                )
                        {
                            Referer = string.Format(UserInventoryUrl,
                                                    userSteamId.ConvertToUInt64())
                        }
                            ).ConfigureAwait(false);

                        if (response?.Success == true)
                        {
                            retrySuccess = true;

                            foreach (var inventoryAsset in response.Assets)
                            {
                                var steamInventoryAsset = inventoryAsset.ToSteamInventoryAsset();

                                if (!assets.Contains(steamInventoryAsset))
                                {
                                    assets.Add(steamInventoryAsset);
                                }
                            }

                            foreach (var itemDescription in response.Descriptions)
                            {
                                var steamAssetDescription = itemDescription.ToSteamAssetDescription();

                                if (!assetDescriptions.Contains(steamAssetDescription))
                                {
                                    assetDescriptions.Add(steamAssetDescription);
                                }
                            }

                            if (!response.MoreItems || response.LastAssetId == null)
                            {
                                return(new UserAppInventory(assets.ToArray(), assetDescriptions.ToArray(), null));
                            }

                            startAssetId = response.LastAssetId.Value;

                            break;
                        }
                    }
                    catch (WebException e)
                    {
                        lastException = e;
                    }
                }

                if (!retrySuccess)
                {
                    throw new UserInventoryFetchAssetsException(appId, contextId, userSteamId, lastException);
                }

                await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false);
            } while (true);
        }
Exemple #16
0
        public async Task Trade()
        {
            var apiKey         = "API KEY";
            var json           = "SESSION JSON CONTENT";
            var partnerSteamId = 76561198000000000;

            var webSession   = JsonConvert.DeserializeObject <WebSession>(json);
            var webAccess    = new SteamWebAccess(webSession);
            var webApi       = new SteamWebAPI(apiKey, webAccess);
            var tradeManager = new TradeManager(webApi, webAccess, TradeOptions.Default);

            var trade = await tradeManager.CreateTrade(new SteamID(partnerSteamId));

            var tradePartnerInventory = await trade.GetPartnerInventory();

            trade.PartnerMessaged += (sender, args) =>
            {
                var partnerMessage = args.Message;

                if (partnerMessage == "hello" || args.Message == "hey")
                {
                    trade.SendMessage("Hello to you too.");
                }
            };

            trade.PartnerOfferedItemsChanged += (sender, args) =>
            {
                if (args.Action == PartnerOfferedItemsChangedAction.Added)
                {
                    var userAssets = await tradePartnerInventory.GetAssets(args.Asset.AppId, args.Asset.ContextId);

                    foreach (var userAsset in userAssets)
                    {
                        if (userAsset.Equals(args.Asset))
                        {
                            // This is our asset

                            var assetDescription = await tradePartnerInventory.GetAssetDescription(userAsset);

                            // Do something with assetDescription

                            break;
                        }
                    }
                }
            };

            trade.PartnerReadyStateChanged += (sender, args) =>
            {
                // If this is a gift, set ready and accept
                if (trade.MyOfferedItems.Length == 0)
                {
                    await trade.SetReadyState(true);

                    await trade.AcceptTrade();
                }
            };

            // Wait for trade to end

            trade.Dispose();
        }