public Bot(Manager botManager, LoginInfo loginInfo, Config config, AsynchronousSocketListener socket) { this.socket = socket; this.config = config; this.loginInfo = loginInfo; this.botManager = botManager; steamClient = new SteamClient(); messageHandler = new HandleMessage(); steamWeb = new SteamTrade.SteamWeb(); manager = new CallbackManager(steamClient); steamchatHandler = new HandleSteamChat(this); MyGenericInventory = new GenericInventory(steamWeb); steamCallbackManager = new CallbackManager(steamClient); this.socket.MessageReceived += Socket_MessageReceived; DB = new Database(config.DatabaseServer, config.DatabaseUser, config.DatabasePassword, config.DatabaseName, config.DatabasePort); DB.InitialiseDatabase(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; System.Timers.Timer refreshMarket = new System.Timers.Timer(421000);//15*1000*60); refreshMarket.Elapsed += UpdateMarketItems; refreshMarket.AutoReset = true; refreshMarket.Enabled = true; }
/// <summary> /// Fetches the Tf2 Item schema. /// </summary> /// <param name="apiKey">The API key.</param> /// <returns>A deserialized instance of the Item Schema.</returns> /// <remarks> /// The schema will be cached for future use if it is updated. /// </remarks> public static TF2Schema FetchSchema(string apiKey) { var url = SchemaApiUrlBase + apiKey; // just let one thread/proc do the initial check/possible update. bool wasCreated; var mre = new EventWaitHandle(false, EventResetMode.ManualReset, SchemaMutexName, out wasCreated); // the thread that create the wait handle will be the one to // write the cache file. The others will wait patiently. if (!wasCreated) { bool signaled = mre.WaitOne(10000); if (!signaled) { return(null); } } HttpWebResponse response = SteamWeb.Request(url, "GET"); DateTime schemaLastModified = response.LastModified; string result = GetSchemaString(response, schemaLastModified); response.Close(); mre.Set(); SchemaResult schemaResult = JsonConvert.DeserializeObject <SchemaResult> (result); return(schemaResult.result ?? null); }
/// <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 Inventory FetchInventory (ulong steamId, string apiKey) { var url = "http://api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/?key=" + apiKey + "&steamid=" + steamId; string response = SteamWeb.Fetch (url, "GET", null, null, false); InventoryResponse result = JsonConvert.DeserializeObject<InventoryResponse>(response); return new Inventory(result.result); }
public static Schema FetchSchema(string apiKey) { var url = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=" + apiKey; string cachefile = "tf_schema.cache"; string result; HttpWebResponse response = SteamWeb.Request(url, "GET"); DateTime SchemaLastModified = DateTime.Parse(response.Headers["Last-Modified"]); if (!System.IO.File.Exists(cachefile) || (SchemaLastModified > System.IO.File.GetCreationTime(cachefile))) { StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); File.WriteAllText(cachefile, result); System.IO.File.SetCreationTime(cachefile, SchemaLastModified); } else { TextReader reader = new StreamReader(cachefile); result = reader.ReadToEnd(); reader.Close(); } response.Close(); SchemaResult schemaResult = JsonConvert.DeserializeObject <SchemaResult> (result); return(schemaResult.result ?? null); }
public static Schema FetchSchema(string apiKey) { var url = "http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=" + apiKey; string result = SteamWeb.Fetch(url, "GET"); SchemaResult schemaResult = JsonConvert.DeserializeObject <SchemaResult> (result); return(schemaResult.result ?? null); }
public GenericInventory(SteamID steamID, SteamWeb steamWeb) { SteamWeb = steamWeb; if (steamID != null) { object[] args = new object[2]; args[0] = steamID; args[1] = this; Program.ExecuteModuleFonction("Start", args); } }
/// <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> /// 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 static Schema FetchSchema(string apiKey) { var url = "http://api.steampowered.com/IEconItems_570/GetSchema/v0001/?key=" + apiKey + "&language=en"; string cachefile = "d2_schema.cache"; string result = ""; try { HttpWebResponse response = SteamWeb.Request(url, "GET"); DateTime SchemaLastModified = DateTime.Now; try { SchemaLastModified = DateTime.Parse(response.Headers["Last-Modified"]); } catch { SchemaLastModified = DateTime.Now; } if (!System.IO.File.Exists(cachefile) || (SchemaLastModified > System.IO.File.GetCreationTime(cachefile))) { StreamReader reader = new StreamReader(response.GetResponseStream()); result = reader.ReadToEnd(); File.WriteAllText(cachefile, result); System.IO.File.SetCreationTime(cachefile, SchemaLastModified); } else { TextReader reader = new StreamReader(cachefile); result = reader.ReadToEnd(); reader.Close(); } response.Close(); } catch (NullReferenceException ex) { //.net 4.5 will error out on Request. using (var wc = new WebClient()) { result = wc.DownloadString(url); } } SchemaResult schemaResult = JsonConvert.DeserializeObject <SchemaResult> (result); return(schemaResult.result ?? 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> public static dynamic GetInventory(SteamID steamid) { string url = String.Format( "http://steamcommunity.com/profiles/{0}/inventory/json/440/2/?trading=1", steamid.ConvertToUInt64() ); try { string response = SteamWeb.Fetch(url, "GET", null, null, true); return(JsonConvert.DeserializeObject(response)); } catch (Exception) { return(JsonConvert.DeserializeObject("{\"success\":\"false\"}")); } }
/// <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; }
private static string RetryWebRequest(string url, string method, NameValueCollection data, CookieContainer cookies, bool ajax = false, string referer = "") { for (int i = 0; i < 10; i++) { try { var response = SteamWeb.Request(url, method, data, cookies, 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(""); }
/// <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 bool Autenticate() { web = new SteamWeb(); web.Authenticate(cookies); if (!web.VerifyCookies()) { return(false); } api = new TradeOfferWebAPI(apiKey, web); manager = new TradeOfferManager(apiKey, web); session = new OfferSession(api, web); SteamID = new SteamID(76561198043356049); TradeOfferCheckingLoop(); return(true); }
internal Trade(SteamID me, SteamID other, SteamWeb steamWeb, Task <Inventory> myInventoryTask, Task <Inventory> otherInventoryTask) { TradeStarted = false; OtherIsReady = false; MeIsReady = false; mySteamId = me; OtherSID = other; session = new TradeSession(other, steamWeb); this.eventList = new List <TradeEvent>(); myOfferedItemsLocalCopy = new Dictionary <int, TradeUserAssets>(); otherOfferedItems = new List <TradeUserAssets>(); myOfferedItems = new List <TradeUserAssets>(); this.otherInventoryTask = otherInventoryTask; this.myInventoryTask = myInventoryTask; }
/// <summary> /// Calls the given function multiple times, until we get a non-null/non-false/non-zero result, or we've made at least /// WEB_REQUEST_MAX_RETRIES attempts (with WEB_REQUEST_TIME_BETWEEN_RETRIES_MS between attempts) /// </summary> /// <returns>The result of the function if it succeeded, or an empty string otherwise</returns> private string RetryWebRequest(string url, SteamID botId) { for (int i = 0; i < WEB_REQUEST_MAX_RETRIES; i++) { try { return(SteamWeb.Fetch(url, "GET", null, Cookies[botId])); } catch (Exception ex) { Console.WriteLine(ex); } if (i != WEB_REQUEST_MAX_RETRIES) { System.Threading.Thread.Sleep(WEB_REQUEST_TIME_BETWEEN_RETRIES_MS); } } return(""); }
/// <summary> /// Fetches the Tf2 Item schema. /// </summary> /// <param name="apiKey">The API key.</param> /// <returns>A deserialized instance of the Item Schema.</returns> /// <remarks> /// The schema will be cached for future use if it is updated. /// </remarks> public static Schema FetchSchema (string apiKey, string schemaLang = null) { var url = SchemaApiUrlBase + apiKey; if (schemaLang != null) url += "&language=" + schemaLang; // just let one thread/proc do the initial check/possible update. bool wasCreated; var mre = new EventWaitHandle(false, EventResetMode.ManualReset, SchemaMutexName, out wasCreated); // the thread that create the wait handle will be the one to // write the cache file. The others will wait patiently. if (!wasCreated) { bool signaled = mre.WaitOne(10000); if (!signaled) { return null; } } using(HttpWebResponse response = new SteamWeb().Request(url, "GET")) { DateTime schemaLastModified = response.LastModified; string result = GetSchemaString(response, schemaLastModified); // were done here. let others read. mre.Set(); SchemaResult schemaResult = JsonConvert.DeserializeObject<SchemaResult>(result); return schemaResult.result ?? null; } }
public GenericInventory(SteamWeb steamWeb) { SteamWeb = steamWeb; }
public OLDSteamMarketPrices(SteamWeb sw) { steamWeb = sw; Items = new List <Item>(); }
string Fetch(string url, string method, NameValueCollection data = null) { return(SteamWeb.Fetch(url, method, data, cookies)); }
public void loadImplementation(int appid, IEnumerable <long> contextIds, SteamID steamid) { dynamic invResponse; isLoaded = false; Dictionary <string, string> tmpAppData; _items.Clear(); _descriptions.Clear(); _errors.Clear(); try { foreach (long contextId in contextIds) { string response = SteamWeb.Fetch(string.Format("http://steamcommunity.com/profiles/{0}/inventory/json/{1}/{2}/", steamid.ConvertToUInt64(), appid, contextId), "GET", null, null, true); invResponse = JsonConvert.DeserializeObject(response); if (invResponse.success == false) { _errors.Add("Fail to open backpack: " + invResponse.Error); continue; } //rgInventory = Items on Steam Inventory foreach (var item in invResponse.rgInventory) { foreach (var itemId in item) { _items.Add((ulong)itemId.id, new Item() { appid = appid, contextid = contextId, assetid = itemId.id, descriptionid = itemId.classid + "_" + itemId.instanceid }); break; } } // rgDescriptions = Item Schema (sort of) foreach (var description in invResponse.rgDescriptions) { foreach (var class_instance in description)// classid + '_' + instenceid { if (class_instance.app_data != null) { tmpAppData = new Dictionary <string, string>(); foreach (var value in class_instance.app_data) { tmpAppData.Add("" + value.Name, "" + value.Value); } } else { tmpAppData = null; } _descriptions.Add("" + (class_instance.classid ?? '0') + "_" + (class_instance.instanceid ?? '0'), new ItemDescription() { name = class_instance.name, type = class_instance.type, marketable = (bool)class_instance.marketable, tradable = (bool)class_instance.tradable, app_data = tmpAppData } ); break; } } } //end for (contextId) } //end try catch (Exception e) { Console.WriteLine(e.Message); _errors.Add("Exception: " + e.Message); } isLoaded = true; }
/// <summary> /// SimpleInventory constructor /// </summary> /// <param name="steamweb">SteamWeb session</param> public SimpleInventory(SteamWeb steamweb) { mSteamWeb = steamweb; }
/// <summary> /// Fetches the Tf2 Item schema. /// </summary> /// <param name="apiKey">The API key.</param> /// <returns>A deserialized instance of the Item Schema.</returns> /// <remarks> /// The schema will be cached for future use if it is updated. /// </remarks> public static Schema FetchSchema(string apiKey, string schemaLang = null) { var url = SchemaApiUrlBase + apiKey; if (schemaLang != null) { url += "&format=json&language=" + schemaLang; } // just let one thread/proc do the initial check/possible update. bool wasCreated; var mre = new EventWaitHandle(false, EventResetMode.ManualReset, SchemaMutexName, out wasCreated); // the thread that create the wait handle will be the one to // write the cache file. The others will wait patiently. if (!wasCreated) { bool signaled = mre.WaitOne(10000); if (!signaled) { return(null); } } bool keepUpdating = true; SchemaResult schemaResult = new SchemaResult(); string tmpUrl = url; do { if (schemaResult.result != null) { tmpUrl = url + "&start=" + schemaResult.result.Next; } string result = new SteamWeb().Fetch(tmpUrl, "GET"); if (schemaResult.result == null || schemaResult.result.Items == null) { schemaResult = JsonConvert.DeserializeObject <SchemaResult>(result); } else { SchemaResult tempResult = JsonConvert.DeserializeObject <SchemaResult>(result); var items = schemaResult.result.Items.Concat(tempResult.result.Items); schemaResult.result.Items = items.ToArray(); schemaResult.result.Next = tempResult.result.Next; } if (schemaResult.result.Next <= schemaResult.result.Items.Count()) { keepUpdating = false; } } while (keepUpdating); //Get origin names string itemOriginUrl = SchemaApiItemOriginNamesUrlBase + apiKey; if (schemaLang != null) { itemOriginUrl += "&format=json&language=" + schemaLang; } string resp = new SteamWeb().Fetch(itemOriginUrl, "GET"); var itemOriginResult = JsonConvert.DeserializeObject <SchemaResult>(resp); schemaResult.result.OriginNames = itemOriginResult.result.OriginNames; // were done here. let others read. mre.Set(); DateTime schemaLastModified = DateTime.Now; return(schemaResult.result ?? null); }
public bool load(ulong appid, List <uint> types, SteamID steamid) { dynamic invResponse; Item tmpItemData; ItemDescription tmpDescription; loaded = false; try { for (int i = 0; i < types.Count; i++) { string response = SteamWeb.Fetch(string.Format("http://steamcommunity.com/profiles/{0}/inventory/json/{1}/{2}/?trading=1", steamid.ConvertToUInt64(), appid, types[i]), "GET", null, null, true); invResponse = JsonConvert.DeserializeObject(response); if (invResponse.success == false) { errors.Add("Fail to open backpack: " + invResponse.Error); return(false); } //rgInventory = Items on Steam Inventory foreach (var item in invResponse.rgInventory) { foreach (var itemId in item) { tmpItemData = new Item(); tmpItemData.id = itemId.id; tmpItemData.classid = itemId.classid; items.Add((ulong)itemId.id, tmpItemData); break; } } // rgDescriptions = Item Schema (sort of) foreach (var description in invResponse.rgDescriptions) { foreach (var classid_instanceid in description)// classid + '_' + instenceid { tmpDescription = new ItemDescription(); tmpDescription.name = classid_instanceid.name; tmpDescription.type = classid_instanceid.type; tmpDescription.marketable = (bool)classid_instanceid.marketable; tmpDescription.tradable = (bool)classid_instanceid.marketable; tmpDescription.metadata = classid_instanceid.descriptions; descriptions.Add((ulong)classid_instanceid.classid, tmpDescription); break; } } } //end for (inventory type) } //end try catch (Exception e) { Console.WriteLine(e.Message); errors.Add("Exception: " + e.Message); return(false); } loaded = true; return(true); }
/// <summary> /// Send the current trade offer. /// </summary> /// <param name="message">Message to send with trade offer.</param> /// <param name="token">Optional trade offer token.</param> /// <returns>-1 if response fails to deserialize (general error), 0 if no tradeofferid exists (Steam error), or the Trade Offer ID of the newly created trade offer.</returns> public ulong SendTrade(string message, string token = "") { var url = "https://steamcommunity.com/tradeoffer/new/send"; var referer = "http://steamcommunity.com/tradeoffer/new/?partner=" + partnerId.AccountID; var data = new NameValueCollection(); data.Add("sessionid", sessionId); data.Add("partner", partnerId.ConvertToUInt64().ToString()); data.Add("tradeoffermessage", message); data.Add("json_tradeoffer", JsonConvert.SerializeObject(this.tradeStatus)); data.Add("trade_offer_create_params", token == "" ? "{}" : "{\"trade_offer_access_token\":\"" + token + "\"}"); try { string result = ""; for (int i = 0; i < 10; i++) { try { var response = SteamWeb.Request(url, "POST", data, cookies, true, referer); using (System.IO.Stream responseStream = response.GetResponseStream()) { using (var reader = new System.IO.StreamReader(responseStream)) { result = reader.ReadToEnd(); if (string.IsNullOrEmpty(result)) { Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode); System.Threading.Thread.Sleep(1000); } else { break; } } } } catch (WebException ex) { try { int statusCode = 0; if (ex.Status == WebExceptionStatus.ProtocolError) { statusCode = (int)((HttpWebResponse)ex.Response).StatusCode; Console.WriteLine("Status Code: {0}, {1}", statusCode, ((HttpWebResponse)ex.Response).StatusDescription); } string errorMessage = new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd(); Console.WriteLine("Error: {0}", errorMessage); if (statusCode == 500 && errorMessage.Contains("There was an error sending your trade offer.")) { var errorJson = JsonConvert.DeserializeObject <dynamic>(errorMessage); if (errorJson.strError != null) { string errorString = errorJson.strError; int errorCode = Convert.ToInt32(errorString.Split(new char[] { '(', ')' })[1]); if (errorCode == 16 || errorCode == 11) { Console.WriteLine("Encountered Steam error code {0}, manually checking for completion...", errorCode); var tradeOfferList = tradeOffers.GetTradeOffers(); foreach (var tradeOffer in tradeOfferList) { if (tradeStatus.me.assets.Count == tradeOffer.ItemsToGive.Length && tradeStatus.them.assets.Count == tradeOffer.ItemsToReceive.Length) { foreach (var item in tradeOffer.ItemsToGive) { var asset = new TradeAsset(item.AppId, Convert.ToInt64(item.ContextId), item.AssetId.ToString(), item.Amount); if (!tradeStatus.me.assets.Contains(asset)) { Console.WriteLine("Could not validate that this trade offer was sent successfully. (1)"); return(0); } } foreach (var item in tradeOffer.ItemsToReceive) { var asset = new TradeAsset(item.AppId, Convert.ToInt64(item.ContextId), item.AssetId.ToString(), item.Amount); if (!tradeStatus.them.assets.Contains(asset)) { Console.WriteLine("Could not validate that this trade offer was sent successfully. (2)"); return(0); } } Console.WriteLine("Successfully validated!"); return(tradeOffer.Id); } } } else if (errorCode == 15) { throw new TradeOfferException(errorString, errorCode); } } } } catch { } } catch (Exception ex) { Console.WriteLine(ex); } } var jsonResponse = JsonConvert.DeserializeObject <dynamic>(result); try { return(Convert.ToUInt64(jsonResponse.tradeofferid)); } catch { return(0); } } catch { return(0); } }
public SteamMarketPrices() { steamWeb = new SteamWeb(); }