Esempio n. 1
0
 public ShowBackpack(Bot bot, SteamID SID)
 {
     InitializeComponent();
     this.bot = bot;
     this.SID = SID;
     this.Text = bot.SteamFriends.GetFriendPersonaName(SID) + "'s Backpack";
 }
Esempio n. 2
0
        public Trade(SteamID me, SteamID other, string sessionId, string token, string apiKey, Bot bot)
        {
            MeSID = me;
            OtherSID = other;

            this.sessionId = sessionId;
            steamLogin = token;
            this.apiKey = apiKey;
            this.bot = bot;

            // Moved here because when Poll is called below, these are
            // set to zero, which closes the trade immediately.
            MaximumTradeTime = bot.MaximumTradeTime;
            MaximumActionGap = bot.MaximiumActionGap;

            baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64 ());

            // try to poll for the first time
            try
            {
                Poll ();
            }
            catch (Exception)
            {
                bot.log.Error ("[TRADE] Failed To Connect to Steam!");

                if (OnError != null)
                    OnError("There was a problem connecting to Steam Trading.");
            }

            FetchInventories ();
        }
 // Todo: move the item-check after a failed trade to a separate method to clean up handler.
 public ReceivingUserHandler(Bot bot, SteamID sid, Configuration config)
     : base(bot, sid, config)
 {
     Success = false;
     mySteamID = Bot.SteamUser.SteamID;
     ReceivingSID = mySteamID;
 }
Esempio n. 4
0
        // This mode is to run a single Bot until it's terminated.
        private static void BotMode(int botIndex)
        {
            if (!File.Exists("settings.json"))
            {
                Console.WriteLine("No settings.json file found.");
                return;
            }

            Configuration configObject;
            try
            {
                configObject = Configuration.LoadConfiguration("settings.json");
            }
            catch (Newtonsoft.Json.JsonReaderException)
            {
                // handle basic json formatting screwups
                Console.WriteLine("settings.json file is corrupt or improperly formatted.");
                return;
            }

            if (botIndex >= configObject.Bots.Length)
            {
                Console.WriteLine("Invalid bot index.");
                return;
            }

            Bot b = new Bot(configObject.Bots[botIndex], configObject.ApiKey, BotManager.UserHandlerCreator, true, true);
            Console.Title = "Bot Manager";
            b.StartBot();

            string AuthSet = "auth";
            string ExecCommand = "exec";

            // this loop is needed to keep the botmode console alive.
            // instead of just sleeping, this loop will handle console input
            while (true)
            {
                string inputText = Console.ReadLine();

                if (String.IsNullOrEmpty(inputText))
                    continue;

                // Small parse for console input
                var c = inputText.Trim();

                var cs = c.Split(' ');

                if (cs.Length > 1)
                {
                    if (cs[0].Equals(AuthSet, StringComparison.CurrentCultureIgnoreCase))
                    {
                        b.AuthCode = cs[1].Trim();
                    }
                    else if (cs[0].Equals(ExecCommand, StringComparison.CurrentCultureIgnoreCase))
                    {
                        b.HandleBotCommand(c.Remove(0, cs[0].Length + 1));
                    }
                }
            }
        }
Esempio n. 5
0
        public ChatTab(Chat chat, Bot bot, ulong sid)
        {
            InitializeComponent();
            this.Chat = chat;
            this.sid = sid;
            this.bot = bot;
            this.steam_name.Text = bot.SteamFriends.GetFriendPersonaName(sid);
            this.steam_status.Text = bot.SteamFriends.GetFriendPersonaState(sid).ToString();
            this.chat_status.Text = "";
            SteamKit2.SteamID SteamID = sid;
            byte[] avatarHash = bot.SteamFriends.GetFriendAvatar(SteamID);
            bool validHash = avatarHash != null && !IsZeros(avatarHash);

            if ((AvatarHash == null && !validHash && avatarBox.Image != null) || (AvatarHash != null && AvatarHash.SequenceEqual(avatarHash)))
            {
                // avatar is already up to date, no operations necessary
            }
            else if (validHash)
            {
                AvatarHash = avatarHash;
                CDNCache.DownloadAvatar(SteamID, avatarHash, AvatarDownloaded);
            }
            else
            {
                AvatarHash = null;
                avatarBox.Image = ComposeAvatar(null);
            }
        }
Esempio n. 6
0
 public ShowBackpack(Bot bot, SteamID SID)
 {
     InitializeComponent();
     this.bot = bot;
     this.SID = SID;
     this.Text = bot.SteamFriends.GetFriendPersonaName(SID) + "'s Backpack";
     Util.LoadTheme(metroStyleManager1);
 }
Esempio n. 7
0
        public GivingUserHandler(Bot bot, SteamID sid, Configuration config)
            : base(bot, sid, config)
        {
            Success = false;

            //Just makes referencing the bot's own SID easier.
            mySteamID = Bot.SteamUser.SteamID;
        }
Esempio n. 8
0
 public Log(string logFile, Bot bot=null, LogLevel output=LogLevel.Success)
 {
     _FileStream = File.AppendText (logFile);
     _FileStream.AutoFlush = true;
     _Bot = bot;
     OutputToConsole = output;
     Console.ForegroundColor = DefaultConsoleColor;
 }
