Error() публичный Метод

public Error ( string data ) : void
data string
Результат void
Пример #1
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());

            #region Login
            msg.Handle <SteamClient.ConnectedCallback> (callback =>
            {
                log.Debug("Connection Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    log.Error("Failed to connect to Steam Community, trying again...");
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoggedOnCallback> (callback =>
            {
                log.Debug("Logged On Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    MyLoginKey = callback.WebAPIUserNonce;
                }
                else
                {
                    log.Error("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command.");

                    // try to get the steamguard auth code from the event callback
                    var eva = new SteamGuardRequiredEventArgs();
                    FireOnSteamGuardRequired(eva);
                    if (!String.IsNullOrEmpty(eva.SteamGuard))
                    {
                        logOnDetails.AuthCode = eva.SteamGuard;
                    }
                    else
                    {
                        logOnDetails.AuthCode = Console.ReadLine();
                    }
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);

                    if (authd)
                    {
                        log.Success("User Authenticated!");

                        tradeManager = new TradeManager(apiKey, sessionId, token);
                        tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                        tradeManager.OnTimeout += OnTradeTimeout;
                        break;
                    }
                    else
                    {
                        log.Warn("Authentication failed, retrying in 2s...");
                        Thread.Sleep(2000);
                    }
                }

                if (Trade.CurrentSchema == null)
                {
                    log.Info("Downloading Schema...");
                    Trade.CurrentSchema = Schema.FetchSchema(apiKey);
                    log.Success("Schema Downloaded!");
                }

                SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName);
                SteamFriends.SetPersonaState(EPersonaState.Online);

                log.Success("Steam Bot Logged In Completely!");

                IsLoggedIn = true;

                GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
            });

            // handle a special JobCallback differently than the others
            if (msg.IsType <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >())
            {
                msg.Handle <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >(
                    jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID)
                    );
            }
            #endregion

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (friend.SteamID.AccountType == EAccountType.Clan)
                    {
                        if (!groups.Contains(friend.SteamID))
                        {
                            groups.Add(friend.SteamID);
                            if (friend.Relationship == EFriendRelationship.RequestRecipient)
                            {
                                if (GetUserHandler(friend.SteamID).OnGroupAdd())
                                {
                                    AcceptGroupInvite(friend.SteamID);
                                }
                                else
                                {
                                    DeclineGroupInvite(friend.SteamID);
                                }
                            }
                        }
                        else
                        {
                            if (friend.Relationship == EFriendRelationship.None)
                            {
                                groups.Remove(friend.SteamID);
                            }
                        }
                    }
                    else if (friend.SteamID.AccountType != EAccountType.Clan)
                    {
                        if (!friends.Contains(friend.SteamID))
                        {
                            friends.Add(friend.SteamID);
                            if (friend.Relationship == EFriendRelationship.RequestRecipient &&
                                GetUserHandler(friend.SteamID).OnFriendAdd())
                            {
                                SteamFriends.AddFriend(friend.SteamID);
                            }
                        }
                        else
                        {
                            if (friend.Relationship == EFriendRelationship.None)
                            {
                                friends.Remove(friend.SteamID);
                                GetUserHandler(friend.SteamID).OnFriendRemove();
                            }
                        }
                    }
                }
            });


            msg.Handle <SteamFriends.FriendMsgCallback> (callback =>
            {
                EChatEntryType type = callback.EntryType;

                if (callback.EntryType == EChatEntryType.ChatMsg)
                {
                    log.Info(String.Format("Chat Message from {0}: {1}",
                                           SteamFriends.GetFriendPersonaName(callback.Sender),
                                           callback.Message
                                           ));
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });
            #endregion

            #region Group Chat
            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
            });
            #endregion

            #region Trading
            msg.Handle <SteamTrading.SessionStartCallback> (callback =>
            {
                bool started = HandleTradeSessionStart(callback.OtherClient);

                if (!started)
                {
                    log.Error("Could not start the trade session.");
                }
                else
                {
                    log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
                }
            });

            msg.Handle <SteamTrading.TradeProposedCallback> (callback =>
            {
                try
                {
                    tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
                }
                catch (WebException we)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade error: " + we.Message);

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }
                catch (Exception)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade declined. Could not correctly fetch your backpack.");

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                //if (tradeManager.OtherInventory.IsPrivate)
                //{
                //    SteamFriends.SendChatMessage(callback.OtherClient,
                //                                 EChatEntryType.ChatMsg,
                //                                 "Trade declined. Your backpack cannot be private.");

                //    SteamTrade.RespondToTrade (callback.TradeID, false);
                //    return;
                //}

                if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest())
                {
                    SteamTrade.RespondToTrade(callback.TradeID, true);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback> (callback =>
            {
                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Debug("Trade Status: " + callback.Response);
                    log.Info("Trade Accepted!");
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
                }
                else
                {
                    log.Warn("Trade failed: " + callback.Response);
                    CloseTrade();
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
                }
            });
            #endregion

            #region Disconnect
            msg.Handle <SteamUser.LoggedOffCallback> (callback =>
            {
                IsLoggedIn = false;
                log.Warn("Logged Off: " + callback.Result);
            });

            msg.Handle <SteamClient.DisconnectedCallback> (callback =>
            {
                IsLoggedIn = false;
                CloseTrade();
                log.Warn("Disconnected from Steam Network!");
                SteamClient.Connect();
            });
            #endregion
        }
