Success() public method

public Success ( string data ) : void
data string
return void
 public override void OnTradeSuccess()
 {
     Log.Success("Trade Complete.");
 }
Beispiel #2
0
        private void sendWinnings(JSONClass winningsResponseObj)
        {
            if (winningsResponseObj.success != 1)
            {
                Log.Error("Server request failed. Error message:\n" + winningsResponseObj.errMsg);

                return;
            }

            Data winningsData = winningsResponseObj.data;

            //Get items to give and keep, and the winner and their trade token
            var itemsToGive = winningsData.tradeItems;
            var itemsToKeep = winningsData.profitItems;

            string  winnerSteamIDString = winningsData.winnerSteamId;
            SteamID winnerSteamID       = new SteamID(winnerSteamIDString);

            string winnerTradeToken = winningsData.winnerTradeToken;

            Log.Success("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken);

            //Get bot's inventory json
            string botInvUrl      = "http://steamcommunity.com/profiles/" + Bot.SteamUser.SteamID.ConvertToUInt64() + "/inventory/json/730/2";
            var    botInvRequest  = (HttpWebRequest)WebRequest.Create(botInvUrl);
            var    botInvResponse = (HttpWebResponse)botInvRequest.GetResponse();
            string botInvString   = new StreamReader(botInvResponse.GetResponseStream()).ReadToEnd();

            BotInventory botInventory = JsonConvert.DeserializeObject <BotInventory>(botInvString);

            if (botInventory.success != true)
            {
                Log.Error("An error occured while fetching the bot's inventory.");
                return;
            }
            var rgInventory = botInventory.rgInventory;

            //Create trade offer for the winner
            var winnerTradeOffer = Bot.NewTradeOffer(winnerSteamID);

            //Loop through all winner's items and add them to trade
            List <long> alreadyAddedToWinnerTrade = new List <long>();

            foreach (CSGOItemFromWeb item in itemsToGive)
            {
                long classId = item.classId, instanceId = item.instanceId;

                //Loop through all inventory items and find the asset id for the item
                long assetId = 0;
                foreach (var inventoryItem in rgInventory)
                {
                    var  value = inventoryItem.Value;
                    long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                    if (tClassId == classId && tInstanceId == instanceId)
                    {
                        //Check if this assetId has already been added to the trade
                        if (alreadyAddedToWinnerTrade.Contains(tAssetId))
                        {
                            continue;
                            //This is for when there are 2 of the same weapon, but they have different assetIds
                        }
                        assetId = tAssetId;
                        break;
                    }
                }

                //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                winnerTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                alreadyAddedToWinnerTrade.Add(assetId);
            }

            //Send trade offer to winner
            if (itemsToGive.Count > 0)
            {
                string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on " + Bot.BotWebsiteName + "! Here are your items.";

                //Try sending them 10 times, whatever
                doWebWithCatch(10, () => {
                    winnerTradeOffer.SendWithToken(out winnerTradeOfferId, winnerTradeToken, winnerMessage);
                });
                Bot.AcceptAllMobileTradeConfirmations();
                Log.Success("Offer sent to winner.");
            }
            else
            {
                Log.Info("No items to give to the winner... strange");
            }
        }
Beispiel #3
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
        }