Esempio n. 9
0
 public ShowBackpack(Bot bot, SteamID SID)
 {
     InitializeComponent();
     this.bot = bot;
     this.SID = SID;
     this.Text = bot.SteamFriends.GetFriendPersonaName(SID) + "'s Backpack";
     Util.LoadTheme(this, this.Controls);
     this.Width = 1012;
 }
Esempio n. 10
0
 public SteamEPHandler(Bot bot, SteamID sid)
     : base(bot, sid)
 {
     messageResponses.Add ("hey", "Hello!|Howdy!|Oi!|Hey!|Hai!");
     messageResponses.Add ("hello", "Hello!|Howdy!|Oi!|Hey!|Hai!");
     messageResponses.Add ("help", "To use me, just send me a trade request and insert the items you want to give me!");
     messageResponses.Add ("!help", "To use me, just send me a trade request and insert the items you want to give me!");
     messageResponses.Add ("/help", "To use me, just send me a trade request and insert the items you want to give me!");
 }
Esempio n. 11
0
        /// <summary>
        /// A method to return an instance of the <c>bot.BotControlClass</c>.
        /// </summary>
        /// <param name="bot">The bot.</param>
        /// <param name="sid">The steamId.</param>
        /// <returns>A <see cref="UserHandler"/> instance.</returns>
        /// <exception cref="ArgumentException">Thrown if the control class type does not exist.</exception>
        public static UserHandler UserHandlerCreator(Bot bot, SteamID sid)
        {
            Type controlClass = Type.GetType(bot.BotControlClass);

            if (controlClass == null)
                throw new ArgumentException("Configured control class type was null. You probably named it wrong in your configuration file.", "bot");

            return (UserHandler)Activator.CreateInstance(
                controlClass, new object[] { bot, sid });
        }
 public UserHandler (Bot bot, SteamID sid)
 {
     Bot = bot;
     OtherSID = sid;
     MySID = bot.SteamUser.SteamID;
     if (MySID != OtherSID)
     {
         MyInventory = new GenericInventory(MySID, MySID);
         OtherInventory = new GenericInventory(OtherSID, MySID);
     }            
 }
Esempio n. 13
0
        public ShowTrade(Bot bot, string name)
        {
            InitializeComponent();
            Util.LoadTheme(metroStyleManager1);
            this.Text = "Trading with " + name;
            this.bot = bot;
            this.sid = bot.CurrentTrade.OtherSID;
            this.username = name;
            this.label_yourvalue.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
            this.label_othervalue.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
            column_otherofferings.Text = name + "'s Offerings:";
            ListInventory.ShowTrade = this;
            Thread checkExpired = new Thread(() =>
            {
                while (true)
                {
                    if (bot.CurrentTrade == null)
                    {
                        bot.main.Invoke((Action)(this.Close));
                        bot.log.Warn("Trade expired.");
                        if (Friends.chat_opened)
                        {
                            bot.main.Invoke((Action)(() =>
                            {
                                foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
                                {
                                    if (tab.Text == bot.SteamFriends.GetFriendPersonaName(sid))
                                    {
                                        tab.Invoke((Action)(() =>
                                        {
                                            foreach (var item in tab.Controls)
                                            {
                                                Friends.chat.chatTab = (ChatTab)item;
                                            }
                                            string result = "The trade session has closed.";
                                            bot.log.Warn(result);
                                            string date = "[" + DateTime.Now + "] ";
                                            Friends.chat.chatTab.UpdateChat("[" + DateTime.Now + "] " + result + "\r\n", false);
                                            ChatTab.AppendLog(sid, "===========[TRADE ENDED]===========\r\n");
                                        }));
                                        break; ;
                                    }
                                }

                            }));
                        }
                        break;
                    }
                }
            });
            checkExpired.Start();
        }
Esempio n. 14
0
        public ChatTab(Chat chat, Bot bot, ulong sid)
        {
            InitializeComponent();
            this.Chat = chat;
            this.userSteamId = sid;
            this.bot = bot;
            this.StyleManager.OnThemeChanged += metroStyleManager1_OnThemeChanged;
            this.StyleManager.Theme = Friends.GlobalStyleManager.Theme;
            this.StyleManager.Style = Friends.GlobalStyleManager.Style;
            Util.LoadTheme(null, this.Controls, this);
            this.Theme = Friends.GlobalStyleManager.Theme;
            this.StyleManager.Style = Friends.GlobalStyleManager.Style;
            metroStyleManager1_OnThemeChanged(null, EventArgs.Empty);
            try
            {
                this.steam_name.Text = prevName = bot.SteamFriends.GetFriendPersonaName(sid);
                this.steam_status.Text = prevStatus = bot.SteamFriends.GetFriendPersonaState(sid).ToString();
            }
            catch
            {

            }
            this.chat_status.Text = "";
            SteamKit2.SteamID SteamID = sid;
            try
            {
                byte[] avatarHash = bot.SteamFriends.GetFriendAvatar(SteamID);
                bool validHash = avatarHash != null && !IsZeros(avatarHash);

                if ((AvatarHash == null && !validHash && avatarBox.Image != null) || (AvatarHash != null && AvatarHash.SequenceEqual(avatarHash)))
                {
                    // avatar is already up to date, no operations necessary
                }
                else if (validHash)
                {
                    AvatarHash = avatarHash;
                    CDNCache.DownloadAvatar(SteamID, avatarHash, AvatarDownloaded);
                }
                else
                {
                    AvatarHash = null;
                    avatarBox.Image = ComposeAvatar(null);
                }
            }
            catch
            {

            }
            new System.Threading.Thread(GetChatLog).Start();
            status_update.RunWorkerAsync();
            text_input.Focus();
        }
