Ejemplo n.º 1
0
        void UserWebLogOn()
        {
            do
            {
                IsLoggedIn = SteamWeb.Authenticate(MyUniqueId, SteamClient, MyUserNonce);

                if (!IsLoggedIn)
                {
                    log.Warn("Authentication failed, retrying in 2s...");
                    Thread.Sleep(2000);
                }
            } while(!IsLoggedIn);

            log.Success("User Authenticated!");

            tradeManager = new TradeManager(ApiKey, SteamWeb);
            tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
            tradeManager.OnTimeout += OnTradeTimeout;

            tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb);
            SubscribeTradeOffer(tradeOfferManager);

            CookiesAreInvalid = false;

            // Success, check trade offers which we have received while we were offline
            tradeOfferManager.GetOffers();
        }
Ejemplo n.º 2
0
        void UserWebLogOn()
        {
            while (true)
            {
                bool authd = SteamWeb.Authenticate(MyUniqueId, SteamClient, out sessionId, out token, out tokensecure, MyUserNonce);

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

                    tradeManager = new TradeManager(apiKey, sessionId, token);
                    tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval);
                    tradeManager.OnTimeout += OnTradeTimeout;

                    tradeOfferManager = new TradeOfferManager(apiKey, sessionId, token, tokensecure);
                    SubscribeTradeOffer(tradeOfferManager);

                    CookiesAreInvalid = false;

                    // Success, check trade offers which we have received while we were offline
                    tradeOfferManager.GetOffers();

                    break;
                }
                else
                {
                    log.Warn("Authentication failed, retrying in 2s...");
                    Thread.Sleep(2000);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Checks if sessionId and token cookies are still valid.
        /// Sets cookie flag if they are invalid.
        /// </summary>
        /// <returns>true if cookies are valid; otherwise false</returns>
        bool CheckCookies()
        {
            // We still haven't re-authenticated
            if (CookiesAreInvalid)
            {
                return(false);
            }

            try
            {
                if (!SteamWeb.VerifyCookies())
                {
                    // Cookies are no longer valid
                    log.Warn("Cookies are invalid. Need to re-authenticate.");
                    CookiesAreInvalid = true;
                    SteamUser.RequestWebAPIUserNonce();
                    return(false);
                }
            }
            catch
            {
                // Even if exception is caught, we should still continue.
                log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
            }

            return(true);
        }
Ejemplo n.º 4
0
        void HandleLoginKey(CallbackMsg msg)
        {
            var details = msg as SteamUser.LoginKeyCallback;

            //Logger.WriteLine("Login Key: " + details.LoginKey);

            Logger.WriteLine("Logging to the Steam Web network...");
            SteamWeb.LogOn(details);
        }
Ejemplo n.º 5
0
 public void Initialize(bool useUDP)
 {
     SteamClient  = new SteamClient(useUDP ? ProtocolType.Udp : ProtocolType.Tcp);
     SteamFriends = SteamClient.GetHandler <SteamFriends>();
     SteamUser    = SteamClient.GetHandler <SteamUser>();
     SteamTrading = SteamClient.GetHandler <SteamTrading>();
     SteamWeb     = SteamClient.GetHandler <SteamWeb>();
     SteamGC      = SteamClient.GetHandler <SteamGameCoordinator>();
 }
Ejemplo n.º 6
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = 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;
            SchemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins         = config.Admins;
            this.ApiKey    = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            this.isprocess = process;

            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;
            SteamWeb        = new SteamWeb();

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

            log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            backgroundWorker = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            backgroundWorker.DoWork             += BackgroundWorkerOnDoWork;
            backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            backgroundWorker.RunWorkerAsync();
        }