Beispiel #4
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...");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "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)
                {
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in to Steam...";
                        log.Info("Logging in to Steam...");
                    }));
                }

                if (callback.Result != EResult.OK)
                {
                    log.Error("Login Error: " + callback.Result);
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Login Error: " + callback.Result;
                    }));
                }

                if (callback.Result == EResult.InvalidPassword)
                {
                    MessageBox.Show("Your password is incorrect. Please try again.",
                                    "Invalid Password",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1);
                    main.wrongAPI = true;
                    main.Invoke((Action)(main.Close));
                    return;
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard();
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("An Invalid Authorization Code was provided.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard("An Invalid Authorization Code was provided.\nEnter the authentication code sent to the proper email: ");
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                log.Debug("Handling LoginKeyCallback...");

                while (true)
                {
                    try
                    {
                        log.Info("About to authenticate...");
                        bool authd = false;
                        try
                        {
                            authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error on authentication:\n" + ex);
                        }
                        if (authd)
                        {
                            log.Success("User Authenticated!");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "User authenticated!";
                            }));
                            tradeManager = new TradeManager(apiKey, sessionId, token);
                            tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                            tradeManager.OnTimeout    += OnTradeTimeout;
                            tradeManager.OnTradeEnded += OnTradeEnded;
                            break;
                        }
                        else
                        {
                            log.Warn("Authentication failed, retrying in 2s...");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "Authentication failed, retrying in 2s...";
                            }));
                            Thread.Sleep(2000);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                    }
                }

                if (Trade.CurrentSchema == null)
                {
                    log.Info("Downloading Schema...");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Downloading schema...";
                    }));
                    try
                    {
                        Trade.CurrentSchema = Schema.FetchSchema(apiKey);
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                        MessageBox.Show("I can't fetch the schema! Your API key may be invalid or there may be a problem connecting to Steam. Please make sure you have obtained a proper API key at http://steamcommunity.com/dev/apikey",
                                        "Schema Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error,
                                        MessageBoxDefaultButton.Button1);
                        main.wrongAPI = true;
                        main.Invoke((Action)(main.Dispose));
                        return;
                    }
                    log.Success("Schema Downloaded!");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Schema downloaded!";
                    }));
                }

                SteamFriends.SetPersonaName(SteamFriends.GetFriendPersonaName(SteamUser.SteamID));
                SteamFriends.SetPersonaState(EPersonaState.Online);

                log.Success("Account Logged In Completely!");
                main.Invoke((Action)(() =>
                {
                    main.label_status.Text = "Logged in completely!";
                }));

                IsLoggedIn  = true;
                displayName = SteamFriends.GetPersonaName();
                ConnectToGC(13540830642081628378);
                Thread.Sleep(500);
                DisconnectFromGC();
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }
                Thread.Sleep(2500);
                CDNCache.Initialize();
            });

            // 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 =>
            {
                bool newFriend = false;
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (!friends.Contains(friend.SteamID) && !friend.SteamID.ToString().StartsWith("1"))
                    {
                        new Thread(() =>
                        {
                            main.Invoke((Action)(() =>
                            {
                                if (showFriends == null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                {
                                    log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                    friends.Add(friend.SteamID);
                                    newFriend = true;
                                    string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                    string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                    if (!ListFriendRequests.Find(friend.SteamID))
                                    {
                                        ListFriendRequests.Add(name, friend.SteamID, status);
                                    }
                                }
                                if (showFriends != null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                {
                                    log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                    friends.Add(friend.SteamID);

                                    /*if (friend.Relationship == EFriendRelationship.RequestRecipient &&
                                     *  GetUserHandler(friend.SteamID).OnFriendAdd())
                                     * {
                                     *  SteamFriends.AddFriend(friend.SteamID);
                                     * }*/
                                    newFriend = true;
                                    string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                    string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                    if (!ListFriendRequests.Find(friend.SteamID))
                                    {
                                        try
                                        {
                                            showFriends.NotifyFriendRequest();
                                            ListFriendRequests.Add(name, friend.SteamID, status);
                                            log.Info("Notifying you that " + SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                            int duration = 5;
                                            FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                                            FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                                            Notification toastNotification = new Notification(name, "has sent you a friend request.", duration, animationMethod, animationDirection);
                                            toastNotification.Show();
                                            try
                                            {
                                                string soundsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
                                                string soundFile = Path.Combine(soundsFolder + "trade_message.wav");
                                                using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundFile))
                                                {
                                                    player.Play();
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine(e.Message);
                                            }
                                            showFriends.list_friendreq.SetObjects(ListFriendRequests.Get());
                                        }
                                        catch
                                        {
                                            Console.WriteLine("Friends list hasn't loaded yet...");
                                        }
                                    }
                                }
                            }));
                        }).Start();
                    }
                    else
                    {
                        if (friend.Relationship == EFriendRelationship.None)
                        {
                            friends.Remove(friend.SteamID);
                            GetUserHandler(friend.SteamID).OnFriendRemove();
                        }
                    }
                }
                if (!newFriend && ListFriendRequests.Get().Count == 0)
                {
                    if (showFriends != null)
                    {
                        showFriends.HideFriendRequests();
                    }
                }
            });

            msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
            {
                var status = callback.State;
                var sid    = callback.FriendID;
                GetUserHandler(sid).SetStatus(status);
                ListFriends.UpdateStatus(sid, status.ToString());
            });


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

                if (callback.EntryType == EChatEntryType.Typing)
                {
                    var name = SteamFriends.GetFriendPersonaName(callback.Sender);
                    GetUserHandler(callback.Sender).SetChatStatus(name + " is typing...");
                }
                else
                {
                    GetUserHandler(callback.Sender).SetChatStatus("");
                }

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

            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                Console.WriteLine(SteamFriends.GetFriendPersonaName(callback.ChatterID) + ": " + callback.Message);
            });
            #endregion

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

                //if (!started)
                //log.Info ("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
                {
                    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 ())
                if (CurrentTrade == null)
                {
                    GetUserHandler(callback.OtherClient).SendTradeState(callback.TradeID);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback>(callback =>
            {
                //log.Debug ("Trade Status: " + callback.Response);

                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    //log.Info ("Trade Accepted!");
                }
                if (callback.Response == EEconTradeResponse.Cancel ||
                    callback.Response == EEconTradeResponse.ConnectionFailed ||
                    callback.Response == EEconTradeResponse.Declined ||
                    callback.Response == EEconTradeResponse.Error ||
                    callback.Response == EEconTradeResponse.InitiatorAlreadyTrading ||
                    callback.Response == EEconTradeResponse.TargetAlreadyTrading ||
                    callback.Response == EEconTradeResponse.Timeout ||
                    callback.Response == EEconTradeResponse.TooSoon ||
                    callback.Response == EEconTradeResponse.TradeBannedInitiator ||
                    callback.Response == EEconTradeResponse.TradeBannedTarget ||
                    callback.Response == EEconTradeResponse.NotLoggedIn) // uh...
                {
                    if (callback.Response == EEconTradeResponse.Cancel)
                    {
                        TradeResponse(callback.OtherClient, "had asked to trade with you, but has cancelled their request.");
                    }
                    if (callback.Response == EEconTradeResponse.ConnectionFailed)
                    {
                        TradeResponse(callback.OtherClient, "Lost connection to Steam. Reconnecting as soon as possible...");
                    }
                    if (callback.Response == EEconTradeResponse.Declined)
                    {
                        TradeResponse(callback.OtherClient, "has declined your trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.Error)
                    {
                        TradeResponse(callback.OtherClient, "An error has occurred in sending the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.InitiatorAlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You are already in a trade so you cannot trade someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.TargetAlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade the other user because they are already in trade with someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.Timeout)
                    {
                        TradeResponse(callback.OtherClient, "did not respond to the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.TooSoon)
                    {
                        TradeResponse(callback.OtherClient, "It is too soon to send a new trade request. Try again later.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedInitiator)
                    {
                        TradeResponse(callback.OtherClient, "You are trade-banned and cannot trade.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedTarget)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade with this person because they are trade-banned.");
                    }
                    if (callback.Response == EEconTradeResponse.NotLoggedIn)
                    {
                        TradeResponse(callback.OtherClient, "Trade failed to initialize because you are not logged in.");
                    }
                    CloseTrade();
                }
            });
            #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!");
                main.Invoke((Action)(() =>
                {
                    main.label_status.Text = "Disconnected from Steam Network! Retrying...";
                }));
                SteamClient.Connect();
                main.Invoke((Action)(() =>
                {
                    main.label_status.Text = "Connecting to Steam...";
                }));
            });
            #endregion

            if (!hasrun && IsLoggedIn)
            {
                Thread main = new Thread(GUI);
                main.Start();
                hasrun = true;
            }
        }
Beispiel #5
0
        public override void OnBotCommand(string command)
        {
            if (IsAdmin)
            {
                if (command.Equals("confirm"))
                {
                    Bot.AcceptAllMobileTradeConfirmations();
                    Log.Success("All trade offers confirmed... on bot: " + Bot.SteamUser.SteamID.ConvertToUInt64());
                }
            }
            if (command.Equals("skins"))
            {
                //Get current pot and all items in inventory
                string withdrawUrl      = Bot.BotWebsiteURL + "/php/bot-withdraw.php";
                var    withdrawRequest  = (HttpWebRequest)WebRequest.Create(withdrawUrl);
                var    withdrawResponse = (HttpWebResponse)withdrawRequest.GetResponse();
                string withdrawString   = new StreamReader(withdrawResponse.GetResponseStream()).ReadToEnd();

                WithdrawResponse botInventory = JsonConvert.DeserializeObject <WithdrawResponse>(withdrawString);

                var data = botInventory.data;

                var rgInventory = data.rgInventory;
                var currentPot  = data.currentPot;

                var withdrawTradeOffer = Bot.NewTradeOffer(new SteamID(Bot.ProfitAdmin));

                foreach (var inventoryItemKeyVal in rgInventory)
                {
                    var  invItem = inventoryItemKeyVal.Value;
                    long classId = invItem.classid, instanceId = invItem.instanceid;

                    bool withdrawThisItem = true;
                    //Check to see if this item is in the current pot
                    foreach (var potItem in currentPot)
                    {
                        long classIdPot = potItem.classid, instanceIdPot = potItem.instanceid;

                        if (classId == classIdPot && instanceId == instanceIdPot)
                        {
                            withdrawThisItem = false;
                        }
                    }

                    if (withdrawThisItem)
                    {
                        if (invItem.instanceid != 0)
                        {
                            if (invItem.instanceid != 519977179)
                            {
                                var assetId = invItem.id;
                                withdrawTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                            }
                        }
                    }
                }

                if (withdrawTradeOffer.Items.GetMyItems().Count != 0)
                {
                    string withdrawOfferId;
                    withdrawTradeOffer.Send(out withdrawOfferId, "Here are the withdraw items requested.");
                    Bot.AcceptAllMobileTradeConfirmations();
                    Log.Success("Withdraw trade offer sent. Offer ID: " + withdrawOfferId);
                }
                else
                {
                    Log.Error("There are no profit items to withdraw at this time.");
                }
            }
            if (command.Equals("withdraw"))
            {
                //Get current pot and all items in inventory
                string withdrawUrl      = Bot.BotWebsiteURL + "/php/bot-withdraw.php";
                var    withdrawRequest  = (HttpWebRequest)WebRequest.Create(withdrawUrl);
                var    withdrawResponse = (HttpWebResponse)withdrawRequest.GetResponse();
                string withdrawString   = new StreamReader(withdrawResponse.GetResponseStream()).ReadToEnd();

                WithdrawResponse botInventory = JsonConvert.DeserializeObject <WithdrawResponse>(withdrawString);

                var data = botInventory.data;

                var rgInventory = data.rgInventory;
                var currentPot  = data.currentPot;

                var withdrawTradeOffer = Bot.NewTradeOffer(new SteamID(Bot.ProfitAdmin));

                foreach (var inventoryItemKeyVal in rgInventory)
                {
                    var  invItem = inventoryItemKeyVal.Value;
                    long classId = invItem.classid, instanceId = invItem.instanceid;

                    bool withdrawThisItem = true;
                    //Check to see if this item is in the current pot
                    foreach (var potItem in currentPot)
                    {
                        long classIdPot = potItem.classid, instanceIdPot = potItem.instanceid;

                        if (classId == classIdPot && instanceId == instanceIdPot)
                        {
                            withdrawThisItem = false;
                        }
                    }

                    if (withdrawThisItem)
                    {
                        var assetId = invItem.id;
                        withdrawTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                    }
                }

                if (withdrawTradeOffer.Items.GetMyItems().Count != 0)
                {
                    string withdrawOfferId;
                    withdrawTradeOffer.Send(out withdrawOfferId, "Here are the withdraw items requested.");
                    Bot.AcceptAllMobileTradeConfirmations();
                    Log.Success("Withdraw trade offer sent. Offer ID: " + withdrawOfferId);
                }
                else
                {
                    Log.Error("There are no profit items to withdraw at this time.");
                }
            }
        }
Beispiel #6
0
        public override void OnTradeAccept()
        {
            if (Validate() || IsAdmin)
            {
                Bot.log.Success("Accepting trade...");
                try
                {
                    Trade.AcceptTrade();
                    if (!IsAdmin)
                    {
                        string fileDirectory = "Donation";
                        string fileName      = OtherSID.ConvertToUInt64().ToString();
                        string fullPath      = Path.Combine(fileDirectory, fileName + ".log");
                        fullPath = FileToCreate;
                        string sPastDonation = string.Empty;
                        string sSpacer       = @"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\";
                        if (File.Exists(fullPath))
                        {
                            TextReader reader = new StreamReader(fullPath);
                            sPastDonation = reader.ReadToEnd();
                            reader.Close();
                        }
                        else
                        {
                            File.Create(fullPath);
                        }

                        StreamWriter writer = new StreamWriter(fullPath, false);
                        writer.WriteLine(sSpacer);
                        List <Inventory.Item> items = new List <Inventory.Item>();
                        foreach (TradeUserAssets id in Trade.OtherOfferedItems)
                        {
                            if (id.appid == 440)
                            {
                                items.Add(Trade.OtherInventory.GetItem(id.assetid));//Get item
                            }
                        }//foreach (ulong id in Trade.OtherOfferedItems)
                        foreach (Inventory.Item id in items)
                        {
                            Schema      schema       = Trade.CurrentSchema;
                            Inventory   inventory    = Trade.OtherInventory;
                            Schema.Item schemaItem   = schema.GetItem(id.Defindex);
                            string      ItemAddedMsg = String.Format("User added {0} {1} {2} {3}", id.IsNotCraftable.ToString().ToLower() == "true" ? "NonCraftable" : "Craftable", clsFunctions.ConvertQualityToString(schemaItem.ItemQuality), schemaItem.ItemName, schemaItem.CraftMaterialType); //ready ItemRemovedMsg
                            writer.WriteLine("Donated: " + ItemAddedMsg);
                        }
                        writer.WriteLine(Bot.SteamFriends.GetFriendPersonaName(OtherSID));
                        writer.WriteLine(OtherSID.ConvertToUInt64().ToString());
                        writer.WriteLine(System.DateTime.Now.ToShortTimeString());
                        if (sPastDonation != null)
                        {
                            writer.Write(sPastDonation);
                        }
                        writer.Close();


                        Bot.SteamFriends.SendChatMessage(OtherSID, EChatEntryType.ChatMsg, "Thank you for donating!");
                        Bot.SteamFriends.SendChatMessage(clsFunctions.BotsOwnerID, EChatEntryType.ChatMsg, "A user just donated!");
                    }

                    Log.Success("Trade Complete!");
                }
                catch (System.Exception ex)
                {
                    Log.Warn("The trade might have failed, but we can't be sure.");
                    Log.Warn(ex.Message);
                }
            }
            Bot.SteamFriends.SetPersonaState(EPersonaState.Online);

            OnTradeClose();
        }
Beispiel #7
0
 public override void OnLoginCompleted()
 {
     Log.Success("SteamBot Version 1.8 started !");
     Log.Success("Visit the Alliedmodders page daily !");
     Log.Success("Important updates may happen !");
 }
Beispiel #8
0
 public override void OnFriendRemove()
 {
     Log.Success(Bot.SteamFriends.GetFriendPersonaName(OtherSID) + "removed me!");
 }
        public override void OnNewTradeOffer(TradeOffer offer)
        {
            //Get password from file on desktop
            string pass = System.IO.File.ReadAllText(@"C:\Users\Jordan Turley\Desktop\password.txt");

            //Get items in the trade, and ID of user sending trade
            var theirItems = offer.Items.GetTheirItems();
            var myItems    = offer.Items.GetMyItems();
            var userID     = offer.PartnerSteamId;

            bool shouldDecline = false;

            //Check if they are trying to get items from the bot
            if (myItems.Count > 0 || theirItems.Count == 0)
            {
                shouldDecline = true;
                Log.Error("Offer declined because the offer wasn't a gift; the user wanted items instead of giving.");
            }

            //Check to make sure all items are for CS: GO.
            foreach (TradeAsset item in theirItems)
            {
                if (item.AppId != 730)
                {
                    shouldDecline = true;
                    Log.Error("Offer declined because one or more items was not for CS: GO.");
                }
            }

            //Check if there are more than 10 items in the trade
            if (theirItems.Count > 10)
            {
                shouldDecline = true;
                Log.Error("Offer declined because there were more than 10 items in the deposit.");
            }

            if (shouldDecline)
            {
                if (offer.Decline())
                {
                    Log.Error("Offer declined.");
                }
                return;
            }

            Log.Success("Offer approved, accepting.");

            //Send items to server and check if all items add up to more than $1.
            //If they do, accept the trade. If they don't, decline the trade.
            string postData = "password="******"&owner=" + userID;

            string theirItemsJSON = JsonConvert.SerializeObject(theirItems);

            postData += "&items=" + theirItemsJSON;

            string url     = "http://csgowinbig.com/php/check-items.php";
            var    request = (HttpWebRequest)WebRequest.Create(url);

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

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

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

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            //Log.Success ("Response received from server: \n" + responseString);

            JSONClass responseJsonObj = JsonConvert.DeserializeObject <JSONClass> (responseString);

            if (responseJsonObj.success == 1)
            {
                //Get data array from json
                var jsonData = responseJsonObj.data;

                if (jsonData.minDeposit == 1)
                {
                    if (offer.Accept())
                    {
                        Log.Success("Offer accepted from " + userID);

                        //Put items into the pot
                        string urlPutItemsIn        = "http://csgowinbig.com/php/deposit.php";
                        var    requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create(urlPutItemsIn);

                        string postDataPutItemsIn = "password="******"&owner=" + userID;
                        postDataPutItemsIn += "&items=" + jsonData.allItems;
                        //Log.Success (jsonData.allItems);

                        var dataPutItemsIn = Encoding.ASCII.GetBytes(postDataPutItemsIn);

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

                        using (var stream = requestUrlPutItemsIn.GetRequestStream()) {
                            stream.Write(dataPutItemsIn, 0, dataPutItemsIn.Length);
                        }

                        var       responsePutItemsIn        = (HttpWebResponse)requestUrlPutItemsIn.GetResponse();
                        string    responsePutItemsInString  = new StreamReader(responsePutItemsIn.GetResponseStream()).ReadToEnd();
                        JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject <JSONClass> (responsePutItemsInString);
                        jsonData = responseJsonObjPutItemsIn.data;
                    }

                    //Check if the pot is over
                    if (jsonData.potOver == 1)
                    {
                        //Get items to give and keep, and the winner and their trade token
                        var itemsToGive = jsonData.tradeItems;
                        var itemsToKeep = jsonData.profitItems;

                        string  winnerSteamIDString = jsonData.winnerSteamID;
                        SteamID winnerSteamID       = new SteamID(winnerSteamIDString);

                        string winnerTradeToken = jsonData.winnerTradeToken;

                        Log.Success("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken);

                        //Get bot's inventory json
                        string botInvUrl      = "http://steamcommunity.com/profiles/76561198238743988/inventory/json/730/2";
                        var    botInvRequest  = (HttpWebRequest)WebRequest.Create(botInvUrl);
                        var    botInvResponse = (HttpWebResponse)botInvRequest.GetResponse();
                        string botInvString   = new StreamReader(botInvResponse.GetResponseStream()).ReadToEnd();

                        BotInventory botInventory = JsonConvert.DeserializeObject <BotInventory> (botInvString);
                        if (botInventory.success != true)
                        {
                            Log.Error("An error occured while fetching the bot's inventory.");
                            return;
                        }
                        var rgInventory = botInventory.rgInventory;

                        //Create trade offer for the winner
                        var winnerTradeOffer = Bot.NewTradeOffer(winnerSteamID);

                        //Loop through all winner's items and add them to trade
                        List <long> alreadyAddedToWinnerTrade = new List <long> ();
                        foreach (CSGOItemFromWeb item in itemsToGive)
                        {
                            long classId = item.classId, instanceId = item.instanceId;

                            //Loop through all inventory items and find the asset id for the item
                            long assetId = 0;
                            foreach (var inventoryItem in rgInventory)
                            {
                                var  value = inventoryItem.Value;
                                long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                                if (tClassId == classId && tInstanceId == instanceId)
                                {
                                    //Check if this assetId has already been added to the trade
                                    if (alreadyAddedToWinnerTrade.Contains(tAssetId))
                                    {
                                        continue;
                                        //This is for when there are 2 of the same weapon, but they have different assetIds
                                    }
                                    assetId = tAssetId;
                                    break;
                                }
                            }

                            //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                            winnerTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                            alreadyAddedToWinnerTrade.Add(assetId);
                        }

                        //Send trade offer to winner
                        if (itemsToGive.Count > 0)
                        {
                            string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on CSGO Win Big! Here are your items.";
                            winnerTradeOffer.SendWithToken(out winnerTradeOfferId, winnerTradeToken, winnerMessage);
                            Log.Success("Offer sent to winner.");
                        }
                        else
                        {
                            Log.Info("No items to give... strange");
                        }
                    }
                }
                else
                {
                    if (offer.Decline())
                    {
                        Log.Error("Minimum deposit not reached, offer declined.");
                    }
                }
            }
            else
            {
                Log.Error("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg);
                offer.Decline();
            }
        }
Beispiel #10
0
        private void timerEvent(object CancellationTokenSource, ElapsedEventArgs e)
        {
            timerTime++;

            //Check if the timer is at 2 minutes
            if (timerTime >= 120)
            {
                //If the timer is done, stop the timer and call to server to end the round/pick a winner
                timer.Stop();
                timerTime    = 0;
                timerRunning = false;

                //Get password from file on desktop
                string pass = Bot.BotDBPassword;

                string urlTimerEnd        = Bot.BotWebsiteURL + "/php/timer-end.php";
                var    requestUrlTimerEnd = (HttpWebRequest)WebRequest.Create(urlTimerEnd);

                string postDataTimerEnd = "password="******"POST";
                requestUrlTimerEnd.ContentType   = "application/x-www-form-urlencoded";
                requestUrlTimerEnd.ContentLength = dataTimerEnd.Length;

                using (var stream = requestUrlTimerEnd.GetRequestStream())
                {
                    stream.Write(dataTimerEnd, 0, dataTimerEnd.Length);
                }

                var    responseTimerEnd       = (HttpWebResponse)requestUrlTimerEnd.GetResponse();
                string responseTimerEndString = new StreamReader(responseTimerEnd.GetResponseStream()).ReadToEnd();

                //Uncomment this line to print out the response from timer-end.php
                //Log.Success ("Response received from timer-end.php: " + responseTimerEndString);

                JSONClass timerEndJsonObj = JsonConvert.DeserializeObject <JSONClass>(responseTimerEndString);

                if (timerEndJsonObj.success != 1)
                {
                    Log.Error("Server request failed. Error message:\n" + timerEndJsonObj.errMsg);

                    return;
                }

                Data timerEndData = timerEndJsonObj.data;

                //Get items to give and keep, and the winner and their trade token
                var itemsToGive = timerEndData.tradeItems;
                var itemsToKeep = timerEndData.profitItems;

                string  winnerSteamIDString = timerEndData.winnerSteamId;
                SteamID winnerSteamID       = new SteamID(winnerSteamIDString);

                string winnerTradeToken = timerEndData.winnerTradeToken;

                Log.Success("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken);

                //Get bot's inventory json
                string botInvUrl      = "http://steamcommunity.com/profiles/" + Bot.SteamUser.SteamID.ConvertToUInt64() + "/inventory/json/730/2";
                var    botInvRequest  = (HttpWebRequest)WebRequest.Create(botInvUrl);
                var    botInvResponse = (HttpWebResponse)botInvRequest.GetResponse();
                string botInvString   = new StreamReader(botInvResponse.GetResponseStream()).ReadToEnd();

                BotInventory botInventory = JsonConvert.DeserializeObject <BotInventory>(botInvString);
                if (botInventory.success != true)
                {
                    Log.Error("An error occured while fetching the bot's inventory.");
                    return;
                }
                var rgInventory = botInventory.rgInventory;

                //Create trade offer for the winner
                var winnerTradeOffer = Bot.NewTradeOffer(winnerSteamID);

                //Loop through all winner's items and add them to trade
                List <long> alreadyAddedToWinnerTrade = new List <long>();
                foreach (CSGOItemFromWeb item in itemsToGive)
                {
                    long classId = item.classId, instanceId = item.instanceId;

                    //Loop through all inventory items and find the asset id for the item
                    long assetId = 0;
                    foreach (var inventoryItem in rgInventory)
                    {
                        var  value = inventoryItem.Value;
                        long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                        if (tClassId == classId && tInstanceId == instanceId)
                        {
                            //Check if this assetId has already been added to the trade
                            if (alreadyAddedToWinnerTrade.Contains(tAssetId))
                            {
                                continue;
                                //This is for when there are 2 of the same weapon, but they have different assetIds
                            }
                            assetId = tAssetId;
                            break;
                        }
                    }

                    //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                    winnerTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                    alreadyAddedToWinnerTrade.Add(assetId);
                }

                //Send trade offer to winner
                if (itemsToGive.Count > 0)
                {
                    string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on " + Bot.BotWebsiteName + "! Here are your items.";

                    doWebWithCatch(-1, () =>
                    {
                        winnerTradeOffer.SendWithToken(out winnerTradeOfferId, winnerTradeToken, winnerMessage);
                    });
                    Bot.AcceptAllMobileTradeConfirmations();
                    Log.Success("Offer sent to winner.");
                }
                else
                {
                    Log.Info("No items to give... strange");
                }

                //Now, send all of the profit items to my own account
                var profitTradeOffer = Bot.NewTradeOffer(new SteamID(Bot.ProfitAdmin));

                //Loop through all profit items and add them to trade
                List <long> alreadyAddedToProfitTrade = new List <long>();
                foreach (CSGOItemFromWeb item in itemsToKeep)
                {
                    long classId = item.classId, instanceId = item.instanceId;

                    //Loop through all inventory items and find the asset id for the item
                    long assetId = 0;
                    foreach (var inventoryItem in rgInventory)
                    {
                        var  value = inventoryItem.Value;
                        long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                        if (tClassId == classId && tInstanceId == instanceId)
                        {
                            //Check if this assetId has already been added to the trade
                            if (alreadyAddedToProfitTrade.Contains(tAssetId))
                            {
                                continue;
                                //This is for when there are 2 of the same weapon, but they have different assetIds
                            }
                            assetId = tAssetId;
                            break;
                        }
                    }

                    //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                    profitTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                    alreadyAddedToProfitTrade.Add(assetId);
                }

                //Send trade offer to myself with profit items
                if (itemsToKeep.Count > 0)
                {
                    string profitTradeOfferId, profitMessage = "Here are the profit items from the round.";

                    doWebWithCatch(10, () =>
                    {
                        profitTradeOffer.Send(out profitTradeOfferId, profitMessage);
                    });
                    Bot.AcceptAllMobileTradeConfirmations();
                    Log.Success("Profit offer sent.");
                }
            }
        }
Beispiel #11
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());
            msg.Handle <SteamGameCoordinator.MessageCallback>(callback =>
            {
                Console.WriteLine(callback.EMsg);
            });

            msg.Handle <ClientPlayerNicknameListHandler.ClientPlayerNicknameListCallback>(callback =>
            {
                foreach (var player in callback.Nicknames)
                {
                    PlayerNicknames.Add(player.steamid, player.nickname);
                }
            });

            #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...");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "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;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in to Steam...";
                        log.Info("Logging in to Steam...");
                    }));
                }

                if (callback.Result != EResult.OK)
                {
                    log.Error("Login Error: " + callback.Result);
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Login Error: " + callback.Result;
                    }));
                }

                if (callback.Result == EResult.InvalidPassword)
                {
                    MetroFramework.MetroMessageBox.Show(main, "Your password is incorrect. Please try again.",
                                                        "Invalid Password",
                                                        MessageBoxButtons.OK,
                                                        MessageBoxIcon.Error,
                                                        MessageBoxDefaultButton.Button1);
                    main.wrongAPI = true;
                    main.Invoke((Action)(main.Close));
                    return;
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard();
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                    SteamClient.Connect();
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("An Invalid Authorization Code was provided.  Enter the authentication code sent to the proper email: ");
                    SteamGuard SteamGuard = new SteamGuard("An Invalid Authorization Code was provided.\nEnter the authentication code sent to the proper email: ");
                    SteamGuard.ShowDialog();
                    logOnDetails.AuthCode = SteamGuard.AuthCode;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in...";
                    }));
                    SteamClient.Connect();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                log.Debug("Handling LoginKeyCallback...");
                while (true)
                {
                    try
                    {
                        log.Info("About to authenticate...");
                        main.Invoke((Action)(() =>
                        {
                            main.label_status.Text = "Authenticating...";
                        }));
                        bool authd = false;
                        try
                        {
                            authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token, MyLoginKey);
                        }
                        catch (Exception ex)
                        {
                            log.Error("Error on authentication:\n" + ex);
                        }
                        if (authd)
                        {
                            log.Success("User authenticated!");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "User authenticated!";
                            }));
                            tradeManager = new TradeManager(apiKey, sessionId, token);
                            tradeManager.SetTradeTimeLimits(0, 0, TradePollingInterval);
                            tradeManager.OnTimeout += OnTradeTimeout;
                            break;
                        }
                        else
                        {
                            log.Warn("Authentication failed, retrying in 2s...");
                            main.Invoke((Action)(() =>
                            {
                                main.label_status.Text = "Authentication failed, retrying in 2s...";
                            }));
                            Thread.Sleep(2000);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error(ex.ToString());
                    }
                }

                SteamFriends.SetPersonaName(SteamFriends.GetFriendPersonaName(SteamUser.SteamID));
                SteamFriends.SetPersonaState(EPersonaState.Online);
                log.Success("Account Logged In Completely!");
                main.Invoke((Action)(() =>
                {
                    main.label_status.Text = "Logged in completely!";
                }));
                botCookies = new CookieContainer();
                botCookies.SetCookies(new Uri("http://steamcommunity.com"), string.Format("steamLogin={0}", token));
                botCookies.SetCookies(new Uri("http://steamcommunity.com"), string.Format("sessionid={0}", sessionId));
                GenericInventory.SetCookie(botCookies, SteamUser.SteamID);

                IsLoggedIn = true;
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }

                new Thread(() =>
                {
                    CDNCache.Initialize();
                    #if !DEBUG
                    ConnectToGC(13540830642081628378);
                    System.Threading.Thread.Sleep(2000);
                    ConnectToGC(0);
                    #endif
                    while (true)
                    {
                        if (showFriends != null)
                        {
                            var numFriendsDisplayed = showFriends.GetNumFriendsDisplayed();
                            var numSteamFriendCount = SteamFriends.GetFriendCount();
                            if (numFriendsDisplayed != -1 && numFriendsDisplayed != ListFriends.Get().Count)
                            {
                                LoadFriends();
                                showFriends.UpdateFriendsHTML();
                            }
                            System.Threading.Thread.Sleep(10000);
                        }
                    }
                }).Start();
            });

            // 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

            msg.Handle <SteamUser.AccountInfoCallback>(callback =>
            {
                DisplayName = callback.PersonaName;
            });

            #region Friends
            msg.Handle <SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (friend.SteamID.AccountType == EAccountType.Clan)
                    {
                    }
                    else
                    {
                        if (!friends.Contains(friend.SteamID))
                        {
                            new Thread(() =>
                            {
                                main.Invoke((Action)(() =>
                                {
                                    if (showFriends == null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                    {
                                        log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                        friends.Add(friend.SteamID);
                                        string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                        string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                        if (!ListFriendRequests.Find(friend.SteamID))
                                        {
                                            ListFriendRequests.Add(name, friend.SteamID, status);
                                        }
                                    }
                                    if (showFriends != null && friend.Relationship == EFriendRelationship.RequestRecipient)
                                    {
                                        log.Info(SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                        friends.Add(friend.SteamID);
                                        string name = SteamFriends.GetFriendPersonaName(friend.SteamID);
                                        string status = SteamFriends.GetFriendPersonaState(friend.SteamID).ToString();
                                        if (!ListFriendRequests.Find(friend.SteamID))
                                        {
                                            try
                                            {
                                                ListFriendRequests.Add(name, friend.SteamID, status);
                                                log.Info("Notifying you that " + SteamFriends.GetFriendPersonaName(friend.SteamID) + " has added you.");
                                                int duration = 5;
                                                FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                                                FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                                                Notification toastNotification = new Notification(name, Util.GetColorFromPersonaState(this, friend.SteamID), "has sent you a friend request.", duration, animationMethod, animationDirection);
                                                toastNotification.Show();
                                                try
                                                {
                                                    string soundsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
                                                    string soundFile = Path.Combine(soundsFolder + "trade_message.wav");
                                                    using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundFile))
                                                    {
                                                        player.Play();
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    Console.WriteLine(e.Message);
                                                }
                                            }
                                            catch
                                            {
                                                Console.WriteLine("Friends list hasn't loaded yet...");
                                            }
                                        }
                                    }
                                }));
                            }).Start();
                        }
                        else
                        {
                            if (friend.Relationship == EFriendRelationship.None)
                            {
                                friends.Remove(friend.SteamID);
                                GetUserHandler(friend.SteamID).OnFriendRemove();
                                RemoveUserHandler(friend.SteamID);
                            }
                        }
                    }
                }
                LoadFriends();
            });

            msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
            {
                var status = callback.State;
                var sid    = callback.FriendID;
                ListFriends.UpdateStatus(sid, status.ToString());
                ListFriends.UpdateName(sid, SteamFriends.GetFriendPersonaName(sid));
                GetUserHandler(sid).UpdatePersonaState();
                if (showFriends != null)
                {
                    showFriends.UpdateState();
                    showFriends.UpdateFriendHTML(sid);
                }
            });


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

                if (type == EChatEntryType.Typing)
                {
                    var name = SteamFriends.GetFriendPersonaName(callback.Sender);
                    GetUserHandler(callback.Sender).SetChatStatus(name + " is typing...");
                    System.Threading.Thread.Sleep(30000);
                    GetUserHandler(callback.Sender).SetChatStatus("");
                }

                if (type == EChatEntryType.ChatMsg)
                {
                    GetUserHandler(callback.Sender).SetChatStatus("");
                    GetUserHandler(callback.Sender).OnMessage(callback.Message, type);
                }
            });

            msg.Handle <SteamFriends.ChatMsgCallback>(callback =>
            {
                Console.WriteLine(SteamFriends.GetFriendPersonaName(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
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

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

            msg.Handle <SteamTrading.TradeResultCallback>(callback =>
            {
                //log.Debug ("Trade Status: " + callback.Response);

                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    //log.Info ("Trade Accepted!");
                }
                else if (callback.Response == EEconTradeResponse.Cancel ||
                         callback.Response == EEconTradeResponse.ConnectionFailed ||
                         callback.Response == EEconTradeResponse.Declined ||
                         callback.Response == EEconTradeResponse.AlreadyHasTradeRequest ||
                         callback.Response == EEconTradeResponse.AlreadyTrading ||
                         callback.Response == EEconTradeResponse.TargetAlreadyTrading ||
                         callback.Response == EEconTradeResponse.NoResponse ||
                         callback.Response == EEconTradeResponse.TooSoon ||
                         callback.Response == EEconTradeResponse.TradeBannedInitiator ||
                         callback.Response == EEconTradeResponse.TradeBannedTarget ||
                         callback.Response == EEconTradeResponse.NotLoggedIn)
                {
                    if (callback.Response == EEconTradeResponse.Cancel)
                    {
                        TradeResponse(callback.OtherClient, "had asked to trade with you, but has cancelled their request.");
                    }
                    if (callback.Response == EEconTradeResponse.ConnectionFailed)
                    {
                        TradeResponse(callback.OtherClient, "Lost connection to Steam. Reconnecting as soon as possible...");
                    }
                    if (callback.Response == EEconTradeResponse.Declined)
                    {
                        TradeResponse(callback.OtherClient, "has declined your trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.AlreadyHasTradeRequest)
                    {
                        TradeResponse(callback.OtherClient, "An error has occurred in sending the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.AlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You are already in a trade so you cannot trade someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.TargetAlreadyTrading)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade the other user because they are already in trade with someone else.");
                    }
                    if (callback.Response == EEconTradeResponse.NoResponse)
                    {
                        TradeResponse(callback.OtherClient, "did not respond to the trade request.");
                    }
                    if (callback.Response == EEconTradeResponse.TooSoon)
                    {
                        TradeResponse(callback.OtherClient, "It is too soon to send a new trade request. Try again later.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedInitiator)
                    {
                        TradeResponse(callback.OtherClient, "You are trade-banned and cannot trade.");
                    }
                    if (callback.Response == EEconTradeResponse.TradeBannedTarget)
                    {
                        TradeResponse(callback.OtherClient, "You cannot trade with this person because they are trade-banned.");
                    }
                    if (callback.Response == EEconTradeResponse.NotLoggedIn)
                    {
                        TradeResponse(callback.OtherClient, "Trade failed to initialize because you are not logged in.");
                    }
                    CloseTrade();
                }
            });
            #endregion

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

            msg.Handle <SteamClient.DisconnectedCallback> (callback =>
            {
                if (IsLoggedIn)
                {
                    IsLoggedIn = false;
                    CloseTrade();
                    log.Warn("Disconnected from Steam Network!");
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Disconnected from Steam Network! Retrying...";
                    }));
                    SteamClient.Connect();
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Connecting to Steam...";
                    }));
                }
            });
            #endregion

            if (!hasrun && IsLoggedIn)
            {
                Thread main = new Thread(GUI);
                main.Start();
                hasrun = true;
            }
        }