Esempio n. 15
0
 public static void assignRequest(Bot bot)
 {
     new Thread(() =>
         {
             while (true)
             {
                 if (getItem().User!=null)
                 {
                     bot.DoRequest(getItem());
                     break;
                 }
                 Thread.Sleep(5000);
             }
         }).Start();
 }
Esempio n. 16
0
        public static void CraftItems(Bot bot, short recipe, params ulong[] items)
        {
            if (bot.CurrentGame != 440)
                throw new Exception("SteamBot is not ingame with AppID 440; current AppID is " + bot.CurrentGame);

            var craftMsg = new ClientGCMsg<MsgCraft>();

            craftMsg.Body.NumItems = (short)items.Length;
            craftMsg.Body.Recipe = recipe;

            foreach (ulong id in items)
                craftMsg.Write(id);

            bot.SteamGameCoordinator.Send(craftMsg, 440);
        }
Esempio n. 17
0
        public ShowTrade(Bot bot, string name)
        {
            InitializeComponent();
            this.Text = "Trading with " + name;
            this.bot = bot;
            this.sid = bot.CurrentTrade.OtherSID;
            this.username = name;
            column_otherofferings.Text = name + "'s Offerings:";
            ListInventory.ShowTrade = this;
            Thread checkExpired = new Thread(() =>
            {
                while (true)
                {
                    if (bot.CurrentTrade == null)
                    {
                        bot.main.Invoke((Action)(this.Dispose));
                        bot.log.Warn("Trade expired.");
                        if (Friends.chat_opened)
                        {
                            bot.main.Invoke((Action)(() =>
                            {
                                foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
                                {
                                    if (tab.Text == bot.SteamFriends.GetFriendPersonaName(sid))
                                    {
                                        tab.Invoke((Action)(() =>
                                        {
                                            foreach (var item in tab.Controls)
                                            {
                                                Friends.chat.chatTab = (ChatTab)item;
                                            }
                                            string result = "The trade session has closed.";
                                            bot.log.Warn(result);
                                            Friends.chat.chatTab.UpdateChat("[" + DateTime.Now + "] " + result + "\r\n");
                                        }));
                                        break; ;
                                    }
                                }

                            }));
                        }
                        break;
                    }
                }
            });
            checkExpired.Start();
        }
 /// <summary>
 /// <para>Add ban for user</para>
 /// <para></para>
 /// <para>Example : ban.Addban(Bot, OtherSID, true); -> Add ban to user + block user's Steam profile</para>
 /// <para>Example : ban.Addban(Bot, OtherSID, false); -> Add ban to user ONLY</para>
 /// </summary>
 /// <returns><c>true</c>, if ban was added, <c>false</c> otherwise.</returns>
 /// <param name="bot">Bot.</param>
 /// <param name="steam64">Steam64.</param>
 /// <param name="banProfile">If set to <c>true</c> ban user Steam's profile.</param>
 public bool AddBan(Bot bot, ulong steam64, bool banProfile)
 {
     if (FileExist()) {
         if (!IsBanned(steam64)) { // if does not exist in ban list
             XDocument doc = XDocument.Load(fileName);
             XElement service = doc.Element("bannedIDs");
             service.Add(new XElement ("steamID", steam64.ToString()));
             if (banProfile) {
                 bot.SteamFriends.IgnoreFriend(steam64, true);
             }
             WriteLog(TAG + "[AddBan] : Successful - " + steam64.ToString());
             doc.Save(fileName);
         }
     } else {
         AddBan(bot, steam64, banProfile);
     }
     return true;
 }
Esempio n. 19
0
        public BackpackExpander(Bot bot, SteamKit2.SteamID id)
            : base(bot, id)
        {
            this.steamID = this.Bot.SteamClient.SteamID;

            lock (BackpackExpander.lockingVar)
            {
                if (BackpackExpander.groupManager == null)
                    BackpackExpander.groupManager = new GroupManager(this.Bot.apiKey);

                // Add the bot to its group
                // TODO: use a different data structure to enable a sorted list
                BackpackExpander.groupManager.AddMember(this.steamID, this.groupID);
            }

            // Wait for own group to be complete, so we really add all group members to friends
            //while (!BackpackExpander.groupManager.GroupComplete(this.groupID)) ;

            // Add all group members to friendslist (also accepts pending invites of group members)
            AddGroupFriends();
        }
