/// <summary> /// Initializes a new instance of the <see cref="TradeSession"/> class. /// </summary> /// <param name="otherSid">The Steam id of the other trading partner.</param> /// <param name="steamWeb">The SteamWeb instance for this bot</param> public TradeSession(SteamID otherSid, SteamWeb steamWeb) { OtherSID = otherSid; SteamWeb = steamWeb; Init(); }
internal string Request(string url, NameValueCollection data, string referer) { string resp; try { resp = SteamWeb.RequestWithException( url, "POST", data, this._cookies, referer: referer, proxy: this._proxy); } catch (Exception e) { throw new SteamException($"Steam error: {e.Message}", e); } try { var offerResponse = JsonConvert.DeserializeObject <NewTradeOfferResponse>(resp); if (!string.IsNullOrEmpty(offerResponse.TradeOfferId)) { return(offerResponse.TradeOfferId); } throw new SteamException(offerResponse.TradeError); } catch (JsonException ex) { Logger.Log.Debug(resp); throw new SteamException($"Unknown steam response - {ex.Message}"); } }
public OffersResponse GetTradeOffers(bool getSentOffers, bool getReceivedOffers, bool getDescriptions, bool activeOnly, bool historicalOnly, string timeHistoricalCutoff = "1389106496", string language = "en_us") { if (!getSentOffers && !getReceivedOffers) { throw new ArgumentException("getSentOffers and getReceivedOffers can't be both false"); } var options = string.Format( "?key={0}&get_sent_offers={1}&get_received_offers={2}&get_descriptions={3}&language={4}&active_only={5}&historical_only={6}", _apiKey, BoolConverter(getSentOffers), BoolConverter(getReceivedOffers), BoolConverter(getDescriptions), language, BoolConverter(activeOnly), BoolConverter(historicalOnly)); if (timeHistoricalCutoff != "1389106496") { options += $"&time_historical_cutoff={timeHistoricalCutoff}"; } var url = string.Format(BaseUrl, "GetTradeOffers", "v1", options); var response = SteamWeb.Request(url, "GET", data: null); try { var result = JsonConvert.DeserializeObject <ApiResponse <OffersResponse> >(response); return(result.Response); } catch (Exception ex) { Logger.Error("Error on get rdade offers", ex); } return(new OffersResponse()); }
public static void BreakOnGems(string sessionId, string appId, string assetId, string contextId, int expectedGemsValue, ulong steamId, CookieContainer cookies, WebProxy proxy) { var response = SteamWeb.Request( $"https://steamcommunity.com/profiles/{steamId}/ajaxgrindintogoo/", "POST", new NameValueCollection { { "sessionid", sessionId }, { "appid", appId }, { "assetid", assetId }, { "contextid", contextId }, { "goo_value_expected", expectedGemsValue.ToString() }, }, cookies, referer: $"https://steamcommunity.com/profiles/{steamId}/inventory/", proxy: proxy); if (response == null) { throw new WebException("Steam response is empty"); } var json = JsonConvert.DeserializeObject <BreakGemsResponse>(response); if (json.Success != 1) { throw new WebException($"Response success is {json.Success}"); } }
//TODO: rewrite without passing apiKey to constructor. Constructor should get API_Key somehow by itself. public ItemInSQL(string itemUrl, SteamWeb steamWeb, int canBuy = 1,int canSell = 1, int maxToBuy = 100, int minPriceBuy = 0, int maxPriceBuy = 0, int minPriceSell = 0, int maxPriceSell = 0) { this.Context = ParseContext(itemUrl); this.ClassInstance = ParseClassInstance(itemUrl); this.ItemUrl = itemUrl; this.ItemUrlSteam = ""; //getting hash and name for item. string itemInfo = CsgotmAPI.GetItemInfo(ClassInstance,"en", steamWeb); dynamic jsonItemInfo = JsonConvert.DeserializeObject(itemInfo); this.Hash = jsonItemInfo.hash.ToString(); this.ItemName = jsonItemInfo.market_name.ToString(); this.CanBuy = canBuy; this.CanSell = canSell; this.MaxToBuy = maxToBuy; this.Bought = 0; this.MinPriceBuy = minPriceBuy; this.MaxPriceBuy = maxPriceBuy; this.MinPriceSell = minPriceSell; this.MaxPriceSell = maxPriceSell; }
public TradeHistoryResponse GetTradeHistory(int?maxTrades, long?startAfterTime, string startAfterTradeId, bool navigatingBack = false, bool getDescriptions = false, string lanugage = "en", bool includeFailed = false) { if (!string.IsNullOrEmpty(startAfterTradeId)) { startAfterTime = null; } var options = GetOptions( ("key", _apiKey), ("max_trades", maxTrades), ("start_after_tradeid", startAfterTradeId), ("get_descriptions", BoolConverter(getDescriptions)), ("language", lanugage), ("include_failed", BoolConverter(includeFailed)), ("start_after_time", startAfterTime), ("navigating_back", BoolConverter(navigatingBack)) ); var url = string.Format(BaseUrl, "GetTradeHistory", "v1", options); var response = SteamWeb.Request(url, "GET", data: null); try { var result = JsonConvert.DeserializeObject <ApiResponse <TradeHistoryResponse> >(response); return(result.Response); } catch (Exception ex) { Logger.Error("Error on get trade history", ex); } return(new TradeHistoryResponse()); }
internal bool Request(string url, NameValueCollection data, string referer, string tradeOfferId, out string newTradeOfferId) { newTradeOfferId = ""; var resp = SteamWeb.Request(url, "POST", data, _cookies, referer: referer); if (!string.IsNullOrEmpty(resp)) { try { var offerResponse = JsonConvert.DeserializeObject <NewTradeOfferResponse>(resp); if (!string.IsNullOrEmpty(offerResponse.TradeOfferId)) { newTradeOfferId = offerResponse.TradeOfferId; return(true); } Error = offerResponse.TradeError; Logger.Error($"Error on decline trade offer - {Error}"); } catch (JsonException ex) { Logger.Error("Error on decline trade offer", ex); } } return(false); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static TF2Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch (url, "GET", null, false); InventoryResponse result = JsonConvert.DeserializeObject<InventoryResponse>(response); return new TF2Inventory(result.result) as TF2Inventory; }
public MyInventoryRootModel LoadMyInventoryPage( SteamID steamid, int appid, int contextid, CookieContainer cookies = null, string startAssetid = "", int count = 5000) { Logger.Log.Debug($"Loading {steamid.ConvertToUInt64()} {appid}-{contextid} inventory page"); var url = "https://" + $"steamcommunity.com/my/inventory/json/{appid}/{contextid}?l=english&count={count}&start_assetid={startAssetid}"; var response = SteamWeb.Request(url, "GET", dataString: null, cookies: cookies, proxy: this.Proxy); MyInventoryRootModel inventoryRoot; try { inventoryRoot = JsonConvert.DeserializeObject <MyInventoryRootModel>(response); } catch (JsonException ex) { Logger.Log.Error($"Error on inventory loading - {ex.Message}", ex); inventoryRoot = null; } return(inventoryRoot); }
/// <summary> /// Constructor to initialize our variables /// </summary> /// <param name="_mobileHelper"></param> /// <param name="_botInfo"></param> /// <param name="_steamWeb"></param> /// <param name="_logger"></param> public TradeOfferHelperClass(MobileHelper _mobileHelper, BotInfo _botInfo, SteamWeb _steamWeb, Logger.Logger _logger) { m_mobileHelper = _mobileHelper; m_tradeOfferWebAPI = new TradeOfferWebAPI(m_steamWeb, m_logger); m_botInfo = _botInfo; m_steamWeb = _steamWeb; m_logger = _logger; }
public OfferSession(TradeOfferWebAPI webApi, SteamWeb steamWeb) { this.webApi = webApi; this.steamWeb = steamWeb; JsonSerializerSettings = new JsonSerializerSettings(); JsonSerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None; JsonSerializerSettings.Formatting = Formatting.None; }
/// <summary> /// Constructor to initialize variables and the class /// </summary> /// <param name="_gamesLibraryHelper"></param> /// <param name="_steamWeb"></param> /// <param name="_logger"></param> public CardFarmHelperClass(GamesLibraryHelperClass _gamesLibraryHelper, SteamWeb _steamWeb, Logger.Logger _logger) { m_steamWeb = _steamWeb; m_steamUserWebAPI = new SteamUserWebAPI(m_steamWeb); m_logger = _logger; m_gamesLibraryHelper = _gamesLibraryHelper; }
public bool BuyOnMarket( double averagePrice, int appid, string hashName, double?ratio, bool buyPackages, int currency) { // the ratio is a value client is ready to accept the difference between average and current price ratio += 1; var order = this.FindBuyingOrder(averagePrice, appid, hashName, ratio); var data = new NameValueCollection { { "sessionid", this.SteamClient.Session.SessionID }, { "currency", currency.ToString() }, { "appid", appid.ToString() }, { "market_hash_name", hashName } }; var quantity = 1; if (buyPackages) { quantity *= order.Count; } // "G", CultureInfo.InvariantCulture - use these as arguments to convert double into string with dots data["price_total"] = (order.Price * 100 * quantity).ToString("G", CultureInfo.InvariantCulture); data["quantity"] = quantity.ToString(); var response = SteamWeb.Request( "https://steamcommunity.com/market/createbuyorder/", "POST", data, this.Cookies, proxy: this.Proxy); var responseJson = (NameValueCollection)JsonConvert.DeserializeObject(response); var success = responseJson["success"]; if (success == null) { Logger.Log.Error("Invalid response from createbuyorder request"); return(false); } var buyOrderId = responseJson["buy_orderid"]; if (success != "1") { Logger.Log.Debug(responseJson["message"]); if (responseJson["message"].Contains("You already have an active buy order")) { this.CancelBuyOrder(buyOrderId); return(false); } } return(true); }
public TradeOfferWebAPI(string apiKey, SteamWeb steamWeb) { this._steamWeb = steamWeb; this._apiKey = apiKey; if (apiKey == null) { throw new ArgumentNullException("apiKey"); } }
public TradeOfferManager(string apiKey, SteamWeb steamWeb) { if (apiKey == null) { throw new ArgumentNullException("apiKey"); } webApi = new TradeOfferWebAPI(apiKey, steamWeb); session = new OfferSession(webApi, steamWeb); }
private InventoryRootModel LoadInventoryPage(SteamID steamid, int appid, int contextid, string startAssetid = "", int count = 5000) { var url = "https://" + $"steamcommunity.com/inventory/{steamid.ConvertToUInt64()}/{appid}/{contextid}?l=english&count={count}&start_assetid={startAssetid}"; var response = SteamWeb.Request(url, "GET", dataString: null); var inventoryRoot = JsonConvert.DeserializeObject <InventoryRootModel>(response); return(inventoryRoot); }
/// <summary> /// Adds or removes the provided workshop item from the collection. /// </summary> /// <param name="workshopid">The WorkshopID of the workshopitem.</param> /// <param name="remove">If true the workshopitem will be removed instead of being addded.</param> public static void ModifyCollection(ulong workshopid, bool remove) { var login = Globals.SteamLogin; var data = "sessionID=" + login.Session.SessionID + "&publishedfileid=" + workshopid + "&collections%5B1377816355%5D%5B" + (remove ? "remove" : "add") + "%5D=true&collections%5B1377816355%5D%5Btitle%5D=Die+Unausstehlichen+-+TTT"; CookieContainer cookies = new CookieContainer(); login.Session.AddCookies(cookies); var response = SteamWeb.Request("https://steamcommunity.com/sharedfiles/ajaxaddtocollections", "POST", data, cookies); Console.WriteLine(response); }
public TradeOfferManager(string apiKey, SteamWeb steamWeb, DateTime lastTimeCheckedOffers) { if (apiKey == null) { throw new ArgumentNullException(nameof(apiKey)); } LastTimeCheckedOffers = lastTimeCheckedOffers; _webApi = new TradeOfferWebAPI(apiKey, steamWeb); Session = new OfferSession(_webApi, steamWeb); _unhandledTradeOfferUpdates = new ConcurrentQueue <Offer>(); }
public TradeOfferManager(string apiKey, SteamWeb steamWeb) { if (apiKey == null) { throw new ArgumentNullException("apiKey"); } LastTimeCheckedOffers = DateTime.MinValue; webApi = new TradeOfferWebAPI(apiKey, steamWeb); session = new OfferSession(webApi, steamWeb); unhandledTradeOfferUpdates = new Queue <Offer>(); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { int attempts = 1; InventoryResponse result = null; while ((result == null || result.result.items == null) && attempts <= 3) { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch(url, "GET", null, false); result = JsonConvert.DeserializeObject<InventoryResponse>(response); attempts++; } return new Inventory(result.result); }
public string Fetch(string url, string method, NameValueCollection data = null, bool ajax = false, string referer = "") { try { HttpWebResponse response = SteamWeb.Request(url, method, data, Cookies, ajax, referer); return(ReadWebStream(response)); } catch (WebException we) { Debug.WriteLine(we); return(ReadWebStream(we.Response)); } }
public Trade(TradeOffers tradeOffers, SteamID partnerId, SteamWeb steamWeb) { _tradeOffers = tradeOffers; _partnerId = partnerId; _steamWeb = steamWeb; tradeStatus = new TradeStatus { version = 1, newversion = true }; tradeStatus.me = new TradeStatusUser(ref tradeStatus); tradeStatus.them = new TradeStatusUser(ref tradeStatus); }
/// <summary> /// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class. /// </summary> /// <param name='apiKey'> /// The Steam Web API key. Cannot be null. /// </param> /// <param name="steamWeb"> /// The SteamWeb instances for this bot /// </param> public TradeManager(string apiKey, SteamWeb steamWeb) { if (apiKey == null) throw new ArgumentNullException ("apiKey"); if (steamWeb == null) throw new ArgumentNullException ("steamWeb"); SetTradeTimeLimits (MaxTradeTimeDefault, MaxGapTimeDefault, TradePollingIntervalDefault); ApiKey = apiKey; SteamWeb = steamWeb; }
public bool DeclineTradeOffer(ulong tradeofferid) { var options = $"?key={this._apiKey}&tradeofferid={tradeofferid}"; var url = string.Format(BaseUrl, "DeclineTradeOffer", "v1", options); var response = SteamWeb.Request(url, "POST", data: null, proxy: this._proxy); dynamic json = JsonConvert.DeserializeObject(response); if (json == null || json.success != "1") { return(false); } return(true); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static Inventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb, Action<string> chatMessage) { int attempts = 1; InventoryResponse result = null; while (result == null || result.result?.items == null) { try { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = steamWeb.Fetch(url, "GET", null, false); result = JsonConvert.DeserializeObject<InventoryResponse>(response); } catch (WebException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR IN INVENTORY.FETCHINVENTORY: " + e.ToString()); Console.ForegroundColor = ConsoleColor.White; result = null; Thread.Sleep(500); } attempts++; if (attempts == 4) { attempts = 0; if (_failedFetch) { //Console.ForegroundColor = ConsoleColor.Red; //Console.WriteLine("Fetch Failing already. Aborting."); //Thread.CurrentThread.Abort(); } if (chatMessage != null) { _failedFetch = true; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Unable to fetch inventory of user #{0}. Giving up.", steamId.ToString()); Console.ForegroundColor = ConsoleColor.White; //chatMessage("I am currently encountering issues connecting to Steam. Please try again in a few minutes."); return null; } } } return new Inventory(result.result); }
/// <summary> /// Initializes a new instance of the <see cref="SteamTrade.TradeManager"/> class. /// </summary> /// <param name='apiKey'> /// The Steam Web API key. Cannot be null. /// </param> /// <param name="steamWeb"> /// The SteamWeb instances for this bot /// </param> public TradeManager(string apiKey, SteamWeb steamWeb, Action<string> sendChat) { if (apiKey == null) throw new ArgumentNullException ("apiKey"); if (steamWeb == null) throw new ArgumentNullException ("steamWeb"); SetTradeTimeLimits (_MAX_TRADE_TIME_DEF, _MAX_GAP_TIME_DEF, _TRADE_POLLING_INTERVAL_DEF); _apiKey = apiKey; _steamWeb = steamWeb; _sendChatMessage = sendChat; }
public static int GetGemsCount(FullRgItem item, CookieContainer steamCookies, WebProxy proxy = null) { var ownerTag = item.Description.OwnerActions?.FirstOrDefault(t => t.Name.Equals("Turn into Gems...", StringComparison.InvariantCultureIgnoreCase)); int gemsCount = 0; if (ownerTag == null) { Gems.Add(item.Description.MarketHashName, gemsCount); return(gemsCount); } if (TryGetGemsCount(item, out gemsCount)) { return(gemsCount); } //javascript:GetGooValue( '%contextid%', '%assetid%', 603770, 3, 1 ) var regex = Regex.Match(ownerTag.Link, "javascript:GetGooValue\\( '%contextid%', '%assetid%', (\\d+), (\\d+), (\\d+) \\)"); var appId = regex.Groups[1].Value; var itemType = regex.Groups[2].Value; var border = regex.Groups[3].Value; var response = SteamWeb.Request( $"https://steamcommunity.com/auction/ajaxgetgoovalueforitemtype/?appid={appId}&item_type={itemType}&border_color={border}", "GET", data: null, cookies: steamCookies, proxy: proxy); var json = JsonConvert.DeserializeObject <GooResponse>(response); if (json.Success != 1) { throw new WebException($"Success status is {json.Success}"); } gemsCount = int.Parse(json.GooValue); Gems.Add(item.Description.MarketHashName, gemsCount); if (++_updateFileCounter == 5) { _updateFileCounter = 0; UpdateFile(); } return(gemsCount); }
public static void Login() { Console.WriteLine("[" + Program.BOTNAME + "] - Starting Login..."); isRunning = true; steamClient = new SteamClient(); steamWeb = new SteamWeb(); gamesHandler = new GamesHandler(); MercuryManager = new CallbackManager(steamClient); //DebugLog.AddListener(new MyListener()); //DebugLog.Enabled = true; #region Callbacks steamUser = steamClient.GetHandler <SteamUser>(); steamFriends = steamClient.GetHandler <SteamFriends>(); MercuryManager.Subscribe <SteamClient.ConnectedCallback>(OnConnected); MercuryManager.Subscribe <SteamClient.DisconnectedCallback>(OnDisconnected); MercuryManager.Subscribe <SteamUser.LoggedOnCallback>(OnLoggedOn); MercuryManager.Subscribe <SteamUser.LoggedOffCallback>(OnLoggedOff); MercuryManager.Subscribe <SteamUser.AccountInfoCallback>(OnAccountInfo); MercuryManager.Subscribe <SteamUser.UpdateMachineAuthCallback>(OnMachineAuth); MercuryManager.Subscribe <SteamUser.LoginKeyCallback>(OnLoginKey); MercuryManager.Subscribe <SteamUser.WebAPIUserNonceCallback>(WebAPIUser); MercuryManager.Subscribe <SteamFriends.FriendsListCallback>(OnFriendsList); MercuryManager.Subscribe <SteamFriends.FriendMsgCallback>(OnFriendMsg); MercuryManager.Subscribe <SteamFriends.FriendMsgEchoCallback>(OnFriendEchoMsg); MercuryManager.Subscribe <SteamFriends.PersonaStateCallback>(OnPersonaState); MercuryManager.Subscribe <SteamFriends.PersonaChangeCallback>(OnSteamNameChange); #endregion steamClient.AddHandler(gamesHandler); MercuryManager.Subscribe <PurchaseResponseCallback>(OnPurchaseResponse); Console.WriteLine("[" + Program.BOTNAME + "] - Connecting to Steam..."); steamClient.Connect(); while (isRunning) { MercuryManager.RunWaitCallbacks(TimeSpan.FromMilliseconds(500)); } }
private bool CancelTradeOffer(ulong tradeofferid) { string options = string.Format("?key={0}&tradeofferid={1}", ApiKey, tradeofferid); string url = String.Format(BaseUrl, "CancelTradeOffer", "v1", options); Debug.WriteLine(url); string response = SteamWeb.Fetch(url, "POST", null, null, false); dynamic json = JsonConvert.DeserializeObject(response); if (json == null || json.success != "1") { return(false); } return(true); }
public void Run(IBackgroundTaskInstance taskInstance) { var web = new SteamWeb(); var locks = new List <WaitHandle>(); var notifCount = 0; foreach (ulong steamid in Storage.GetAccounts().Keys) { SteamGuardAccount acc = Storage.GetSteamGuardAccount(steamid); if (!acc.FullyEnrolled) { continue; } var lck = new AutoResetEvent(false); locks.Add(lck); acc.FetchConfirmations(web, (response, ex) => { if (ex != null) { acc.RefreshSession(web, success => { if (success == Success.Failure) { Storage.Logout(acc.Session.SteamID); } lck.Set(); }); return; } foreach (Confirmation c in response.Where(c => c.ID > acc.NotifySince)) { ShowNotification(steamid, c.ID.ToString(), c.Description, c.Description2); } notifCount += response.Count; acc.NotifySince = response.DefaultIfEmpty().Max(x => x?.ID ?? 0); acc.PushStore(); lck.Set(); }); } if (locks.Count == 0 || WaitHandle.WaitAll(locks.ToArray(), TimeSpan.FromSeconds(15))) { SetBadgeCount(notifCount); } }
public TradeOffers(SteamID botId, SteamWeb steamWeb, string accountApiKey, List<ulong> pendingTradeOffers = null) { this.BotId = botId; this.SteamWeb = steamWeb; this.AccountApiKey = accountApiKey; this.ShouldCheckPendingTradeOffers = true; if (pendingTradeOffers == null) this.OurPendingTradeOffers = new List<ulong>(); else this.OurPendingTradeOffers = pendingTradeOffers; this.ReceivedPendingTradeOffers = new List<ulong>(); new System.Threading.Thread(CheckPendingTradeOffers).Start(); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="appid"></param> public Inventory FetchInventory(ulong steamId, string apiKey, int appid) { var attempts = 1; InventoryResponse result = null; while ((result?.result.Items == null) && attempts <= 3) { var url = $"http://api.steampowered.com/IEconItems_{appid}/GetPlayerItems/v0001/?key={apiKey}&steamid={steamId}"; var response = SteamWeb.Request(url, "GET", data: null, referer: "http://api.steampowered.com"); result = JsonConvert.DeserializeObject <InventoryResponse>(response); attempts++; } return(new Inventory(result?.result)); }
public static void SendUsageStats(ulong steamId) { string systemName = string.Empty; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem"); foreach (System.Management.ManagementObject os in searcher.Get()) { systemName = os["Caption"].ToString(); break; } var data = new System.Collections.Specialized.NameValueCollection(); data.Add("steamId", steamId.ToString()); data.Add("os", systemName); SteamWeb.Fetch("http://jzhang.net/mist/stats.php", "POST", data); }
public string FetchTradeToken() { this.IsSessionUpdated = true; Logger.Log.Debug("Parsing trade token from - 'https://steamcommunity.com/my/tradeoffers/privacy'"); try { var response = SteamWeb.Request( "https://steamcommunity.com/my/tradeoffers/privacy", "GET", string.Empty, this.Cookies, proxy: this.Proxy); if (response == null) { Logger.Log.Warn( "Error on parsing trade token. Steam privacy page cant not be loaded. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'"); return(null); } var token = Regex.Match( response, @"https://steamcommunity\.com/tradeoffer/new/\?partner=.+&token=(.+?)""").Groups[1].Value; if (string.IsNullOrEmpty(token)) { Logger.Log.Warn( "Error on parsing trade token. Steam privacy page cant not be loaded. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'"); return(null); } Logger.Log.Debug($"'{token}' trade token was successfully parsed"); return(token); } catch (Exception e) { Logger.Log.Warn( $"Error on parsing trade token. {e.Message}. Try to scrap it manually from - 'https://steamcommunity.com/my/tradeoffers/privacy'"); return(null); } }
/// <summary> /// Gets the inventory for the given Steam ID using the Steam Community website. /// </summary> /// <returns>The inventory for the given user. </returns> /// <param name='steamid'>The Steam identifier. </param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static dynamic GetInventory(SteamID steamid, SteamWeb steamWeb) { string url = String.Format( "http://steamcommunity.com/profiles/{0}/inventory/json/730/2/?trading=1", steamid.ConvertToUInt64() ); try { string response = steamWeb.Fetch(url, "GET"); return JsonConvert.DeserializeObject(response); } catch (Exception) { return JsonConvert.DeserializeObject("{\"success\":\"false\"}"); } }
public TradeOffers(SteamID botId, SteamWeb steamWeb, string accountApiKey, int tradeOfferRefreshRate, List <ulong> pendingTradeOffers = null) { _botId = botId; _steamWeb = steamWeb; _accountApiKey = accountApiKey; _shouldCheckPendingTradeOffers = true; _tradeOfferRefreshRate = tradeOfferRefreshRate; OurPendingTradeOffers = pendingTradeOffers ?? new List <ulong>(); _ourPendingTradeOffersLock = new object(); _handledTradeOffers = new List <ulong>(); _awaitingConfirmationTradeOffers = new List <ulong>(); _inEscrowTradeOffers = new List <ulong>(); new Thread(CheckPendingTradeOffers).Start(); }
public OfferResponse GetTradeOffer(string tradeofferid) { string options = string.Format("?key={0}&tradeofferid={1}&language={2}", ApiKey, tradeofferid, "en_us"); string url = String.Format(BaseUrl, "GetTradeOffer", "v1", options); try { string response = SteamWeb.Fetch(url, "GET", null, null, false); var result = JsonConvert.DeserializeObject <ApiResponse <OfferResponse> >(response); return(result.Response); } catch (Exception ex) { //todo log Debug.WriteLine(ex); } return(new OfferResponse()); }
public OfferResponse GetTradeOffer(string tradeofferid) { var options = string.Format("?key={0}&tradeofferid={1}&language={2}", this._apiKey, tradeofferid, "en_us"); var url = string.Format(BaseUrl, "GetTradeOffer", "v1", options); try { var response = SteamWeb.Request(url, "GET", data: null, proxy: this._proxy); var result = JsonConvert.DeserializeObject <ApiResponse <OfferResponse> >(response); return(result.Response); } catch (Exception ex) { Logger.Log.Error("Error on getting trade offers", ex); } return(new OfferResponse()); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> /// <param name="steamWeb">The SteamWeb instance for this Bot</param> public static CSGOInventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { var url = "http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; for (int i = 0; i < 100; i++) { try { string response = steamWeb.Fetch(url, "GET", null, false); InventoryResponse result = JsonConvert.DeserializeObject<InventoryResponse>(response); if (result.result != null) { return new CSGOInventory(result.result) as CSGOInventory; } } catch (System.Net.WebException we) { } } throw new InventoryException("Failed to load CSGO inventory."); }
/// <summary> /// Fetches the inventory for the given Steam ID using the Steam API. /// </summary> /// <returns>The give users inventory.</returns> /// <param name='steamId'>Steam identifier.</param> /// <param name='apiKey'>The needed Steam API key.</param> public static CsgoInventory FetchInventory(ulong steamId, string apiKey, SteamWeb steamWeb) { //TODO: Add a while loop here to try to fetch multiple times because according the //original authors the steam API is not reliable. //var url = "http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; var url = string.Format("http://steamcommunity.com/profiles/{0}/inventory/json/{1}/{2}", steamId, 730, 2); var response = steamWeb.Fetch(url, "GET", null, false); dynamic obj = JsonConvert.DeserializeObject<dynamic>(response); bool success = obj["success"]; bool more = obj["more"]; bool moreStart = obj["more_start"]; var items = new List<Item>(); foreach (var variable in obj["rgDescriptions"].Children()) { string str = variable.Value.ToString(); var desc = JsonConvert.DeserializeObject<Item>(str); items.Add(desc); } //var result = JsonConvert.DeserializeObject<InventoryResponse>(response); return new CsgoInventory(items, success, more, moreStart); }
public void UpdateSteamBansData(SteamWeb.Models.PlayerBans bans) { HasVACBan = bans.IsVACBanned; VACBanCount = bans.VACBanCount; DaysSinceLastVACBan = bans.DaysSinceLastBan; }
public static void Main (string[] args) { #region SteamRE Init AllArgs = args; //Hacking around https ServicePointManager.CertificatePolicy = new MainClass (); Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine ("\n\tSteamBot Beta\n\tCreated by Jessecar96.\n\n"); Console.ForegroundColor = ConsoleColor.White; steamClient = new SteamClient (); steamTrade = steamClient.GetHandler<SteamTrading>(); SteamUser steamUser = steamClient.GetHandler<SteamUser> (); steamFriends = steamClient.GetHandler<SteamFriends>(); steamClient.Connect (); #endregion while (true) { CallbackMsg msg = steamClient.WaitForCallback (true); //Console Debug printConsole (msg.ToString(),ConsoleColor.Blue,true); #region Logged Off Handler msg.Handle<SteamUser.LoggedOffCallback> (callback => { printConsole("Logged Off: "+callback.Result,ConsoleColor.Red); }); #endregion #region Steam Disconnect Handler msg.Handle<SteamClient.DisconnectedCallback> (callback => { printConsole("Disconnected.",ConsoleColor.Red); }); #endregion #region Steam Connect Handler /** * --Steam Connection Callback * * It's not needed to modify this section */ msg.Handle<SteamClient.ConnectedCallback> (callback => { //Print Callback printConsole("Steam Connected Callback: "+callback.Result, ConsoleColor.Cyan); //Validate Result if(callback.Result==EResult.OK){ //Get Steam Login Details printConsole("Username: "******"Password: "******"Getting Web Cookies...",ConsoleColor.Yellow); //Get Web Cookies SteamWeb web = new SteamWeb(); WebCookies = web.DoLogin (user,pass); if(WebCookies!=null){ printConsole ("SteamWeb Cookies retrived.",ConsoleColor.Green); //Do Login steamUser.LogOn (new SteamUser.LogOnDetails{ Username = user, Password = pass }); }else{ printConsole ("Error while getting SteamWeb Cookies.",ConsoleColor.Red); } }else{ //Failure printConsole ("Failed to Connect to steam.",ConsoleColor.Red); } }); #endregion #region Steam Login Handler //Logged in (or not) msg.Handle<SteamUser.LoggedOnCallback>( callback => { printConsole("Logged on callback: "+callback.Result, ConsoleColor.Cyan); if(callback.Result != EResult.OK){ printConsole("Login Failed!",ConsoleColor.Red); }else{ printConsole("Successfulyl Logged In!\nWelcome "+steamUser.SteamID,ConsoleColor.Green); //Set community status steamFriends.SetPersonaName(BotPersonaName); steamFriends.SetPersonaState(BotPersonaState); } }); #endregion #region Steam Trade Start /** * * Steam Trading Handler * */ msg.Handle<SteamTrading.TradeStartSessionCallback>(call => { //Trading trade = null; trade = new TradeSystem(); trade.initTrade(steamUser.SteamID,call.Other,WebCookies); }); #endregion #region Trade Requested Handler //Don't modify this msg.Handle<SteamTrading.TradeProposedCallback>( thing => { //Trade Callback printConsole ("Trade Proposed Callback. Other: "+thing.Other+"\n"); //Accept It steamTrade.RequestTrade(thing.Other); }); #endregion msg.Handle<SteamFriends.PersonaStateCallback>(callback => { if (callback.FriendID == steamUser.SteamID) return; EFriendRelationship relationship = steamFriends.GetFriendRelationship(callback.FriendID); if (!(relationship == EFriendRelationship.RequestRecipient)) return; if(steamFriends.GetFriendRelationship(callback.FriendID)==EFriendRelationship.PendingInvitee){ printConsole("[Friend] Friend Request Pending: " + callback.FriendID + "(" + steamFriends.GetFriendPersonaName(callback.FriendID) + ") - Accepted", ConsoleColor.Yellow); steamFriends.AddFriend(callback.FriendID); } }); #region Steam Chat Handler /** * * Steam Chat Handler * */ msg.Handle<SteamFriends.FriendMsgCallback>(callback => { //Type (emote or chat) EChatEntryType type = callback.EntryType; if(type == EChatEntryType.ChatMsg){ //Message is a chat message //Reply with the same message steamFriends.SendChatMessage(callback.Sender,EChatEntryType.ChatMsg,callback.Message); //Chat API coming soon }else if(type == EChatEntryType.Emote){ //Message is emote //Do nothing yet } }); #endregion } //end while loop } //end Main method
public void UpdateSteamFriendData(SteamWeb.Models.Friend friend) { KnownFriends.Add(friend.FriendSteamID); }
public void UpdateSteamPlayerData(SteamWeb.Models.Player steamPlayer) { Name = steamPlayer.PersonaName; AvatarSmallURL = steamPlayer.AvatarSmallURL; AvatarMediumURL = steamPlayer.AvatarMediumURL; AvatarFullURL = steamPlayer.AvatarFullURL; IsSteamProfilePrivate = steamPlayer.CommunityVisibilityState != SteamWeb.CommunityVisibilityState.Public; IsSteamProfileConfigured = steamPlayer.ProfileState == SteamWeb.ProfileState.Setup; SteamProfileTimeCreated = steamPlayer.TimeCreated; if (!IsSteamProfilePrivate) { RealName = steamPlayer.RealName; CountryCode = steamPlayer.LocationCountryCode; } }
public void UpdateSteamGamesData(SteamWeb.Models.OwnedGames games) { SteamGameCount = games.GameCount; }
public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { userHandlers = new Dictionary<SteamID, UserHandler>(); logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; isProccess = process; try { if( config.LogLevel != null ) { consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName); } else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); consoleLogLevel = Log.LogLevel.Info; } try { fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); fileLogLevel = Log.LogLevel.Info; } logFile = config.LogFile; Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel); createHandler = handlerCreator; BotControlClass = config.BotControlClass; SteamWeb = new SteamWeb(); // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; Log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamClient.AddHandler(new SteamNotifications()); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; botThread.RunWorkerAsync(); }
public GenericInventory(SteamWeb steamWeb) { SteamWeb = steamWeb; }
public Trade(TradeOffers tradeOffers, SteamID partnerId, SteamWeb steamWeb) { this.TradeOffers = tradeOffers; this.partnerId = partnerId; this.steamWeb = steamWeb; tradeStatus = new TradeStatus(); tradeStatus.version = 1; tradeStatus.newversion = true; tradeStatus.me = new TradeStatusUser(ref tradeStatus); tradeStatus.them = new TradeStatusUser(ref tradeStatus); }
private static string RetryWebRequest(SteamWeb steamWeb, string url, string method, NameValueCollection data, bool ajax = false, string referer = "") { for (int i = 0; i < 10; i++) { try { var response = steamWeb.Request(url, method, data, ajax, referer); using (System.IO.Stream responseStream = response.GetResponseStream()) { using (var reader = new System.IO.StreamReader(responseStream)) { string result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) { Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode); System.Threading.Thread.Sleep(1000); } else { return result; } } } } catch (WebException ex) { try { if (ex.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code: {0}, {1}", (int)((HttpWebResponse)ex.Response).StatusCode, ((HttpWebResponse)ex.Response).StatusDescription); } Console.WriteLine("Error: {0}", new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd()); } catch { } } catch (Exception ex) { Console.WriteLine(ex); } } return ""; }
public void UpdateFamilyShareData(SteamWeb.Models.FamilyShareAccount familyShare) { IsFamilyShareAccount = familyShare.IsFamilyShareAccount; FamilyShareLenderSteamID = familyShare.LenderSteamID; }