Ejemplo n.º 7
0
        public static void InviteToGroup(ulong invitee, string gid, string groupname, TextBox text_log, Label label_invite)
        {
            CookieContainer cookies = new CookieContainer();

            cookies.Add(new Cookie("sessionid", Bot.sessionId, String.Empty, "steamcommunity.com"));
            cookies.Add(new Cookie("steamLogin", Bot.token, String.Empty, "steamcommunity.com"));
            var data = new NameValueCollection();

            data.Add("type", "groupInvite");
            data.Add("inviter", Bot.SteamUser.SteamID.ConvertToUInt64().ToString());
            data.Add("invitee", invitee.ToString());
            data.Add("group", gid);
            data.Add("sessionID", Bot.sessionId);
            try
            {
                HttpWebResponse webResponse = SteamWeb.Request("http://steamcommunity.com/actions/GroupInvite", "POST", data, cookies, false);
                Stream          response    = null;
                response = webResponse.GetResponseStream();
                StreamReader reader = new StreamReader(response);
                string       result = reader.ReadToEnd();
                if (result.Contains("![CDATA[OK]]"))
                {
                    Interface.AppendText(text_log, "\r\nSuccess!\n");
                    Console.WriteLine("Success.");
                    blacklist(invitee, groupname);
                    successfulInvite++;
                }
                else
                {
                    int    start  = result.IndexOf("![CDATA[");
                    int    stop   = result.IndexOf("]]");
                    string output = result.Substring(start + 8, stop - start - 8);
                    Interface.AppendText(text_log, "\r\nError: " + output + "\n");
                    Console.WriteLine("Error: " + output);
                    blacklist(invitee, groupname);
                }
            }
            catch
            {
                Interface.UpdateLabel(label_invite, "Failed to get response; retrying...");
                InviteToGroup(invitee, gid, groupname, text_log, label_invite);
            }
        }
Ejemplo n.º 8
0
        public void Bump()
        {
            UpdateRaffleDetails();
            var data = new System.Collections.Specialized.NameValueCollection();

            data.Add("sessionID", Bot.SteamWeb.SessionId);
            data.Add("action", "post");
            data.Add("headline", title);
            data.Add("body", body);
            foreach (string url in urls)
            {
                try
                {
                    var response = SteamWeb.Fetch(url, "post", data, true, "");
                }
                catch
                {
                    Bot.Log.Error("Error while posting announcement. " + url);
                }
            }
            Bot.Log.Success("All announcements bumped");
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Checks if sessionId and token cookies are still valid.
        /// Sets cookie flag if they are invalid.
        /// </summary>
        /// <returns>true if cookies are valid; otherwise false</returns>
        bool CheckCookies()
        {
            // We still haven't re-authenticated
            if (CookiesAreInvalid)
            {
                return(false);
            }

            // Construct cookie container
            CookieContainer cookies = new CookieContainer();

            cookies.Add(new Cookie("sessionid", sessionId, String.Empty, "steamcommunity.com"));
            cookies.Add(new Cookie("steamLogin", token, String.Empty, "steamcommunity.com"));

            try
            {
                if (!SteamWeb.VerifyCookies(cookies))
                {
                    // Cookies are no longer valid
                    log.Warn("Cookies are invalid. Need to re-authenticate.");
                    CookiesAreInvalid = true;
                    SteamUser.RequestWebAPIUserNonce();
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch
            {
                // Even if exception is caught, we should still continue.
                log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
                return(true);
            }
        }
Ejemplo n.º 10
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;
            }
        }
Ejemplo n.º 11
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false,
                   bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = _sec_RetrievePassword(config.Username)
            };
            DisplayName           = config.DisplayName;
            ChatResponse          = config.ChatResponse;
            MaximumTradeTime      = config.MaximumTradeTime;
            MaximumActionGap      = config.MaximumActionGap;
            DisplayNamePrefix     = config.DisplayNamePrefix;
            _tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang            = config.SchemaLang != null ? config.SchemaLang : "en_US";
            Admins     = config.Admins;
            ApiKey     = !string.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine("(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be " +
                                      "removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to 'Info'", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile         = config.LogFile;
            Log             = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel);
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

            Orders = OrderManager.Load(Log);

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

            Log.Debug("Initializing Steam Bot...");

            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            CallbackMgr = new CallbackManager(SteamClient);

            EventMgr = new EventManager(this, CallbackMgr);

            botSteamThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botSteamThread.DoWork             += _backgroundWorkerOnDoWork;
            botSteamThread.RunWorkerCompleted += _backgroundWorkerOnRunWorkerCompleted;
            botSteamThread.RunWorkerAsync();

            heartBeatThread      = new Thread(HeartbeatLoop);
            heartBeatThread.Name = "bp.tf Heartbeat Thread: " + config.Username;
            heartBeatThread.Start();

            crafterThread      = new Thread(CrafterLoop);
            crafterThread.Name = "Crafting Loop Thread: " + config.Username;
            crafterThread.Start();
        }