Esempio n. 20
0
        public UserHandler(Bot bot, SteamID sid, Configuration config)
        {
            Bot = bot;
            OtherSID = sid;
            if (Settings == null)
            {
                BotMode = config.BotMode;
                NumberOfBots = config.TotalBots;

                AutoCraftWeps = config.Options.AutoCraftWeapons;
                ManageCrates = config.Options.ManageCrates;
                DeleteCrates = config.Options.DeleteCrates;
                TransferCrates = config.Options.TransferCrates;
                ExcludedCrates = config.Options.SavedCrates;

                CrateUHIsRunning = config.HasCrateUHLoaded;
                MainUHIsRunning = config.HasMainUHLoaded;

                Settings = config;
            }
        }
Esempio n. 21
0
 public static void SmeltRefined(Bot bot)
 {
     List<ulong> refs = new List<ulong>();
     bot.GetInventory();
     Inventory.Item[] items = bot.MyInventory.Items;
     for (int i = 0; i < items.Length; i++)
     {
         Inventory.Item item = items[i];
         if (refs.Count == 1)
         {
             break;
         }
         if (item.Defindex == 5002 && !refs.Contains(item.Id))
         {
             refs.Add(item.Id);
         }
     }
     if (refs.Count == 1)
     {
         Crafting.CraftItems(bot, ECraftingRecipe.SmeltRefined, refs.ToArray());
     }
 }
Esempio n. 22
0
 public static void CraftReclaimed(Bot bot)
 {
     List<ulong> scraps = new List<ulong>();
     bot.GetInventory();
     Inventory.Item[] items = bot.MyInventory.Items;
     for (int i = 0; i < items.Length; i++)
     {
         Inventory.Item item = items[i];
         if (scraps.Count == 3)
         {
             break;
         }
         if (item.Defindex == 5000 && !scraps.Contains(item.Id))
         {
             scraps.Add(item.Id);
         }
     }
     if (scraps.Count == 3)
     {
         Crafting.CraftItems(bot, ECraftingRecipe.CombineScrap, scraps.ToArray());
     }
 }
Esempio n. 23
0
        static void Main(string[] args)
        {
            var SteamWebClient = new SteamWebClient();

            var bots = new BotCredentials[]
            {
                new BotCredentials() { Username = "******", Password = "******" }
            };

            var schemaCache = new ItemsSchema(SteamWebClient, STEAM_WEB_KEY);
            var schemas = schemaCache.LookupSchemas();
            schemaCache.Load(schemas);

            foreach(var botInfo in bots)
            {
                var bot = new Bot(Logger, schemaCache, botInfo);
                bot.Admins.Add(new SteamID(00000000000000000));

                bot.OnWebLoggedOn += (b) =>
                {
                    b.SteamFriends.SetPersonaName("SteamBot");
                    b.SteamFriends.SetPersonaState(EPersonaState.Online);
                };

                bot.Initialize(useUDP: true);
                bot.Connect();

                while (bot.IsRunning)
                {
                    bot.Update();
                    bot.UpdateIdlerBots();
                    Thread.Sleep(1);
                }

                Logger.WriteLine("Bot is shutting down");

                bot.Shutdown();
            }
        }
Esempio n. 24
0
 public void AddData(Bot bot, double refs, int trades)
 {
     StoreName(bot);
     if (File.Exists(fileName))
     {
         XDocument doc = XDocument.Load(fileName);
         XElement service = new XElement(bot.DisplayName);
         service.ReplaceNodes("trades", trades.ToString());
         doc.Save(fileName);
     }
     else if (File.Exists(fileName))
     {
         XDocument doc = XDocument.Load(fileName);
         XElement service = new XElement(bot.DisplayName);
         service.ReplaceNodes("refs", refs.ToString());
         doc.Save(fileName);
     }
     else
     {
         CreateFile();
         if (File.Exists(fileName))
         {
             XDocument doc = XDocument.Load(fileName);
             XElement service = new XElement(bot.DisplayName);
             service.Add(new XElement("trades", trades.ToString()));
             doc.Save(fileName);
         }
         if (File.Exists(fileName))
         {
             XDocument doc = XDocument.Load(fileName);
             XElement service = new XElement(bot.DisplayName);
             service.Add(new XElement("refs", refs.ToString()));
             doc.Save(fileName);
         }
     }
 }
Esempio n. 25
0
 public UserHandler(Bot bot, SteamID sid)
 {
     Bot = bot;
     OtherSID = sid;
     GetOtherInventory();
 }
            private void SpawnBotThread(Configuration.BotInfo botConfig)
            {
                // the bot object itself is threaded so we just build it and start it.
                Bot b = new Bot(botConfig,
                                config.ApiKey,
                                UserHandlerCreator,
                                true);

                TheBot = b;
                TheBot.StartBot();
            }