Пример #2
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());

            #region Login
            msg.Handle <SteamClient.ConnectedCallback>(callback =>
            {
                log.Debug("Connection Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    log.Error("Failed to connect to Steam Community, trying again...");
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoggedOnCallback>(callback =>
            {
                log.Debug("Logged On Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    MyUserNonce = callback.WebAPIUserNonce;
                }
                else
                {
                    log.Error("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command.");

                    // try to get the steamguard auth code from the event callback
                    var eva = new SteamGuardRequiredEventArgs();
                    FireOnSteamGuardRequired(eva);
                    if (!String.IsNullOrEmpty(eva.SteamGuard))
                    {
                        logOnDetails.AuthCode = eva.SteamGuard;
                    }
                    else
                    {
                        logOnDetails.AuthCode = Console.ReadLine();
                    }
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback>(callback =>
            {
                MyUniqueId = callback.UniqueID.ToString();

                UserWebLogOn();

                if (Trade.CurrentSchema == null)
                {
                    log.Info("Downloading Schema...");
                    Trade.CurrentSchema = Schema.FetchSchema(apiKey);
                    log.Success("Schema Downloaded!");
                }

                SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName);
                SteamFriends.SetPersonaState(EPersonaState.Online);

                log.Success("Steam Bot Logged In Completely!");

                IsLoggedIn = true;

                GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
            });

            msg.Handle <SteamClient.JobCallback <SteamUser.WebAPIUserNonceCallback> >(jobCallback =>
            {
                log.Debug("Received new WebAPIUserNonce.");

                if (jobCallback.Callback.Result == EResult.OK)
                {
                    MyUserNonce = jobCallback.Callback.Nonce;

                    UserWebLogOn();
                }
                else
                {
                    log.Error("WebAPIUserNonce Error: " + jobCallback.Callback.Result);
                }
            });

            // handle a special JobCallback differently than the others
            if (msg.IsType <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >())
            {
                msg.Handle <SteamClient.JobCallback <SteamUser.UpdateMachineAuthCallback> >(
                    jobCallback => OnUpdateMachineAuthCallback(jobCallback.Callback, jobCallback.JobID)
                    );
            }
            #endregion

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    switch (friend.SteamID.AccountType)
                    {
                    case EAccountType.Clan:
                        if (friend.Relationship == EFriendRelationship.RequestRecipient)
                        {
                            if (GetUserHandler(friend.SteamID).OnGroupAdd())
                            {
                                AcceptGroupInvite(friend.SteamID);
                            }
                            else
                            {
                                DeclineGroupInvite(friend.SteamID);
                            }
                        }
                        break;

                    default:
                        CreateFriendsListIfNecessary();
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                            RemoveUserHandler(friend.SteamID);
                        }
                        else if (friend.Relationship == EFriendRelationship.RequestRecipient)
                        {
                            if (GetUserHandler(friend.SteamID).OnFriendAdd())
                            {
                                if (!friends.Contains(friend.SteamID))
                                {
                                    friends.Add(friend.SteamID);
                                }
                                else
                                {
                                    log.Error("Friend was added who was already in friends list: " + friend.SteamID);
                                }
                                SteamFriends.AddFriend(friend.SteamID);
                            }
                            else
                            {
                                SteamFriends.RemoveFriend(friend.SteamID);
                                RemoveUserHandler(friend.SteamID);
                            }
                        }
                        break;
                    }
                }
            });


            msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
            {
                EChatEntryType type = callback.EntryType;

                if (callback.EntryType == EChatEntryType.ChatMsg)
                {
                    log.Info(String.Format("Chat Message from {0}: {1}",
                                           SteamFriends.GetFriendPersonaName(callback.Sender),
                                           callback.Message
                                           ));
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });
            #endregion

            #region Group Chat
            //Begin KFBros stuff
            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);

                if (callback.Message == "hi")
                {
                    SteamFriends.SendChatRoomMessage(callback.ChatRoomID, EChatEntryType.ChatMsg, "hi");
                }

                if (callback.Message.Contains("v="))
                {
                    string coolresult;
                    string[] result = callback.Message.Split(' ');

                    for (int i = 0; i < result.Length; ++i)
                    {
                        if (result[i].Contains("v="))
                        {
                            coolresult = result[i];
                            log.Warn(coolresult.Substring(coolresult.IndexOf("v=") + 2));

                            string url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + coolresult.Substring(coolresult.IndexOf("v=") + 2) + "&key=" + youtubeService.ApiKey;

                            WebRequest request   = HttpWebRequest.Create(url);
                            WebResponse response = request.GetResponse();
                            StreamReader reader  = new StreamReader(response.GetResponseStream());

                            string urlText = reader.ReadToEnd();

                            string final = "Youtube: " + urlText.Substring(urlText.IndexOf("\"title\": ") + 9, (urlText.IndexOf("\"description\":") - 6) - (urlText.IndexOf("\"title\": ") + 9));

                            log.Success(final);

                            if (final.Length > 9)
                            {
                                SteamFriends.SendChatRoomMessage(callback.ChatRoomID, EChatEntryType.ChatMsg, final);
                            }
                        }
                    }
                }
            });

            //handle bot being kicked and other type of chat member state messages
            msg.Handle <SteamFriends.ChatMemberInfoCallback>(callback =>
            {
                if (callback.StateChangeInfo.ChatterActedOn == 76561198119861272)
                {
                    if (callback.StateChangeInfo.StateChange == EChatMemberStateChange.Kicked)
                    {
                        SteamFriends.JoinChat(callback.ChatRoomID);
                    }
                }
            });



            #endregion

            #region Trading
            msg.Handle <SteamTrading.SessionStartCallback>(callback =>
            {
                bool started = HandleTradeSessionStart(callback.OtherClient);

                if (!started)
                {
                    log.Error("Could not start the trade session.");
                }
                else
                {
                    log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
                }
            });

            msg.Handle <SteamTrading.TradeProposedCallback>(callback =>
            {
                if (CheckCookies() == false)
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                try
                {
                    tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
                }
                catch (WebException we)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade error: " + we.Message);

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }
                catch (Exception)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade declined. Could not correctly fetch your backpack.");

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                //if (tradeManager.OtherInventory.IsPrivate)
                //{
                //    SteamFriends.SendChatMessage(callback.OtherClient,
                //                                 EChatEntryType.ChatMsg,
                //                                 "Trade declined. Your backpack cannot be private.");

                //    SteamTrade.RespondToTrade (callback.TradeID, false);
                //    return;
                //}

                if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest())
                {
                    SteamTrade.RespondToTrade(callback.TradeID, true);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback>(callback =>
            {
                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Debug("Trade Status: " + callback.Response);
                    log.Info("Trade Accepted!");
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
                }
                else
                {
                    log.Warn("Trade failed: " + callback.Response);
                    CloseTrade();
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
                }
            });
            #endregion

            #region Disconnect
            msg.Handle <SteamUser.LoggedOffCallback>(callback =>
            {
                IsLoggedIn = false;
                log.Warn("Logged Off: " + callback.Result);
            });

            msg.Handle <SteamClient.DisconnectedCallback>(callback =>
            {
                IsLoggedIn = false;
                CloseTrade();
                log.Warn("Disconnected from Steam Network!");
                SteamClient.Connect();
            });
            #endregion

            #region Notifications
            msg.Handle <SteamBot.SteamNotifications.NotificationCallback>(callback =>
            {
                //currently only appears to be of trade offer
                if (callback.Notifications.Count != 0)
                {
                    foreach (var notification in callback.Notifications)
                    {
                        log.Info(notification.UserNotificationType + " notification");
                    }
                }

                // Get offers only if cookies are valid
                if (CheckCookies())
                {
                    tradeOfferManager.GetOffers();
                }
            });

            msg.Handle <SteamBot.SteamNotifications.CommentNotificationCallback>(callback =>
            {
                //various types of comment notifications on profile/activity feed etc
                //log.Info("received CommentNotificationCallback");
                //log.Info("New Commments " + callback.CommentNotifications.CountNewComments);
                //log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner);
                //log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions);
            });
            #endregion
        }