Ejemplo n.º 12
0
        public static void Main(string[] args)
        {
            #region SteamRE Init
            AllArgs = args;

            //Hacking around https
            ServicePointManager.CertificatePolicy = new MainClass();

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("\n\tSteamBot Beta\n\tCreated by Jessecar96.\n\n");
            Console.ForegroundColor = ConsoleColor.White;


            steamClient = new SteamClient();
            steamTrade  = steamClient.GetHandler <SteamTrading>();
            SteamUser steamUser = steamClient.GetHandler <SteamUser> ();
            steamFriends = steamClient.GetHandler <SteamFriends>();

            steamClient.Connect();
            #endregion


            while (true)
            {
                CallbackMsg msg = steamClient.WaitForCallback(true);

                //Console Debug
                printConsole(msg.ToString(), ConsoleColor.Blue, true);


                #region Logged Off Handler
                msg.Handle <SteamUser.LoggedOffCallback> (callback =>
                {
                    printConsole("Logged Off: " + callback.Result, ConsoleColor.Red);
                });
                #endregion


                #region Steam Disconnect Handler
                msg.Handle <SteamClient.DisconnectedCallback> (callback =>
                {
                    printConsole("Disconnected.", ConsoleColor.Red);
                });
                #endregion


                #region Steam Connect Handler

                /**
                 * --Steam Connection Callback
                 *
                 * It's not needed to modify this section
                 */

                msg.Handle <SteamClient.ConnectedCallback> (callback =>
                {
                    //Print Callback
                    printConsole("Steam Connected Callback: " + callback.Result, ConsoleColor.Cyan);

                    //Validate Result
                    if (callback.Result == EResult.OK)
                    {
                        //Get Steam Login Details
                        printConsole("Username: "******"Password: "******"Getting Web Cookies...", ConsoleColor.Yellow);

                        //Get Web Cookies
                        SteamWeb web = new SteamWeb();
                        WebCookies   = web.DoLogin(user, pass);

                        if (WebCookies != null)
                        {
                            printConsole("SteamWeb Cookies retrived.", ConsoleColor.Green);
                            //Do Login
                            steamUser.LogOn(new SteamUser.LogOnDetails {
                                Username = user,
                                Password = pass
                            });
                        }
                        else
                        {
                            printConsole("Error while getting SteamWeb Cookies.", ConsoleColor.Red);
                        }
                    }
                    else
                    {
                        //Failure
                        printConsole("Failed to Connect to steam.", ConsoleColor.Red);
                    }
                });
                #endregion


                #region Steam Login Handler
                //Logged in (or not)
                msg.Handle <SteamUser.LoggedOnCallback>(callback =>
                {
                    printConsole("Logged on callback: " + callback.Result, ConsoleColor.Cyan);

                    if (callback.Result != EResult.OK)
                    {
                        printConsole("Login Failed!", ConsoleColor.Red);
                    }
                    else
                    {
                        printConsole("Successfulyl Logged In!\nWelcome " + steamUser.SteamID, ConsoleColor.Green);

                        //Set community status
                        steamFriends.SetPersonaName(BotPersonaName);
                        steamFriends.SetPersonaState(BotPersonaState);
                    }
                });
                #endregion


                #region Steam Trade Start

                /**
                 *
                 * Steam Trading Handler
                 *
                 */
                msg.Handle <SteamTrading.TradeStartSessionCallback>(call =>
                {
                    //Trading
                    trade = null;
                    trade = new TradeSystem();
                    trade.initTrade(steamUser.SteamID, call.Other, WebCookies);
                });
                #endregion

                #region Trade Requested Handler
                //Don't modify this
                msg.Handle <SteamTrading.TradeProposedCallback>(thing =>
                {
                    //Trade Callback
                    printConsole("Trade Proposed Callback. Other: " + thing.Other + "\n");

                    //Accept It
                    steamTrade.RequestTrade(thing.Other);
                });
                #endregion

                msg.Handle <SteamFriends.PersonaStateCallback>(callback =>
                {
                    if (callback.FriendID == steamUser.SteamID)
                    {
                        return;
                    }

                    EFriendRelationship relationship = steamFriends.GetFriendRelationship(callback.FriendID);
                    if (!(relationship == EFriendRelationship.RequestRecipient))
                    {
                        return;
                    }


                    if (steamFriends.GetFriendRelationship(callback.FriendID) == EFriendRelationship.PendingInvitee)
                    {
                        printConsole("[Friend] Friend Request Pending: " + callback.FriendID + "(" + steamFriends.GetFriendPersonaName(callback.FriendID) + ") - Accepted", ConsoleColor.Yellow);
                        steamFriends.AddFriend(callback.FriendID);
                    }
                });


                #region Steam Chat Handler

                /**
                 *
                 * Steam Chat Handler
                 *
                 */
                msg.Handle <SteamFriends.FriendMsgCallback>(callback =>
                {
                    //Type (emote or chat)
                    EChatEntryType type = callback.EntryType;

                    if (type == EChatEntryType.ChatMsg)
                    {
                        //Message is a chat message

                        //Reply with the same message
                        steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, callback.Message);

                        //Chat API coming soon
                    }
                    else if (type == EChatEntryType.Emote)
                    {
                        //Message is emote

                        //Do nothing yet
                    }
                });
                #endregion
            }     //end while loop
        }         //end Main method