Esempio n. 27
0
 public UserHandler(Bot bot, SteamID sid)
 {
     Bot      = bot;
     OtherSID = sid;
 }
 /// <summary>
 /// <para>Remove ban from user</para>
 /// <para></para>
 /// <para>Example : ban.RemoveBan(Bot, OtherSID, true); -> Unban user + unblock user's Steam profile</para>
 /// <para>Example : ban.RemoveBan(Bot, OtherSID, false); -> Unban user ONLY</para>
 /// </summary>
 /// <returns><c>true</c>, if ban was removed, <c>false</c> otherwise.</returns>
 /// <param name="bot">Bot.</param>
 /// <param name="steam64">Steam64.</param>
 /// <param name="unbanProfile">If set to <c>true</c> unban user Steam's profile.</param>
 public bool RemoveBan(Bot bot, ulong steam64, bool unbanProfile)
 {
     if (FileExist()) {
         XDocument bannedIDs = XDocument.Load(fileName);
         if (bannedIDs.Element("bannedIDs").Elements("steamID").Any()) {
             foreach (var steamid in bannedIDs.Element("bannedIDs").Elements("steamID")) {
                 if (steamid.Value.ToString().Equals(steam64.ToString())) {
                     bannedIDs.Element("bannedIDs")
                 .Elements("steamID")
                 .Where(x => x.Value == steam64.ToString())
                 .Remove();
                     if (unbanProfile) {
                         bot.SteamFriends.IgnoreFriend(steam64, false);
                     }
                     WriteLog(TAG + "[RemoveBan] : Successful - " + steam64.ToString());
                 }
             }
         }
         bannedIDs.Save(fileName);
     }
     return true;
 }
Esempio n. 29
0
		public void checkTradeStatuses()
		{
			string password = System.IO.File.ReadAllText(@"../cstrade_admin_password.txt");
			foreach(KeyValuePair<int, TradeStatus> trade in tradeStatuses)
			{
				if(trade.Value.state == TradeOfferState.TradeOfferStateCanceled
					|| trade.Value.state == TradeOfferState.TradeOfferStateCountered
					|| trade.Value.state == TradeOfferState.TradeOfferStateDeclined
					|| trade.Value.state == TradeOfferState.TradeOfferStateExpired
					|| trade.Value.state == TradeOfferState.TradeOfferStateInvalid
					|| trade.Value.state == TradeOfferState.TradeOfferStateInvalidItems
					|| trade.Value.state == TradeOfferState.TradeOfferStateCanceledBySecondFactor
					|| trade.Value.itemsPushed == true)
				{
				}
				else
				{
					TradeOffer tradeOfferData;
					bool traderequest = Bot.TryGetTradeOffer(trade.Value.steam_trade_id, out tradeOfferData);
					if(traderequest)
					{
						if (trade.Value.state != tradeOfferData.OfferState) 
						{
							Log.Info ("Trade " + trade.Value.steam_trade_id + "/" + trade.Value.server_trade_id + " has status of " + tradeOfferData.OfferState + "/" + (int)tradeOfferData.OfferState);
							trade.Value.state = tradeOfferData.OfferState;
						} else 
						{
							continue; //go to next trade because state hasnt changed...
						}

						List<long> itemids = new List<long>();
						if(trade.Value.trade_type.Equals("d", StringComparison.Ordinal) ||
						   trade.Value.trade_type.Equals("t", StringComparison.Ordinal) )
						{
							if(tradeOfferData.OfferState == TradeOfferState.TradeOfferStateAccepted)
							{
								for (int attempts = 0;; attempts++) 
								{
									try 
									{
										string tradeReceipt = Bot.SteamWeb.Fetch("http://steamcommunity.com/trade/"+tradeOfferData.TradeID+"/receipt/", "GET", null, false);

										string start = "oItem = ";
										string end = ";";
										string input = tradeReceipt;

										Regex r = new Regex("(?<="+start+")" + "(.*?)" + "(?="+end+")");
										MatchCollection matches = r.Matches(input);
										foreach (Match match in matches) 
										{
											string itemJSON;
											itemJSON = match.Value.Split(',')[0] + "}"; //Strips everything past the id to prevent any issues
											dynamic itemJsonified = JsonConvert.DeserializeObject (itemJSON);
											string itemID = itemJsonified.id;
											long id = Convert.ToInt64 (itemID);
											itemids.Add(id);
										}
										break;
									} catch (Exception e) {
										Log.Error (e.Message);
										if (attempts > 4)
											throw e;
									}
								}
							}
						}
						else if(trade.Value.trade_type.Equals("w", StringComparison.Ordinal))
						{
							if(tradeOfferData.OfferState == TradeOfferState.TradeOfferStateNeedsConfirmation)
							{
								Bot.AcceptAllMobileTradeConfirmations();
							}
						}

						string postData = "password="******"&trade_id=" + trade.Value.server_trade_id;
						postData += "&steam_trade_id=" + trade.Value.steam_trade_id;
						postData += "&trade_status=" + (int)tradeOfferData.OfferState;
						postData += "&user_steam_id=" + trade.Value.steam_user_id;
						postData += "&bot_steam_id=" + Bot.SteamUser.SteamID.ConvertToUInt64();
						postData += "&trade_asset_ids=" + JsonConvert.SerializeObject(itemids);
						postData += "&trade_type=" + trade.Value.trade_type;

						string url = "http://skinbonanza.com/backend/update_trade.php";
						var updaterequest = (HttpWebRequest)WebRequest.Create (url);

						var data = Encoding.ASCII.GetBytes (postData);

						updaterequest.Method = "POST";
						updaterequest.ContentType = "application/x-www-form-urlencoded";
						updaterequest.ContentLength = data.Length;

						using (var stream = updaterequest.GetRequestStream ()) {
							stream.Write (data, 0, data.Length);
						}

						for (int attempts = 0;; attempts++) 
						{
							try 
							{
								var response = (HttpWebResponse)updaterequest.GetResponse ();
								var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
								if(responseString.Contains("success"))
								{
									Log.Success("Trade " + trade.Value.steam_trade_id + "/" + trade.Value.server_trade_id + " status updated.");
								}
								if(trade.Value.trade_type.Equals("d", StringComparison.Ordinal))
								{
									if(responseString.Contains("itemspushed"))
									{
										trade.Value.itemsPushed = true;
										Log.Success("Trade items successfully added to user account");
									}
								}
								else if(responseString.Contains("completed"))
								{
									trade.Value.itemsPushed = true;
								}
								break;
							} catch (Exception e) {
								Log.Error (e.Message);
								if (attempts > 4)
									throw e;
							}
						}
					}
					else
					{
						Log.Warn("Trade offer state request failed.");
					}
				}
			}
		}