Beispiel #12
0
        public override void OnNewTradeOffer(TradeOffer offer)
        {
            var escrow = Bot.GetEscrowDuration(offer.TradeOfferId);

            if (escrow.DaysMyEscrow != 0 || escrow.DaysTheirEscrow != 0)
            {
                doWebWithCatch(1, () =>
                {
                    if (offer.Decline())
                    {
                        Log.Error("User has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined.");
                    }
                });
            }
            else
            {
                //Get password from file on desktop
                string pass = Bot.BotDBPassword;

                //Get items in the trade, and ID of user sending trade
                var theirItems = offer.Items.GetTheirItems();
                var myItems    = offer.Items.GetMyItems();
                var userID     = offer.PartnerSteamId;

                bool shouldDecline = false;

                //Check if they are trying to get items from the bot
                if (myItems.Count > 0 || theirItems.Count == 0)
                {
                    //shouldDecline = true;
                    Log.Error("Offer declined because the offer wasn't a gift; the user wanted items instead of giving.");
                }

                //Check to make sure all items are for CS: GO.
                foreach (TradeAsset item in theirItems)
                {
                    if (item.AppId != 730)
                    {
                        shouldDecline = true;
                        Log.Error("Offer declined because one or more items was not for CS: GO.");
                    }
                }

                //Check if there are more than 10 items in the trade
                if (theirItems.Count > 10)
                {
                    shouldDecline = true;
                    Log.Error("Offer declined because there were more than 10 items in the deposit.");
                }

                if (shouldDecline)
                {
                    doWebWithCatch(1, () =>
                    {
                        if (offer.Decline())
                        {
                            Log.Error("Offer declined.");
                        }
                    });

                    return;
                }

                Log.Success("Offer approved, accepting.");
                //Send items to server and check if all items add up to more than $1.
                //If they do, accept the trade. If they don't, decline the trade.
                string postData = "password="******"&owner=" + userID;

                string theirItemsJSON = JsonConvert.SerializeObject(theirItems);

                postData += "&items=" + theirItemsJSON;

                string url     = Bot.BotWebsiteURL + "/php/check-items.php";
                var    request = (HttpWebRequest)WebRequest.Create(url);

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

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

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

                var response = (HttpWebResponse)request.GetResponse();

                var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

                //Uncomment this line to view the response from check-items.php
                //Log.Success ("Response received from check-items.php: \n" + responseString);

                JSONClass responseJsonObj = JsonConvert.DeserializeObject <JSONClass>(responseString);

                if (responseJsonObj.success == 1)
                {
                    //Get data array from json
                    var jsonData = responseJsonObj.data;

                    if (jsonData.minDeposit == 1)
                    {
                        doWebWithCatch(10, () =>
                        {
                            if (offer.Accept())
                            {
                                Log.Success("Offer accepted from " + userID);

                                //Put items into the pot
                                string urlPutItemsIn     = Bot.BotWebsiteURL + "/php/deposit.php";
                                var requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create(urlPutItemsIn);

                                string postDataPutItemsIn = "password="******"&owner=" + userID;
                                postDataPutItemsIn       += "&items=" + jsonData.allItems;
                                //Log.Success (jsonData.allItems);

                                var dataPutItemsIn = Encoding.ASCII.GetBytes(postDataPutItemsIn);

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

                                using (var stream = requestUrlPutItemsIn.GetRequestStream())
                                {
                                    stream.Write(dataPutItemsIn, 0, dataPutItemsIn.Length);
                                }

                                var responsePutItemsIn          = (HttpWebResponse)requestUrlPutItemsIn.GetResponse();
                                string responsePutItemsInString = new StreamReader(responsePutItemsIn.GetResponseStream()).ReadToEnd();

                                //Uncomment this line to view the response from deposit.php
                                //Log.Success ("Response received from deposit.php: " + responsePutItemsInString);

                                JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject <JSONClass>(responsePutItemsInString);
                                jsonData = responseJsonObjPutItemsIn.data;
                            }
                        });

                        //Check if it should start the timer
                        if (jsonData.startTimer == 1)
                        {
                            //Check if the timer is already running.
                            if (!timerRunning)
                            {
                                timer          = new System.Timers.Timer();
                                timer.Elapsed += new ElapsedEventHandler(timerEvent);
                                timer.Interval = 1000;
                                timer.Start();

                                timerRunning = true;
                            }
                        }

                        //Check if the pot is over
                        if (jsonData.potOver == 1)
                        {
                            //End the timer
                            timerTime = 0;
                            timer.Stop();

                            //Get items to give and keep, and the winner and their trade token
                            var itemsToGive = jsonData.tradeItems;
                            var itemsToKeep = jsonData.profitItems;

                            string  winnerSteamIDString = jsonData.winnerSteamId;
                            SteamID winnerSteamID       = new SteamID(winnerSteamIDString);

                            string winnerTradeToken = jsonData.winnerTradeToken;

                            Log.Success("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken);

                            //Get bot's inventory json
                            string botInvUrl      = "http://steamcommunity.com/profiles/" + Bot.SteamUser.SteamID.ConvertToUInt64() + "/inventory/json/730/2";
                            var    botInvRequest  = (HttpWebRequest)WebRequest.Create(botInvUrl);
                            var    botInvResponse = (HttpWebResponse)botInvRequest.GetResponse();
                            string botInvString   = new StreamReader(botInvResponse.GetResponseStream()).ReadToEnd();

                            BotInventory botInventory = JsonConvert.DeserializeObject <BotInventory>(botInvString);
                            if (botInventory.success != true)
                            {
                                Log.Error("An error occured while fetching the bot's inventory.");
                                return;
                            }
                            var rgInventory = botInventory.rgInventory;

                            //Create trade offer for the winner
                            var winnerTradeOffer = Bot.NewTradeOffer(winnerSteamID);

                            //Loop through all winner's items and add them to trade
                            List <long> alreadyAddedToWinnerTrade = new List <long>();
                            foreach (CSGOItemFromWeb item in itemsToGive)
                            {
                                long classId = item.classId, instanceId = item.instanceId;

                                //Loop through all inventory items and find the asset id for the item
                                long assetId = 0;
                                foreach (var inventoryItem in rgInventory)
                                {
                                    var  value = inventoryItem.Value;
                                    long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                                    if (tClassId == classId && tInstanceId == instanceId)
                                    {
                                        //Check if this assetId has already been added to the trade
                                        if (alreadyAddedToWinnerTrade.Contains(tAssetId))
                                        {
                                            continue;
                                            //This is for when there are 2 of the same weapon, but they have different assetIds
                                        }
                                        assetId = tAssetId;
                                        break;
                                    }
                                }

                                //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                                winnerTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                                alreadyAddedToWinnerTrade.Add(assetId);
                            }
                            //Send trade offer to winner
                            if (itemsToGive.Count > 0)
                            {
                                string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on " + Bot.BotWebsiteName + "! Here are your items.";

                                doWebWithCatch(-1, () =>
                                {
                                    if (winnerTradeOffer.SendWithToken(out winnerTradeOfferId, winnerTradeToken, winnerMessage))
                                    {
                                        Bot.AcceptAllMobileTradeConfirmations();
                                        Log.Success("Offer sent to winner.");
                                    }
                                });
                            }
                            else
                            {
                                Log.Info("No items to give... strange");
                            }

                            //Now, send all of the profit items to my own account
                            //Put your own Steam ID here

                            var profitTradeOffer = Bot.NewTradeOffer(new SteamID(Bot.ProfitAdmin));

                            //Loop through all profit items and add them to trade
                            List <long> alreadyAddedToProfitTrade = new List <long>();
                            foreach (CSGOItemFromWeb item in itemsToKeep)
                            {
                                long classId = item.classId, instanceId = item.instanceId;

                                //Loop through all inventory items and find the asset id for the item
                                long assetId = 0;
                                foreach (var inventoryItem in rgInventory)
                                {
                                    var  value = inventoryItem.Value;
                                    long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid;

                                    if (tClassId == classId && tInstanceId == instanceId)
                                    {
                                        //Check if this assetId has already been added to the trade
                                        if (alreadyAddedToProfitTrade.Contains(tAssetId))
                                        {
                                            continue;
                                            //This is for when there are 2 of the same weapon, but they have different assetIds
                                        }
                                        assetId = tAssetId;
                                        break;
                                    }
                                }

                                //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId);

                                profitTradeOffer.Items.AddMyItem(730, 2, assetId, 1);
                                alreadyAddedToProfitTrade.Add(assetId);
                            }

                            //Send trade offer to myself with profit items
                            Log.Success(itemsToKeep.Count + "");
                            if (itemsToKeep.Count > 0)
                            {
                                string profitTradeOfferId, profitMessage = "Here are the profit items from the round.";

                                doWebWithCatch(10, () =>
                                {
                                    if (profitTradeOffer.Send(out profitTradeOfferId, profitMessage))
                                    { //Don't need the token because I am friends with the bot.
                                        Bot.AcceptAllMobileTradeConfirmations();
                                        Log.Success("Profit trade offer sent.");
                                    }
                                });
                            }
                        }
                        else
                        {
                            //Only try this one time, because even if it gives an error, it still gets declined.
                            doWebWithCatch(1, () =>
                            {
                                if (offer.Decline())
                                {
                                    Log.Error("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg);
                                }
                            });
                        }
                    }
                    else
                    {
                        //Only try this one time, because even if it gives an error, it still gets declined.
                        doWebWithCatch(1, () =>
                        {
                            if (offer.Decline())
                            {
                                Log.Error("Minimum deposit not reached, offer declined.");
                            }
                        });
                    }
                }
            }
        }
Beispiel #13
0
 public override void OnLoginCompleted()
 {
     Bot.AcceptAllMobileTradeConfirmations();
     Log.Success("All trade offers confirmed... on bot: " + Bot.SteamUser.SteamID.ConvertToUInt64());
 }
Beispiel #14
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
		}
        private void OnNewTradeOffer(TradeOffer offer)
        {
            var myItems    = offer.Items.GetMyItems();
            var theirItems = offer.Items.GetTheirItems();

            if (myItems.Count == 0)
            {
                offer.Accept();
                Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, "I received a donation offer!");
                Bot.AcceptAllMobileTradeConfirmations();
                Log.Success("Received a donation-offer");
            }
            else
            {
                Bot.TradeOfferEscrowDuration CurrentEscrow = Bot.GetEscrowDuration(offer.TradeOfferId);

                //Check if trader has delayed trades
                if (CurrentEscrow.DaysTheirEscrow > 2)
                {
                    Log.Error("Trade offer has been declined due to escrow.");
                    Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, "Incoming trade offer has been declined due to escrow.");
                    offer.Decline();
                }
                else
                {
                    List <long> contextId = new List <long>();
                    contextId.Add(2);
                    contextId.Add(6);

                    mySteamInventory.load(440, contextId, Bot.SteamClient.SteamID);
                    OtherSteamInventory.load(440, contextId, offer.PartnerSteamId);

                    int MyRef = 0;
                    int MyKey = 0;

                    int TheirRef = 0;
                    int TheirKey = 0;

                    #region User
                    for (int count = 0; count < theirItems.Count; count++)
                    {
                        if (theirItems[count].AppId == 440)
                        {
                            if (OtherSteamInventory.getDescription((ulong)theirItems[count].AssetId).name == "Scrap Metal")
                            {
                                TheirRef += 1;
                            }
                            else if (OtherSteamInventory.getDescription((ulong)theirItems[count].AssetId).name == "Reclaimed Metal")
                            {
                                TheirRef += 3;
                            }
                            else if (OtherSteamInventory.getDescription((ulong)theirItems[count].AssetId).name == "Refined Metal")
                            {
                                TheirRef += 9;
                            }
                            else if (OtherSteamInventory.getDescription((ulong)theirItems[count].AssetId).name == "Mann Co. Supply Crate Key")
                            {
                                TheirKey++;
                            }
                        }
                    }
                    #endregion
                    #region Bot
                    for (int count = 0; count < myItems.Count; count++)
                    {
                        if (mySteamInventory.getDescription((ulong)myItems[count].AssetId).name == "Scrap Metal")
                        {
                            MyRef += 1;
                        }
                        else if (mySteamInventory.getDescription((ulong)myItems[count].AssetId).name == "Reclaimed Metal")
                        {
                            MyRef += 3;
                        }
                        else if (mySteamInventory.getDescription((ulong)myItems[count].AssetId).name == "Refined Metal")
                        {
                            MyRef += 9;
                        }
                        else if (mySteamInventory.getDescription((ulong)myItems[count].AssetId).name == "Mann Co. Supply Crate Key")
                        {
                            MyRef += 9;
                        }
                    }
                    #endregion
                    #region Calculate
                    Console.Write(" - TheirKey: " + TheirKey);
                    Console.Write(" - Buyprice: " + buyPrice);
                    Console.WriteLine(" - MyRef: " + MyRef);
                    Console.Write(" - MyKey: " + MyKey);
                    Console.Write(" - SellPrice: " + sellPrice);
                    Console.WriteLine(" - TheirRef: " + TheirRef);
                    if (((TheirKey * buyPrice) == MyRef) && ((MyKey * sellPrice) == TheirRef))
                    {
                        Log.Success("[#" + offer.TradeOfferId + "] Accepted Offer.");
                        offer.Accept();
                        Bot.AcceptAllMobileTradeConfirmations();
                        Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, "I've done a succesful offer with " + Bot.SteamFriends.GetFriendPersonaName(offer.PartnerSteamId) + ".");
                    }
                    else if (IsAdmin)
                    {
                        string tradeid;
                        offer.Accept(out tradeid);
                        Log.Success("[ADMINOFFER] Accepted trade offer successfully : Trade ID: " + tradeid);
                        Bot.AcceptAllMobileTradeConfirmations();
                    }
                    else
                    {
                        Log.Success("[#" + offer.TradeOfferId + "] Declined Offer.");
                        offer.Decline();
                        Bot.AcceptAllMobileTradeConfirmations();
                    }
                    #endregion
                }
            }
        }