Ejemplo n.º 13
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
        }
Ejemplo n.º 14
0
        void HandleSteamMessage(CallbackMsg msg, Interface gui)
        {
            //log.Debug(msg.ToString());

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

                if (callback.Result == EResult.OK)
                {
                    UserLogOn();
                }
                else
                {
                    gui.UpdateLog("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)
                {
                    gui.UpdateLog("\r\nLogin Error: " + callback.Result);
                    //log.Error("Login Error: " + callback.Result);
                    gui.Invoke((Action)(() => gui.text_username.Enabled = true));
                    gui.Invoke((Action)(() => gui.text_password.Enabled = true));
                    gui.Invoke((Action)(() => gui.button_login.Text = "Login"));
                }

                if (callback.Result == EResult.AccountLogonDenied)
                {
                    ////log.Interface("This account is protected by Steam Guard.  Enter the authentication code sent to the proper email: ");
                    gui.Invoke((Action)(() => gui.SteamGuard()));

                    while (Application.OpenForms.Count > 1)
                    {
                    }

                    logOnDetails.AuthCode = SteamGuard.authCode;
                }

                if (callback.Result == EResult.InvalidLoginAuthCode)
                {
                    gui.Invoke((Action)(() => gui.SteamGuard(true)));

                    while (Application.OpenForms.Count > 1)
                    {
                    }

                    logOnDetails.AuthCode = SteamGuard.authCode;
                }
            });

            msg.Handle <SteamUser.LoginKeyCallback>(callback =>
            {
                while (true)
                {
                    bool authd = SteamWeb.Authenticate(callback, SteamClient, out sessionId, out token);
                    if (authd)
                    {
                        gui.UpdateLog("\r\nUser authenticated!");
                        break;
                    }
                    else
                    {
                        gui.UpdateLog("\r\nAuthentication failed, retrying in 2s...");
                        Thread.Sleep(2000);
                    }
                }

                SteamFriends.SetPersonaState(EPersonaState.Snooze);

                gui.UpdateLog("\r\nLogged in completely!\r\n");
                gui.Invoke((Action)(() => gui.button_login.Text = "Logged in"));

                IsLoggedIn = true;

                while (true)
                {
                    Console.ReadLine();
                }
            });

            // 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 =>
            {
                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
                {
                    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 =>
            {
                //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;
                gui.UpdateLog("\r\nLogged Off: " + callback.Result);
                //log.Warn("Logged Off: " + callback.Result);
            });

            msg.Handle <SteamClient.DisconnectedCallback>(callback =>
            {
                IsLoggedIn = false;
                CloseTrade();
                gui.UpdateLog("\r\nDisconnected from Steam Network! Trying to reconnect...");
                //log.Warn("Disconnected from Steam Network!");
                SteamClient.Connect();
            });
            #endregion
        }
Ejemplo n.º 15
0
Archivo: Bot.cs Proyecto: xaustinx/Mist
        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;
            }
        }