Esempio n. 30
0
 public SimpleUserHandler(Bot bot, SteamID sid) : base(bot, sid)
 {
 }
Esempio n. 31
0
        public void AddItems()
        {
            Log.Info("Getting Inventory");
            Bot.GetInventory();

            var AllItems = new List <Inventory.Item>();

            if (OtherSID == CrateSID)
            {
                if (ManageCrates)
                {
                    AllItems = GetCrates(Bot.MyInventory, TransferCrates);
                }
                else
                {
                    return;
                }
            }
            else if (OtherSID == MainSID)
            {
                AllItems = GetTradeItems(Bot.MyInventory, TransferCrates);
            }
            else
            {
                return;
            }

            Log.Debug("Adding items");
            uint added = AddItemsFromList(AllItems);

            if (added > 0 || AllItems.Count == 0)
            {
                Log.Info("Added " + added + " items.");
                System.Threading.Thread.Sleep(50);
                MeAdded = true;
                if (!SendMessage("ready"))
                {
                    CancelTrade();
                    OnTradeClose();
                }
            }
            else
            {
                Log.Debug("Something's gone wrong.");
                Bot.GetInventory();
                int ItemsLeft = 0;

                if (ManageCrates)
                {
                    ItemsLeft = GetTradeItems(Bot.MyInventory, TransferCrates).Count;
                }
                else
                {
                    ItemsLeft = GetTradeItems(Bot.MyInventory, 0).Count;
                }

                if (ItemsLeft > 0)
                {
                    Log.Debug("Still have items to trade, aborting trade.");
                    //errorOcccured = true;
                    CancelTrade();
                    OnTradeClose();
                }
                else
                {
                    Log.Debug("No items in bot inventory. This shouldn't be possible.");
                    TradeReadyBots.Remove(mySteamID);
                    CancelTrade();

                    Log.Warn("[Receiving] TRADE CLOSED");
                    Bot.CloseTrade();
                    Bot.StopBot();
                }
            }
        }
Esempio n. 32
0
 public TradeOfferUserHandler(Bot bot, SteamID sid) : base(bot, sid)
 {
 }
Esempio n. 33
0
 public HelperbotUserHandler(Bot bot, SteamID sid) : base(bot, sid)
 {
 }
Esempio n. 34
0
 public SimpleUserHandler(Bot bot, SteamID sid)
     : base(bot, sid)
 {
 }
Esempio n. 35
0
 public AdminUserHandler(Bot bot, SteamID sid) : base(bot, sid)
 {
 }
Esempio n. 36
0
 public ItemTransferHandler(Bot bot, SteamID sid)
     : base(bot, sid)
 {
     this.myOffers = new List<Inventory.Item>();
 }
Esempio n. 37
0
 // Todo: move the item-check after a failed trade to a separate method to clean up handler.
 public ReceivingUserHandler(Bot bot, SteamID sid, Configuration config) : base(bot, sid, config)
 {
     Success      = false;
     mySteamID    = Bot.SteamUser.SteamID;
     ReceivingSID = mySteamID;
 }
 public UserHandler(Bot bot, SteamID sid)
 {
     Bot = bot;
     OtherSID = sid;
     TradeOffers = bot.TradeOffers;
 }