Beispiel #16
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)
                {
                    log.Error("Login Error: " + callback.Result);
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    logOnDetails.AuthCode = Console.ReadLine();
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    log.Interface("An Invalid Authorization Code was provided.  Enter the authentication code sent to the proper email: ");
                    logOnDetails.AuthCode = Console.ReadLine();
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback> (callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    if (authd)
                    {
                        log.Success("User Authenticated!");
                        break;
                    }
                    else
                    {
                        log.Warn("Authentication failed, retrying in 2s...");
                        Thread.Sleep(2000);
                    }
                }

                log.Info("Downloading Schema...");

                if (Trade.CurrentSchema == null)
                {
                    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;
            });

            // 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 (!friends.Contains(friend.SteamID))
                    {
                        friends.Add(friend.SteamID);
                        if (friend.Relationship == EFriendRelationship.PendingInvitee &&
                            GetUserHandler(friend.SteamID).OnFriendAdd())
                        {
                            SteamFriends.AddFriend(friend.SteamID);
                        }
                    }
                }
            });

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

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

            #region Trading
            msg.Handle <SteamTrading.SessionStartCallback> (callback =>
            {
                OpenTrade(callback.OtherClient);
            });

            msg.Handle <SteamTrading.TradeProposedCallback> (callback =>
            {
                if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest())
                {
                    SteamTrade.RespondToTrade(callback.TradeID, true);
                }
                else
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                }
            });

            msg.Handle <SteamTrading.TradeResultCallback> (callback =>
            {
                log.Debug("Trade Status: " + callback.Response);

                if (callback.Response == EEconTradeResponse.Accepted)
                {
                    log.Info("Trade Accepted!");
                }
                if (callback.Response == EEconTradeResponse.Cancel ||
                    callback.Response == EEconTradeResponse.ConnectionFailed ||
                    callback.Response == EEconTradeResponse.Declined ||
                    callback.Response == EEconTradeResponse.Error ||
                    callback.Response == EEconTradeResponse.InitiatorAlreadyTrading ||
                    callback.Response == EEconTradeResponse.TargetAlreadyTrading ||
                    callback.Response == EEconTradeResponse.Timeout ||
                    callback.Response == EEconTradeResponse.TooSoon ||
                    callback.Response == EEconTradeResponse.VacBannedInitiator ||
                    callback.Response == EEconTradeResponse.VacBannedTarget ||
                    callback.Response == EEconTradeResponse.NotLoggedIn) // uh...
                {
                    CloseTrade();
                }
            });
            #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
        }