Пример #3
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
		}
Пример #4
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.");
					}
				}
			}
		}
Пример #5
0
        void HandleSteamMessage(ICallbackMsg msg)
        {
            log.Debug(msg.ToString());

            #region Login
            msg.Handle <SteamClient.ConnectedCallback>(callback =>
            {
                log.Debug("Connection Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    log.Error("Failed to connect to Steam Community, trying again...");
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoggedOnCallback>(callback =>
            {
                log.Debug("Logged On Callback: " + callback.Result);

                if (callback.Result == EResult.OK)
                {
                    MyUserNonce = callback.WebAPIUserNonce;
                }
                else
                {
                    log.Error("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command.");

                    // try to get the steamguard auth code from the event callback
                    var eva = new SteamGuardRequiredEventArgs();
                    FireOnSteamGuardRequired(eva);
                    if (!String.IsNullOrEmpty(eva.SteamGuard))
                    {
                        logOnDetails.AuthCode = eva.SteamGuard;
                    }
                    else
                    {
                        logOnDetails.AuthCode = Console.ReadLine();
                    }
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback>(callback =>
            {
                MyUniqueId = callback.UniqueID.ToString();

                UserWebLogOn();

                if (Trade.CurrentSchema == null)
                {
                    log.Info("Downloading Schema...");
                    Trade.CurrentSchema = Schema.FetchSchema(apiKey);
                    log.Success("Schema Downloaded!");
                }

                SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName);
                SteamFriends.SetPersonaState(EPersonaState.Online);

                log.Success("Steam Bot Logged In Completely!");

                IsLoggedIn = true;

                GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
            });

            msg.Handle <SteamUser.WebAPIUserNonceCallback>(webCallback =>
            {
                log.Debug("Received new WebAPIUserNonce.");

                if (webCallback.Result == EResult.OK)
                {
                    MyUserNonce = webCallback.Nonce;
                    UserWebLogOn();
                }
                else
                {
                    log.Error("WebAPIUserNonce Error: " + webCallback.Result);
                }
            });

            msg.Handle <SteamUser.UpdateMachineAuthCallback>(
                authCallback => OnUpdateMachineAuthCallback(authCallback)
                );
            #endregion

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    switch (friend.SteamID.AccountType)
                    {
                    case EAccountType.Clan:
                        if (friend.Relationship == EFriendRelationship.RequestRecipient)
                        {
                            if (GetUserHandler(friend.SteamID).OnGroupAdd())
                            {
                                AcceptGroupInvite(friend.SteamID);
                            }
                            else
                            {
                                DeclineGroupInvite(friend.SteamID);
                            }
                        }
                        break;

                    default:
                        CreateFriendsListIfNecessary();
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                            RemoveUserHandler(friend.SteamID);
                        }
                        else if (friend.Relationship == EFriendRelationship.RequestRecipient)
                        {
                            if (GetUserHandler(friend.SteamID).OnFriendAdd())
                            {
                                if (!friends.Contains(friend.SteamID))
                                {
                                    friends.Add(friend.SteamID);
                                }
                                else
                                {
                                    log.Error("Friend was added who was already in friends list: " + friend.SteamID);
                                }
                                SteamFriends.AddFriend(friend.SteamID);
                            }
                            else
                            {
                                SteamFriends.RemoveFriend(friend.SteamID);
                                RemoveUserHandler(friend.SteamID);
                            }
                        }
                        break;
                    }
                }
            });


            msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
            {
                EChatEntryType type = callback.EntryType;

                if (callback.EntryType == EChatEntryType.ChatMsg)
                {
                    log.Info(String.Format("Chat Message from {0}: {1}",
                                           SteamFriends.GetFriendPersonaName(callback.Sender),
                                           callback.Message
                                           ));
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });
            #endregion

            #region Group Chat
            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
            });
            #endregion

            #region Trading
            msg.Handle <SteamTrading.SessionStartCallback>(callback =>
            {
                bool started = HandleTradeSessionStart(callback.OtherClient);

                if (!started)
                {
                    log.Error("Could not start the trade session.");
                }
                else
                {
                    log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened.");
                }
            });

            msg.Handle <SteamTrading.TradeProposedCallback>(callback =>
            {
                if (CheckCookies() == false)
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                try
                {
                    tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
                }
                catch (WebException we)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade error: " + we.Message);

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }
                catch (Exception)
                {
                    SteamFriends.SendChatMessage(callback.OtherClient,
                                                 EChatEntryType.ChatMsg,
                                                 "Trade declined. Could not correctly fetch your backpack.");

                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

                //if (tradeManager.OtherInventory.IsPrivate)
                //{
                //    SteamFriends.SendChatMessage(callback.OtherClient,
                //                                 EChatEntryType.ChatMsg,
                //                                 "Trade declined. Your backpack cannot be private.");

                //    SteamTrade.RespondToTrade (callback.TradeID, false);
                //    return;
                //}

                if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest())
                {
                    SteamTrade.RespondToTrade(callback.TradeID, true);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback>(callback =>
            {
                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Debug("Trade Status: " + callback.Response);
                    log.Info("Trade Accepted!");
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString());
                }
                else
                {
                    log.Warn("Trade failed: " + callback.Response);
                    CloseTrade();
                    GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString());
                }
            });
            #endregion

            #region Disconnect
            msg.Handle <SteamUser.LoggedOffCallback>(callback =>
            {
                IsLoggedIn = false;
                log.Warn("Logged Off: " + callback.Result);
            });

            msg.Handle <SteamClient.DisconnectedCallback>(callback =>
            {
                IsLoggedIn = false;
                CloseTrade();
                log.Warn("Disconnected from Steam Network!");
                SteamClient.Connect();
            });
            #endregion

            #region Notifications
            msg.Handle <SteamBot.SteamNotifications.NotificationCallback>(callback =>
            {
                //currently only appears to be of trade offer
                if (callback.Notifications.Count != 0)
                {
                    foreach (var notification in callback.Notifications)
                    {
                        log.Info(notification.UserNotificationType + " notification");
                    }
                }

                // Get offers only if cookies are valid
                if (CheckCookies())
                {
                    tradeOfferManager.GetOffers();
                }
            });

            msg.Handle <SteamBot.SteamNotifications.CommentNotificationCallback>(callback =>
            {
                //various types of comment notifications on profile/activity feed etc
                //log.Info("received CommentNotificationCallback");
                //log.Info("New Commments " + callback.CommentNotifications.CountNewComments);
                //log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner);
                //log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions);
            });
            #endregion
        }
Пример #6
0
 public override void OnTradeError(string error)
 {
     Log.Error(error);
 }