Esempio n. 39
0
		private void checkForTrades()
		{
			string password = System.IO.File.ReadAllText(@"../cstrade_admin_password.txt");

			TradeList data;
			string getUrl = "http://skinbonanza.com/backend/get_items.php";
			var getRequest = (HttpWebRequest)WebRequest.Create (getUrl);

			string getData = "password="******"&bot_steam_id=" + Bot.SteamUser.SteamID.ConvertToUInt64();
			var getData_encoded = Encoding.ASCII.GetBytes (getData);

			getRequest.Method = "POST";
			getRequest.ContentType = "application/x-www-form-urlencoded";
			getRequest.ContentLength = getData_encoded.Length;

			using (var stream = getRequest.GetRequestStream ()) {
				stream.Write (getData_encoded, 0, getData_encoded.Length);
			}

			for(int attempts = 0;;attempts++)
			{
				try
				{
					var getResponse = (HttpWebResponse)getRequest.GetResponse (); //THIS LINE/AREA IS CAUSING A LOT OF ISSUES... TRY CATCH NEEDED
					string getString = new StreamReader (getResponse.GetResponseStream()).ReadToEnd();
					if (debug_output) {
						Log.Info(getString + "");
					}
					data = JsonConvert.DeserializeObject<TradeList> (getString);
					break;
				}
				catch (Exception e)
				{
					getRequest.Abort ();
					Log.Error (e.Message);
					if(attempts > 4)
						throw e;
				}
			}

			//Prevent valid trades from being cancelled because they dont exist in tradeStatuses yet
			foreach(TradeData trade in data.trades)
			{
				bool tradeValue;
				if(tradesDone.TryGetValue(trade.tradeid, out tradeValue))
				{
					//Log.Info("Trade " + trade.tradeid + " already made");
				}
				else if(trade.status == 2 || trade.status == 9 || trade.status == 11)
				{
					//Trade not in update list, bot must have restarted, add now
					Log.Info("Incomplete Trade Missing with tradeID: " + trade.tradeid);
					tradesDone[trade.tradeid] = true;
					tradeStatuses[trade.tradeid] = new TradeStatus(trade.user.steamid, trade.steamid, trade.tradeid, trade.type);						
				}
			}

			foreach(TradeData trade in data.trades)
			{
				bool tradeValue;
				if(tradesDone.TryGetValue(trade.tradeid, out tradeValue))
				{
					//Log.Info("Trade " + trade.tradeid + " already made");
				}
				else
				{
					Log.Info("Trade " + trade.tradeid + " not completed... Attempting");

					TradeUser user = trade.user;

					var tradeOffer = Bot.NewTradeOffer(new SteamID(user.steamid));
					int count = 0;
					foreach(long item in trade.items)
					{
						Log.Info("Adding Item with AssetID: " + item + " to Trade");
						if(trade.type.Equals("d", StringComparison.Ordinal) || 
						   trade.type.Equals("t", StringComparison.Ordinal))
						{
							tradeOffer.Items.AddTheirItem(730, 2, item);
						}
						else if(trade.type.Equals("w", StringComparison.Ordinal))
						{
							tradeOffer.Items.AddMyItem(730, 2, item);
						}
						count++;
					}
					if(trade.type.Equals("d", StringComparison.Ordinal) || 
					   trade.type.Equals("t", StringComparison.Ordinal))
					{
						Log.Info("Deposit/MultiTrade: " + count + " items being traded from user " + user.steamid);
					}
					else if(trade.type.Equals("w", StringComparison.Ordinal))
					{
						Log.Info("Withdrawal: " + count + " items being traded to user " + user.steamid);
					}


					if (tradeOffer.Items.NewVersion == null) {
						Log.Error ("TradeOffer is appearing as NULL, restarting the bot may fix?");
					}
					if (tradeOffer.Items.NewVersion)
					{
						string tradeID = "";
						string tradeError = "";
						bool sent = tradeOffer.SendWithToken(out tradeID, out tradeError, trade.user.token, "Secure Code: " + trade.code);

						if(sent)
						{
							Log.Success("New TradeID: " + tradeID);
							tradesDone[trade.tradeid] = true;
							//Add trade to list of trades to check status of (accepted, declined, etc)
							tradeStatuses[trade.tradeid] = new TradeStatus(user.steamid, tradeID, trade.tradeid, trade.type);

							string setTradeIDData = "password="******"&trade_id=" + trade.tradeid;
							setTradeIDData += "&trade_steam_id=" + tradeID;

							string url = "http://skinbonanza.com/backend/update_trade.php";
							var updaterequest = (HttpWebRequest)WebRequest.Create (url);

							var setTradeID_data = Encoding.ASCII.GetBytes (setTradeIDData);

							updaterequest.Method = "POST";
							updaterequest.ContentType = "application/x-www-form-urlencoded";
							updaterequest.ContentLength = setTradeID_data.Length;

							using (var stream = updaterequest.GetRequestStream ()) {
								stream.Write (setTradeID_data, 0, setTradeID_data.Length);
							}

							for(int attempts = 0;;attempts++)
							{
								try
								{
									var response = (HttpWebResponse)updaterequest.GetResponse ();
									var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
									if(responseString.Contains("success"))
									{
										Log.Info("Steam TradeID set in update_trade.");
									}
									break;
								}
								catch (Exception e)
								{
									Log.Error (e.Message);
									if(attempts > 4)
										throw e;
								}
							}
						}
						else
						{
							int statusID = 12;
							if (!String.IsNullOrEmpty (tradeError)) {
								if (tradeError.Contains ("JSonException")) {
									Log.Error ("Trade may have been sent, but a JSON conversion error occurred");
									statusID = 14;
								} else if (tradeError.Contains ("ResponseEmpty")) {
									Log.Error ("The request was sent, but Steam returned an empty response");
									statusID = 15;
								} else if (tradeError.Contains ("(26)")) {
									Log.Error ("The trade contains an invalid trade item");
									statusID = 16;
								} else if (tradeError.Contains ("(15)")) {
									Log.Error ("The trade url for the user is invalid");
									statusID = 17;
								} else if (tradeError.Contains ("(50)")) {
									Log.Error ("Too many concurrent trade offers sent (5 max)");
									statusID = 18;
								} else {
									Log.Error ("Error: {0}", tradeError);
								}
							} else {
								Log.Error ("Trade not sent and trade error is null/empty!");
							}

							int knownActiveTradesCount = 0;
							foreach(KeyValuePair<int, TradeStatus> knowntrade in tradeStatuses)
							{
								if(knowntrade.Value.state == TradeOfferState.TradeOfferStateCanceled
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateCountered
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateDeclined
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateExpired
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateInvalid
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateInvalidItems
									|| knowntrade.Value.state == TradeOfferState.TradeOfferStateCanceledBySecondFactor
									|| knowntrade.Value.itemsPushed == true)
								{
								}
								else
								{
									knownActiveTradesCount++;
								}
							}

							OffersResponse offersresponse = Bot.tradeOfferManager.webApi.GetActiveTradeOffers(true, false, false);
							List<Offer> activeTrades = offersresponse.TradeOffersSent;
							bool unmatched = false;
							if(activeTrades.Count != knownActiveTradesCount)
							{
								foreach(Offer offer in activeTrades)
								{
									//GetActiveOffers still gets cancelled and declined trades
									//so check that the trade is actually active
									if(offer.TradeOfferState == TradeOfferState.TradeOfferStateActive
										|| offer.TradeOfferState == TradeOfferState.TradeOfferStateNeedsConfirmation
										|| offer.TradeOfferState == TradeOfferState.TradeOfferStateInEscrow)
									{
										foreach(KeyValuePair<int, TradeStatus> checkTrade in tradeStatuses)
										{
											if(checkTrade.Value.state == TradeOfferState.TradeOfferStateCanceled
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateCountered
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateDeclined
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateExpired
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateInvalid
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateInvalidItems
												|| checkTrade.Value.state == TradeOfferState.TradeOfferStateCanceledBySecondFactor
												|| checkTrade.Value.itemsPushed == true)
											{
											}
											else
											{
												if(checkTrade.Value.steam_trade_id == offer.TradeOfferId)
												{
													//matching trade found
													continue;
												}
											}
										}

										//no matching trade found
										//trade not being tracked
										unmatched = true;
										Log.Error("Untracked trade found {0}, cancelling it", offer.TradeOfferId);
										Bot.tradeOfferManager.session.Cancel(offer.TradeOfferId);
									}
								}
							}
							if(!unmatched)
								Log.Success("No non-tracked trades found.");

							string postData = "password="******"&trade_id=" + trade.tradeid;
							postData += "&trade_status=" + statusID;
							postData += "&user_steam_id=" + user.steamid;
							postData += "&bot_steam_id=" + Bot.SteamUser.SteamID.ConvertToUInt64();

							string url = "http://skinbonanza.com/backend/update_trade.php";
							var updaterequest = (HttpWebRequest)WebRequest.Create (url);

							var failedTrade_data = Encoding.ASCII.GetBytes (postData);

							updaterequest.Method = "POST";
							updaterequest.ContentType = "application/x-www-form-urlencoded";
							updaterequest.ContentLength = failedTrade_data.Length;

							using (var stream = updaterequest.GetRequestStream ()) {
								stream.Write (failedTrade_data, 0, failedTrade_data.Length);
							}

							for (int attempts = 0;; attempts++) 
							{
								try 
								{
									var response = (HttpWebResponse)updaterequest.GetResponse ();
									var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
									if (responseString.Contains ("success")) {
										Log.Success ("Trade status updated.");
									}
									break;
								} catch (Exception e) {
									Log.Error (e.Message);
									if (attempts > 4)
										throw e;
								}
							}
						}
					}
					else
					{
						Log.Error("Old version of trade. Cancelling.");

						string postData = "password="******"&trade_id=" + trade.tradeid;
						postData += "&trade_status=" + 6;
						postData += "&user_steam_id=" + user.steamid;
						postData += "&bot_steam_id=" + Bot.SteamUser.SteamID.ConvertToUInt64();

						string url = "http://skinbonanza.com/backend/update_trade.php";
						var updaterequest = (HttpWebRequest)WebRequest.Create (url);

						var failedTrade_data = Encoding.ASCII.GetBytes (postData);

						updaterequest.Method = "POST";
						updaterequest.ContentType = "application/x-www-form-urlencoded";
						updaterequest.ContentLength = failedTrade_data.Length;

						using (var stream = updaterequest.GetRequestStream ()) {
							stream.Write (failedTrade_data, 0, failedTrade_data.Length);
						}

						for (int attempts = 0;; attempts++) 
						{
							try 
							{
								var response = (HttpWebResponse)updaterequest.GetResponse ();
								var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
								if (responseString.Contains ("success")) {
									Log.Success ("Trade status updated.");
								}
								break;
							} catch (Exception e) {
								Log.Error (e.Message);
								if (attempts > 4)
									throw e;
							}
						}
					}
				}
			}
			//https://steamcommunity.com/tradeoffer/new/?partner=81920318&token=od9DZwUG
		}