Beispiel #17
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.");
					}
				}
			}
		}
Beispiel #18
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };

            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximiumActionGap    = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins      = config.Admins;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log           = new Log(config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam Bot...");
            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            log.Info("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    HandleSteamMessage(msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep(TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll();

                            if (CurrentTrade != null &&
                                CurrentTrade.OtherUserCancelled)
                            {
                                log.Info("Other user cancelled the trade.");
                                CurrentTrade = null;
                            }
                        }
                        catch (Exception e)
                        {
                            log.Error("Error Polling Trade: " + e);
                            // ok then we should stop polling...
                            CurrentTrade = null;
                        }
                    }
                }
            }).Start();

            CallbackThread.Start();
            log.Success("Done Loading Bot!");
            CallbackThread.Join();
        }
 public override void OnTradeSuccess()
 {
     Log.Success("Trade Complete. I suggest turning on email confirmations for additional security.");
     SendChatToAdmins("Completed real-time trade with user {0}: {1}", OtherSID.ToString(),
                      ActiveOrder.ToString(Trade.CurrentSchema, true));
 }
Beispiel #20
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)
                {
                    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);
                    if (authd)
                    {
                        log.Success("User Authenticated!");

                        tradeManager = new TradeManager(apiKey, sessionId, token);
                        tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                        tradeManager.OnTimeout    += OnTradeTimeout;
                        tradeManager.OnTradeEnded += OnTradeEnded;
                        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 (!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 ||
                    callback.EntryType == EChatEntryType.Emote)
                {
                    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!");
                }
                else
                {
                    log.Warn("Trade failed: " + callback.Response);
                    CloseTrade();
                    GetUserHandler(SteamClient.SteamID).OnTradeError(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
        }
Beispiel #21
0
        public Bot(Configuration.BotInfo config, Log log, string apiKey, UserHandlerCreator handlerCreator, Login _login, bool debug = false)
        {
            this.main    = _login;
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = _login.Username,
                Password = _login.Password
            };
            ChatResponse         = "";
            TradePollingInterval = 50;
            Admins      = new ulong[1];
            Admins[0]   = 123456789;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), "Debug", true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            this.log        = log;
            CreateHandler   = handlerCreator;
            BotControlClass = "SteamBot.SimpleUserHandler";

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug("Initializing Steam account...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Initializing Steam account...";
            }));
            SteamClient  = new SteamClient();
            SteamTrade   = SteamClient.GetHandler <SteamTrading>();
            SteamUser    = SteamClient.GetHandler <SteamUser>();
            SteamFriends = SteamClient.GetHandler <SteamFriends>();
            log.Info("Connecting...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Connecting to Steam...";
            }));
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    HandleSteamMessage(msg);
                }
            });

            CallbackThread.Start();
            CallbackThread.Join();
            log.Success("Done loading account!");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Done loading account!";
            }));
        }