Ejemplo n.º 16
0
        public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
        {
            userHandlers = new Dictionary <SteamID, UserHandler>();
            logOnDetails = new SteamUser.LogOnDetails
            {
                Username = config.Username,
                Password = config.Password
            };
            DisplayName          = config.DisplayName;
            ChatResponse         = config.ChatResponse;
            MaximumTradeTime     = config.MaximumTradeTime;
            MaximumActionGap     = config.MaximumActionGap;
            DisplayNamePrefix    = config.DisplayNamePrefix;
            tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval;
            schemaLang           = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en";
            Admins     = config.Admins;
            ApiKey     = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
            isProccess = process;
            try
            {
                if (config.LogLevel != null)
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
                    Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
                }
                else
                {
                    consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
                }
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                consoleLogLevel = Log.LogLevel.Info;
            }

            try
            {
                fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
            }
            catch (ArgumentException)
            {
                Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
                fileLogLevel = Log.LogLevel.Info;
            }

            logFile = config.LogFile;
            CreateLog();
            createHandler   = handlerCreator;
            BotControlClass = config.BotControlClass;
            SteamWeb        = new SteamWeb();

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

            Log.Debug("Initializing Steam Bot...");
            SteamClient = new SteamClient();
            SteamClient.AddHandler(new SteamNotifications());
            SteamTrade           = SteamClient.GetHandler <SteamTrading>();
            SteamUser            = SteamClient.GetHandler <SteamUser>();
            SteamFriends         = SteamClient.GetHandler <SteamFriends>();
            SteamGameCoordinator = SteamClient.GetHandler <SteamGameCoordinator>();
            SteamNotifications   = SteamClient.GetHandler <SteamNotifications>();

            botThread = new BackgroundWorker {
                WorkerSupportsCancellation = true
            };
            botThread.DoWork             += BackgroundWorkerOnDoWork;
            botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
            botThread.RunWorkerAsync();
        }
Ejemplo n.º 17
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.PendingInvitee &&
                            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
                {
                    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();
                }
            });
            #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
        }
Ejemplo n.º 18
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());

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

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

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

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

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

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

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

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

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

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

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

                if (BotControlClass == "SteamBot.KeybankHandler")
                {
                    //string newName = DisplayNamePrefix + DisplayName + " B>6 S>6.11";
                    string newName = DisplayNamePrefix + DisplayName + String.Format(" B>{0} S>{1}", Convert.ToString(clsFunctions.GetKeyBuyPrice()), Convert.ToString(clsFunctions.GetKeySellPrice()));
                    SteamFriends.SetPersonaName(newName);
                }
                else
                {
                    SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName);
                }
                SteamFriends.SetPersonaState(EPersonaState.Online);
                log.Success("Steam Bot Logged In Completely!");
                IsLoggedIn = true;
                this.SteamFriends.JoinChat(< GROUPCHATID >);//Gamem Tradeing Services
                if (BotControlClass != "SteamBot.RaffleDonatoinUserHandler")
                {
                    this.SteamFriends.JoinChat(< GROUPID >); //TF2 Exchange
                    this.SteamFriends.JoinChat(< GROUPID >); //TF2 Alliance
                }
                uid         = < GROUPID >;
                InGroupChat = true;
                try
                {
                    clsFunctions.AddBotToList(this, logOnDetails.Username);
                    GetInventory();
                }
                catch
                {
                }

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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