Beispiel #22
0
        public void AddItems()
        {
            if (BotItemMap[mySteamID].Count < 1)
            {
                SendMessage("ready");
                MeAdded = true;

                if (OtherAdded)
                {
                    SetReady(true);
                }

                return;
            }

            Thread.Sleep(500);

            Log.Debug("Adding all items.");

            uint added = AddItemsFromList(BotItemMap[mySteamID]);

            if (added > 0)
            {
                Log.Success("Added " + added + " items.");
                System.Threading.Thread.Sleep(50);

                SendMessage("ready");
                MeAdded = true;
            }
            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;
                    Bot.SteamFriends.SendChatMessage(OtherSID, EChatEntryType.ChatMsg, "failed");
                    OnTradeClose();
                }
                else
                {
                    Log.Debug("No items in bot inventory. This shouldn't be possible.");
                    TradeReadyBots.Remove(mySteamID);

                    CancelTrade();
                    OnTradeClose();
                    Bot.StopBot();
                }
            }
        }
Beispiel #23
0
        public override void OnNewTradeOffer(TradeOffer offer)
        {
            var escrow = Bot.GetEscrowDuration(offer.TradeOfferId);

            Log.Success(escrow.DaysMyEscrow + " | " + escrow.DaysTheirEscrow);

            //Code for limiting pot for only specific users

            /* if (offer.PartnerSteamId.ConvertToUInt64() != 76561198020620333 && offer.PartnerSteamId.ConvertToUInt64() != 76561197995164153) {
             *      if (offer.Decline ()) {
             *              Log.Error ("Not one of the 2 verified accounts.");
             *              return;
             *      }
             * } */

            if (escrow.DaysMyEscrow != 0)
            {
                doWebWithCatch(1, () => {
                    if (offer.Decline())
                    {
                        Log.Error("This bot has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined.");
                    }
                });
            }
            else if (escrow.DaysTheirEscrow != 0)
            {
                doWebWithCatch(1, () => {
                    if (offer.Decline())
                    {
                        Log.Error("User has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined.");
                    }
                });
            }
            else
            {
                //Get password from bot configuration file
                string pass = Bot.BotDBPassword;

                //Get items in the trade, and ID of user sending trade
                var theirItems = offer.Items.GetTheirItems();
                var myItems    = offer.Items.GetMyItems();

                bool shouldDecline = false;

                //Check if they are trying to get items from the bot
                if (myItems.Count > 0 || theirItems.Count == 0)
                {
                    //shouldDecline = true;
                    Log.Error("Offer declined because the offer wasn't a gift; the user wanted items instead of giving.");
                }

                //Check to make sure all items are for CS: GO.
                foreach (TradeAsset item in theirItems)
                {
                    if (item.AppId != 730)
                    {
                        shouldDecline = true;
                        Log.Error("Offer declined because one or more items was not for CS: GO.");
                    }
                }

                //Check if there are more than 10 items in the trade
                if (theirItems.Count > 10)
                {
                    shouldDecline = true;
                    Log.Error("Offer declined because there were more than 10 items in the deposit.");
                }

                if (shouldDecline)
                {
                    doWebWithCatch(1, () => {
                        if (offer.Decline())
                        {
                            Log.Error("Offer declined.");
                        }
                    });

                    return;
                }

                Log.Success("Offer approved, accepting.");

                //Send items to server and check if all items add up to more than the minimum deposit.
                //If they do, accept the trade. If they don't, decline.
                if (timerTime <= 15)
                {
                    acceptTrade(offer);
                }
                else
                {
                    Log.Success("Offer sent within 15 seconds of round end, delaying to next round.");
                    System.Timers.Timer acceptDelayTimer = new System.Timers.Timer();
                    acceptDelayTimer.Interval = 20000;                     //20 seconds
                    acceptDelayTimer.Elapsed += delegate {
                        acceptTrade(offer);
                        acceptDelayTimer.Stop();
                    };
                    acceptDelayTimer.Start();
                }
            }
        }
Beispiel #24
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log          = new Log (config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);

                    HandleSteamMessage (msg);
                }
            });

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #25
0
        private void acceptTrade(TradeOffer offer)
        {
            string pass = Bot.BotDBPassword;

            List <TradeAsset> theirItems = offer.Items.GetTheirItems();
            SteamID           userID     = offer.PartnerSteamId;

            string postData = "password="******"&owner=" + userID;

            string theirItemsJSON = JsonConvert.SerializeObject(theirItems);

            postData += "&items=" + theirItemsJSON;

            string url     = Bot.BotWebsiteURL + "/php/check-items.php";
            var    request = (HttpWebRequest)WebRequest.Create(url);

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

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

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

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            //Uncomment this line to view the response from check-items.php
            Log.Success("Response received from check-items.php: \n" + responseString);

            JSONClass responseJsonObj = JsonConvert.DeserializeObject <JSONClass>(responseString);

            if (responseJsonObj.success == 1)
            {
                //Get data array from json
                var jsonData = responseJsonObj.data;

                if (jsonData.minDeposit == 1)
                {
                    doWebWithCatch(10, () => {
                        if (offer.Accept())
                        {
                            Log.Success("Offer accepted from " + userID);

                            //Put items into the pot
                            string urlPutItemsIn     = Bot.BotWebsiteURL + "/php/deposit.php";
                            var requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create(urlPutItemsIn);

                            string postDataPutItemsIn = "password="******"&owner=" + userID;
                            postDataPutItemsIn       += "&items=" + jsonData.allItems;
                            //Log.Success (jsonData.allItems);

                            var dataPutItemsIn = Encoding.ASCII.GetBytes(postDataPutItemsIn);

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

                            using (var stream = requestUrlPutItemsIn.GetRequestStream()) {
                                stream.Write(dataPutItemsIn, 0, dataPutItemsIn.Length);
                            }

                            var responsePutItemsIn          = (HttpWebResponse)requestUrlPutItemsIn.GetResponse();
                            string responsePutItemsInString = new StreamReader(responsePutItemsIn.GetResponseStream()).ReadToEnd();

                            //Uncomment this line to view the response from deposit.php
                            //Log.Success ("Response received from deposit.php: " + responsePutItemsInString);

                            JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject <JSONClass> (responsePutItemsInString);
                            jsonData = responseJsonObjPutItemsIn.data;
                        }
                    });

                    //Check if it should start the timer
                    if (jsonData.startTimer == 1)
                    {
                        //Check if the timer is already running.
                        if (!timerRunning)
                        {
                            timer          = new System.Timers.Timer();
                            timer.Elapsed += new ElapsedEventHandler(timerEvent);
                            timer.Interval = 1000;
                            timer.Start();

                            timerRunning = true;
                        }
                    }

                    //Check if the pot is over
                    if (jsonData.potOver == 1)
                    {
                        //End the timer
                        timerTime = 0;
                        timer.Stop();

                        sendWinnings(responseJsonObj);
                    }
                    else
                    {
                        //Only try this one time, because even if it gives an error, it still gets declined.
                        doWebWithCatch(1, () => {
                            if (offer.Decline())
                            {
                                Log.Error("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg);
                            }
                        });
                    }
                }
                else
                {
                    //Only try this one time, because even if it gives an error, it still gets declined.
                    doWebWithCatch(1, () => {
                        if (offer.Decline())
                        {
                            Log.Error("Minimum deposit not reached, offer declined.");
                        }
                    });
                }
            }
            else
            {
                doWebWithCatch(1, () => {
                    if (offer.Decline())
                    {
                        Log.Error("The depositor's inventory could not be accessed.");
                    }
                });
            }
        }
Beispiel #26
0
        public void OnMessageHandler(string message, EChatEntryType type)
        {
            _lastMessageWasFromTrade = false;
            if (!HandleWaitingOnUserResponse(message))
            {
                if (message[0] == '/')
                {
                    string   command     = message.Substring(1);
                    string   commandName = command.Split(' ')[0];
                    string[] commandArgs = new string[0];
                    if (command.Contains(" "))
                    {
                        commandArgs = command.Split(' ').Skip(1).ToArray();
                    }
                    switch (commandName)
                    {
                    case "dummy":
                        ChatCommand dummyCommand = new ChatCommand(2);
                        Log.Success("Dummycall successful!");
                        dummyCommand.Parse(message);
                        foreach (var s in dummyCommand.GetArguments())
                        {
                            Log.Success(s);
                        }
                        break;

                    case "comment":
                        try
                        {
                            string  comment_id      = commandArgs[0];
                            SteamID comment_steamId = new SteamID((ulong.Parse(comment_id)));
                            string  comment_message = commandArgs[1];
                            var     success         = PostProfileComment(comment_steamId, comment_message);
                            if (success == HttpStatusCode.OK)
                            {
                                SendReplyMessage("Posted comment \"" + comment_message + "\" on " + comment_steamId.ToString() + "'s profile.");
                            }
                            else
                            {
                                SendReplyMessage("Commandexecution failed. Statuscode: " + success);
                            }
                        }
                        catch (Exception e)
                        {
                            SendReplyMessage("Command execution failed. Command requires (string)steamid (string)message.");
                        }
                        break;

                    case "game":
                        ChatCommand gameCommand = new ChatCommand(1);
                        gameCommand.Parse(message);
                        string game_arg = gameCommand.GetArgument(0);
                        if (game_arg == "stop")
                        {
                            Bot.SetGamePlaying(0);
                            SendReplyMessage("Stopped game simulation");
                        }
                        else
                        {
                            try
                            {
                                Bot.SetGamePlaying(int.Parse(game_arg));
                                SendReplyMessage("Started simulating gameplay of " + game_arg);
                            }
                            catch (Exception e)
                            {
                                SendReplyMessage(e.ToString());
                            }
                        }
                        break;

                    default:
                        SendReplyMessage("Command execution failed. Command not found.");
                        break;
                    }
                }
                else if (message.Contains("+csgo_econ_action_preview"))
                {
                    Bot.RequestFloat(message, PrintFloat);
                }
                OnMessage(message, type);
            }
        }
Beispiel #27
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            Username     = config.Username;
            Password     = config.Password;
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            AuthCode     = null;
            log          = new Log (config.LogFile, this);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);
                    HandleSteamMessage (msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep (TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll ();
                        }
                        catch (Exception e)
                        {
                            log.Error ("Error Polling Trade: " + e);
                        }
                    }
                }
            }).Start ();

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #28
0
        public Bot(Configuration.BotInfo config, Log log, string apiKey, UserHandlerCreator handlerCreator, Login _login, bool debug = false)
        {
            this.main = _login;
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = _login.Username,
                Password = _login.Password
            };
            ChatResponse = "";
            TradePollingInterval = 500;
            Admins = new ulong[1];
            Admins[0] = 0;
            this.apiKey = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), "Debug", true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            this.log = log;
            CreateHandler = handlerCreator;
            BotControlClass = "SteamBot.SimpleUserHandler";

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam account...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Initializing Steam account...";
            }));
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new ClientPlayerNicknameListHandler());
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
            SteamNicknames = SteamClient.GetHandler<ClientPlayerNicknameListHandler>();
            log.Info ("Connecting...");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Connecting to Steam...";
            }));
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback(true);

                    new Thread(() => HandleSteamMessage(msg)).Start();
                }
            });

            CallbackThread.Start();
            CallbackThread.Join();
            log.Success("Done loading account!");
            main.Invoke((Action)(() =>
            {
                main.label_status.Text = "Done loading account!";
            }));
        }
Beispiel #29
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            Username     = config.Username;
            Password     = config.Password;
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            AuthCode     = null;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log          = new Log (config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();

            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);
                    HandleSteamMessage (msg);
                }
            });

            new Thread(() => // Trade Polling if needed
            {
                while (true)
                {
                    Thread.Sleep (TradePollingInterval);
                    if (CurrentTrade != null)
                    {
                        try
                        {
                            CurrentTrade.Poll ();

                            if (CurrentTrade.OtherUserCancelled)
                            {
                                log.Info("Other user cancelled the trade.");
                                CurrentTrade = null;
                            }
                        }
                        catch (Exception e)
                        {
                            log.Error ("Error Polling Trade: " + e);
                            // ok then we should stop polling...
                            CurrentTrade = null;
                        }
                    }
                }
            }).Start ();

            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }
Beispiel #30
0
        public override void OnTradeInit()
        {
            Log.Success("Trade Started");

            Bot.SteamFriends.SendChatMessage(OtherSID, EChatEntryType.ChatMsg, "initialized");
        }
        public override void OnMessage(string message, EChatEntryType type)
        {
            message = message.ToLower();
            Log.Success(Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " : " + message);
            Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " : " + message);
            #region Buy
            if (message.StartsWith("!buy"))
            {
                if (message == "!buy")
                {
                    SendChatMessage("You have to put a amount in. Ex: !buy 2 for buying 2 keys.");
                }
                else
                {
                    bool notEnough = false;
                    SendChatMessage("Your request will be dealt with shortly.");
                    int amount = 0;

                    if (message.Substring(6) == "x")
                    {
                        amount = 0;
                        SendChatMessage("You didn't enter a number. Ex: !buy 2 for buying 2 keys.");
                    }
                    else
                    {
                        try
                        {
                            amount = int.Parse(message.Substring(5));
                        }
                        catch
                        {
                            SendChatMessage("You didn't put a valid number in. Example: !buy 2 for buying 2 keys");
                        }
                    }
                    // Check if the user has escrow.
                    if (Bot.GetEscrowDuration(new SteamID(OtherSID), "").DaysTheirEscrow > 2)
                    {
                        SendChatMessage("Sorry, You require to have an account with a valid Phone Authenticator.");
                    }
                    else
                    {
                        // Bot adds keys. User adds metal.

                        List <long> contextId = new List <long>();
                        contextId.Add(2);
                        contextId.Add(6);

                        mySteamInventory.load(440, contextId, Bot.SteamClient.SteamID);
                        OtherSteamInventory.load(440, contextId, OtherSID);

                        #region User-part
                        //Checking users stock.
                        int UserRefCount   = 0;
                        int UserRecCount   = 0;
                        int UserScrapCount = 0;
                        int KeysInStock    = 0;
                        foreach (GenericInventory.Item item in OtherSteamInventory.items.Values)
                        {
                            if (OtherSteamInventory.getDescription(item.assetid).name == "Refined Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                UserRefCount++;
                            }
                            else if (OtherSteamInventory.getDescription(item.assetid).name == "Reclaimed Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                UserRecCount++;
                            }
                            else if (OtherSteamInventory.getDescription(item.assetid).name == "Scrap Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                UserScrapCount++;
                            }
                        }

                        int     MetalRequired       = amount * sellPrice;
                        int     OfferChangeRequired = 0;
                        decimal RefRequired         = Math.Floor((decimal)MetalRequired / 9);
                        if (UserRefCount < RefRequired)
                        {
                            RefRequired = UserRefCount;
                        }
                        decimal metalRequiredR = MetalRequired - (RefRequired * 9);
                        decimal RecRequired    = Math.Floor((decimal)metalRequiredR / 3);
                        if (UserRecCount < RecRequired)
                        {
                            RecRequired = UserRecCount;
                        }
                        decimal ScrapRequired = metalRequiredR - (RecRequired * 3);
                        if (UserScrapCount < ScrapRequired)
                        {
                            while (UserScrapCount < ScrapRequired)
                            {
                                RecRequired++;
                                ScrapRequired -= 3;
                                if (ScrapRequired < 0)
                                {
                                    OfferChangeRequired = (int)ScrapRequired * -1;
                                    ScrapRequired       = 0;
                                }
                            }
                        }
                        if (UserRecCount < RecRequired)
                        {
                            while (UserRecCount < RecRequired)
                            {
                                if (UserRefCount > RefRequired)
                                {
                                    RefRequired++;
                                    RecRequired -= 3;
                                    if (RecRequired < 0)
                                    {
                                        OfferChangeRequired = ((int)RecRequired * -1) * 3;
                                        RecRequired         = 0;
                                    }
                                }
                                else
                                {
                                    ScrapRequired += 3;
                                    RecRequired--;
                                }
                            }
                        }

                        var offer = Bot.NewTradeOffer(OtherSID);

                        foreach (GenericInventory.Item item in OtherSteamInventory.items.Values)
                        {
                            if (OtherSteamInventory.getDescription(item.assetid).name == "Refined Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                if (RefRequired > 0)
                                {
                                    offer.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid);
                                    RefRequired--;
                                }
                            }
                            else if (OtherSteamInventory.getDescription(item.assetid).name == "Reclaimed Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                if (RecRequired > 0)
                                {
                                    offer.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid);
                                    RecRequired--;
                                }
                            }
                            else if (OtherSteamInventory.getDescription(item.assetid).name == "Scrap Metal" && OtherSteamInventory.getDescription(item.assetid).tradable)
                            {
                                if (ScrapRequired > 0)
                                {
                                    offer.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid);
                                    ScrapRequired--;
                                }
                            }
                            if (RefRequired == 0 && RecRequired == 0 && ScrapRequired == 0)
                            {
                                break;
                            }
                        }
                        if (!(RefRequired == 0 && RecRequired == 0 && ScrapRequired == 0))
                        {
                            notEnough = true;
                            SendChatMessage("Sorry, You dont have enough metal. (You need " + string.Format("{0:0.000}", (int.Parse("" + ScrapRequired) / 9.0)).Substring(0, 4) + " Scrap more.)");
                        }
                        foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                        {
                            if (mySteamInventory.getDescription(item.assetid).name == "Mann Co. Supply Crate Key" && mySteamInventory.getDescription(item.assetid).tradable)
                            {
                                KeysInStock++;
                            }
                        }
                        if (amount > KeysInStock)
                        {
                            SendChatMessage("Sorry, I dont have enough keys in stock. (Current stock: " + KeysInStock + " keys).");
                            notEnough = true;
                        }
                        #endregion
                        #region BotPart
                        if (!notEnough)
                        {
                            int KeysRemaining = amount;
                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (KeysRemaining > 0)
                                {
                                    if (mySteamInventory.getDescription(item.assetid).name == "Mann Co. Supply Crate Key" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        KeysRemaining--;
                                    }
                                }
                                if (OfferChangeRequired >= 9)
                                {
                                    if (mySteamInventory.getDescription(item.assetid).name == "Refined Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        OfferChangeRequired -= 9;
                                    }
                                }
                            }
                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (OfferChangeRequired >= 3 && OfferChangeRequired < 9)
                                {
                                    if (mySteamInventory.getDescription(item.assetid).name == "Reclaimed Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        OfferChangeRequired -= 3;
                                    }
                                }
                            }

                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (OfferChangeRequired >= 1 && OfferChangeRequired < 3)
                                {
                                    if (mySteamInventory.getDescription(item.assetid).name == "Scrap Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        OfferChangeRequired -= 1;
                                    }
                                }
                            }
                            if (KeysRemaining != 0 && OfferChangeRequired != 0)
                            {
                                SendChatMessage("Sorry, I dont have enough stock to send this order.");
                            }

                            #endregion
                            #region Sending Offer..
                            else
                            {
                                if (offer.Items.NewVersion)
                                {
                                    string newOfferId;
                                    if (offer.Send(out newOfferId, "Please leave a +rep if liked it!"))
                                    {
                                        Bot.AcceptAllMobileTradeConfirmations();
                                        SendChatMessage("Thanks for trading with us.Your order (" + amount + " keys) has been sent.");
                                        //SendChatMessage("If you like a comment from me, Send me \"+rep\" in the chat.");
                                        SendChatMessage("You can accept it here: https://steamcommunity.com/tradeoffer/" + newOfferId + "/");
                                        Log.Success("Trade offer sent : Offer ID " + newOfferId);
                                        Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, "I've sold a key to " + Bot.SteamFriends.GetFriendPersonaName(OtherSID));
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
            }
            #endregion
            #region Sell
            else if (message.StartsWith("!sell"))
            {
                if (message == "!sell")
                {
                    SendChatMessage("You have to put a amount in. Ex: !sell 2 for selling 2 keys.");
                }
                else
                {
                    bool notEnough = false;
                    SendChatMessage("Your request will be dealt with shortly.");
                    int amount = 0;
                    if (message.Substring(6) == "x")
                    {
                        amount = 0;
                        SendChatMessage("You didn't enter a number. Ex: !sell 2 for selling 2 keys.");
                    }
                    else
                    {
                        try
                        {
                            amount = int.Parse(message.Substring(6));
                        }
                        catch
                        {
                            SendChatMessage("You didn't put a valid number in. Example: !sell 2 for selling 2 keys");
                        }
                    }
                    // Check if the user has escrow.
                    if (Bot.GetEscrowDuration(new SteamID(OtherSID), "").DaysTheirEscrow > 2)
                    {
                        SendChatMessage("Sorry, You require to have an account with a valid Phone Authenticator.");
                    }
                    else
                    {
                        List <long> contextId = new List <long>();
                        contextId.Add(2);
                        contextId.Add(6);

                        mySteamInventory.load(440, contextId, Bot.SteamClient.SteamID);
                        OtherSteamInventory.load(440, contextId, OtherSID);
                        int KeysRequired  = amount;
                        int MetalRequired = amount * buyPrice;
                        var offer         = Bot.NewTradeOffer(OtherSID);
                        #region User-part
                        //Checking users stock.
                        foreach (GenericInventory.Item item in OtherSteamInventory.items.Values)
                        {
                            if (KeysRequired != 0)
                            {
                                if (OtherSteamInventory.getDescription(item.assetid).name == "Mann Co. Supply Crate Key" && OtherSteamInventory.getDescription(item.assetid).tradable)
                                {
                                    offer.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid);
                                    KeysRequired--;
                                }
                            }
                        }
                        if (KeysRequired != 0)
                        {
                            SendChatMessage("You dont have enough keys available for selling " + amount + " keys.");
                            notEnough = true;
                        }
                        #endregion
                        #region Bot-part
                        else
                        {
                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (mySteamInventory.getDescription(item.assetid).name == "Refined Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                {
                                    if (MetalRequired >= 9)
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        MetalRequired -= 9;
                                    }
                                }
                            }
                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (mySteamInventory.getDescription(item.assetid).name == "Reclaimed Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                {
                                    if (MetalRequired >= 3 && MetalRequired <= 8)
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        MetalRequired -= 3;
                                    }
                                }
                            }
                            foreach (GenericInventory.Item item in mySteamInventory.items.Values)
                            {
                                if (mySteamInventory.getDescription(item.assetid).name == "Scrap Metal" && mySteamInventory.getDescription(item.assetid).tradable&& !UsedAssetIDs.Contains(item.assetid))
                                {
                                    if (MetalRequired >= 1 && MetalRequired < 9)
                                    {
                                        offer.Items.AddMyItem(item.appid, item.contextid, (long)item.assetid);
                                        MetalRequired -= 1;
                                    }
                                }
                            }
                            if (MetalRequired != 0)
                            {
                                Console.WriteLine(MetalRequired);
                                SendChatMessage("I dont have enough metal.");
                            }
                            #endregion
                            #region Sending Offer..
                            else
                            {
                                if (offer.Items.NewVersion)
                                {
                                    string newOfferId;
                                    offer.Send(out newOfferId, "Please leave a +rep if liked it!");
                                    if (!(newOfferId == null || newOfferId == String.Empty))
                                    {
                                        Bot.AcceptAllMobileTradeConfirmations();
                                        SendChatMessage("Thanks for trading with us. Your order (" + amount + " keys) has been sent.");
                                        SendChatMessage("You can accept it here: https://steamcommunity.com/tradeoffer/" + newOfferId + "/");
                                        Log.Success("Trade offer sent : Offer ID " + newOfferId);
                                        Bot.SteamFriends.SendChatMessage(ownerID, EChatEntryType.ChatMsg, "I've bought a key from " + Bot.SteamFriends.GetFriendPersonaName(OtherSID));
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
            #endregion
            #region Help
            else if (message.Contains("help"))
            {
                SendChatMessage("For first you have to check if I have keys or metals in my inventory. You can do it by writing \"stock\" (without quotation marks) to me. Also dont forget to check current price by writing \"price\". If you do this and you're sure I have things you want in my stock and you agree with price, use command \"!buy x\" or \"!sell x\" - \"x\" is amount of goods you want to buy. Right after doing that bot will send you trade offer with key(s) and metals.");
                SendChatMessage("*Example* - you want to buy 2 keys, so write !buy 2 and wait for offer.");
            }
            #endregion
            #region Stock
            else if (message.Contains("stock"))
            {
                int StockScrap     = 0;
                int StockReclaimed = 0;
                int StockRefined   = 0;
                int StockKey       = 0;
                Bot.GetInventory();
                Inventory myInventory = Bot.MyInventory;
                foreach (Inventory.Item item in myInventory.Items)
                {
                    if (item.Defindex == 5000)
                    {
                        StockScrap++;
                    }
                    else if (item.Defindex == 5001)
                    {
                        StockReclaimed++;
                    }
                    else if (item.Defindex == 5002)
                    {
                        StockRefined++;
                    }
                    else if (item.Defindex == 5021)
                    {
                        StockKey++;
                    }
                }
                if ((StockScrap / 9.0) + (StockReclaimed / 3.0) + (StockRefined) < 10)
                {
                    Bot.SteamFriends.SendChatMessage(OtherSID, EChatEntryType.ChatMsg, "I have : " + string.Format("{0:0.000}", (StockScrap / 9.0) + (StockReclaimed / 3.0) + (StockRefined)).Substring(0, 4) + " refined. (" + StockRefined + " refined, " + StockReclaimed + " reclaimed, " + StockScrap + " scrap) and " + StockKey + " key(s).");
                }
                else
                {
                    Bot.SteamFriends.SendChatMessage(OtherSID, EChatEntryType.ChatMsg, "I have : " + string.Format("{0:0.000}", (StockScrap / 9.0) + (StockReclaimed / 3.0) + (StockRefined)).Substring(0, 5) + " refined. (" + StockRefined + " refined, " + StockReclaimed + " reclaimed, " + StockScrap + " scrap) and " + StockKey + " key(s).");
                }
            }
            #endregion
            #region Price
            else if (message.Contains("price") || message == ("p") || message.Contains("buying") || message.Contains("selling"))
            {
                Bot.SteamFriends.SendChatMessage(OtherSID, type, "I'm buying keys for " + string.Format("{0:0.000}", buyPrice / 9.0).Substring(0, 5) + " refined, and selling for " + string.Format("{0:0.000}", sellPrice / 9.0).Substring(0, 5) + " refined.");
            }
            #endregion
            #region Owner
            else if (message.Contains("owner") || message.Contains("mod") || message.Contains("admin"))
            {
                SendChatMessage("My owner is Krypton. ( https://steamcommunity.com/id/KryptonGas )");
            }
            #endregion
            #region Group
            else if (message.Contains("group") || message.Contains("community"))
            {
                SendChatMessage("You can get latest info, updates and helpful things in our group. ( http://steamcommunity.com/groups/TF2bot )");
            }
            #endregion
            #region Play
            else if (message.Contains(".play"))
            {
                if (IsAdmin)
                {
                    string PlayID = message.Substring(6);
                    if (PlayID.Contains("list"))
                    {
                        //List of GameIDs
                        Bot.SteamFriends.SendChatMessage(OtherSID, type, "List of GameIDs:");
                        Bot.SteamFriends.SendChatMessage(OtherSID, type, "440. Team Fortress 2");
                        Bot.SteamFriends.SendChatMessage(OtherSID, type, "570. Dota 2");
                        Bot.SteamFriends.SendChatMessage(OtherSID, type, "301520. RoboCraft");
                    }
                    if (PlayID.Contains("n"))
                    {
                        //No, None, Nothing etc.
                        Bot.SetGamePlaying(0);
                    }
                    else
                    {
                        // Play-Part
                        int PlayMessage = Int32.Parse(PlayID);
                        Bot.SetGamePlaying(PlayMessage);
                    }
                }

                else
                {
                    Bot.SteamFriends.SendChatMessage(OtherSID, type, "No.");
                }
            }
            #endregion
            #region Trade
            else if (message.Contains("trade"))
            {
                SendChatMessage("Sorry, You can't trade with normal trading, Use trade offers instead, Do command \"help\" to know how!");
            }
            #endregion
            #region Escrow
            else if (message.Contains("escrow") || (message.Contains("hold") && message.Contains("trade")))
            {
                bool HasEscrow = Bot.GetEscrowDuration(new SteamID(OtherSID), "").DaysTheirEscrow > 0;
                if (HasEscrow)
                {
                    SendChatMessage("You have escrow :( , Which means you are unable to trade with this bot.");
                    SendChatMessage("You can find more information about activating Phone Authentication here: https://support.steampowered.com/kb_article.php?ref=4440-RTUI-9218 .");
                }
                else
                {
                    SendChatMessage("You have no escrow!!! You are able to trade with this bot!");
                }
            }
            #endregion
            #region getauth
            else if (message == "getauth")
            {
                if (IsAdmin)
                {
                    try
                    {
                        SendChatMessage("Generated Steam Guard code: " + Bot.SteamGuardAccount.GenerateSteamGuardCode());
                    }
                    catch (NullReferenceException)
                    {
                        SendChatMessage("Unable to generate Steam Guard code.");
                    }
                }
            }
            #endregion
            #region Else
            else
            {
                SendChatMessage("Sorry, I dont know what you mean.. Available commands: \"!buy\", \"!sell\", \"help\", \"stock\", \"price\", \"owner\", \"group\".");
            }
            #endregion
        }
Beispiel #32
0
 public override bool OnTradeRequest()
 {
     Log.Success("Trade request made");
     return(false);
 }
Beispiel #33
0
 public override void OnTradeSuccess()
 {
     // Trade completed successfully
     Log.Success("Trade Complete.");
 }
Beispiel #34
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false)
        {
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName  = config.DisplayName;
            ChatResponse = config.ChatResponse;
            MaximumTradeTime = config.MaximumTradeTime;
            MaximiumActionGap = config.MaximumActionGap;
            DisplayNamePrefix = config.DisplayNamePrefix;
            TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            hatBuyPrice= config.HatBuyPrice;
            hatSellPrice= config.HatSellPrice;
            maxRequestTime= config.MaxRequestTime;
            craftHatSellPrice = config.CraftHatSellPrice;
            Admins       = config.Admins;
            this.apiKey  = apiKey;
            try
            {
                LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'");
                LogLevel = Log.LogLevel.Info;
            }
            log          = new Log (config.LogFile, this.DisplayName, LogLevel);
            CreateHandler = handlerCreator;
            BotControlClass = config.BotControlClass;

            // Hacking around https
            ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;

            log.Debug ("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamTrade = SteamClient.GetHandler<SteamTrading>();
            SteamUser = SteamClient.GetHandler<SteamUser>();
            SteamFriends = SteamClient.GetHandler<SteamFriends>();
            log.Info ("Connecting...");
            SteamClient.Connect();
            
            Thread CallbackThread = new Thread(() => // Callback Handling
            {
                while (true)
                {
                    CallbackMsg msg = SteamClient.WaitForCallback (true);

                    HandleSteamMessage (msg);
                }
            });
            new Thread(() =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);
                        if (currentRequest.User != null)
                        {
                            DateTime RequestTimeout = RequestTime.AddSeconds(maxRequestTime);
                            int untilTradeTimeout = (int)Math.Round((RequestTimeout - DateTime.Now).TotalSeconds);
                            if (untilTradeTimeout <= 0 && (MySQL.getItem().User != null))
                            {
                                SteamFriends.SendChatMessage(currentRequest.User, EChatEntryType.ChatMsg, "Sorry, but your request took too long");
                                NewRequest(MySQL.RequestStatus.Timedout);
                                log.Warn("Request timedout");
                            }
                        }
                    }
                }).Start();
            CallbackThread.Start();
            log.Success ("Done Loading Bot!");
            CallbackThread.Join();
        }