private void DisplayNotification(RtmMessageModel message)
        {
            if (MainWindow.Form.InvokeRequired)
            {
                MainWindow.Form.Invoke((Action)(delegate { DisplayNotification(message); }));
                return;
            }

            var existingNotification = _openNotifications.FirstOrDefault(x => x.Key == message.ChannelId).Value;

            // Don't create new notifications for messages posted by the current user
            if (existingNotification != null || message.IsIncoming)
            {
                if (existingNotification == null)
                {
                    existingNotification = new Notification(message.ChannelId, message.ChannelName, 20,
                        FormAnimator.AnimationMethod.Slide, FormAnimator.AnimationDirection.Up);
                    existingNotification.Closed += OnChannelClosed;
                    existingNotification.OnQuickReply += OnChannelQuickReply;
                    existingNotification.OnSnooze += OnNotificationSnoozeClick;

                    existingNotification.Show();
                    _openNotifications.Add(message.ChannelId, existingNotification);
                }

                existingNotification.AddMessage(message.User, message.MessageText, message.IsIncoming);
            }
        }
Beispiel #2
0
        public void showExpiredNotif()
        {
            //MySqlConnection notifConn = LoginNew.conn;
            //string query = "CALL notif();";
            //try
            //{
            //    if (notifConn != null && (notifConn.State == ConnectionState.Closed))
            //        notifConn.Open();
            //    using (MySqlCommand cmd = new MySqlCommand(query, notifConn))
            //    {
            //        using (MySqlDataReader dataReader = cmd.ExecuteReader())
            //        {
            //            //Read the data and store them in the list
            //            while (dataReader.Read())
            //            {
            //                ToastNotifications.Notification notif = new ToastNotifications.Notification(dataReader[0].ToString(), dataReader[1].ToString(), 7, ToastNotifications.FormAnimator.AnimationMethod.Slide, ToastNotifications.FormAnimator.AnimationDirection.Up);
            //                notif.Show();
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Notif: " + ex.Message);
            //}
            //finally
            //{
            //    notifConn.Close();
            //}
            int exp, min, max;

            exp = Int32.Parse(Program.getPrevCode("select count(*) FROM vwnotif where type=0;"));
            min = Int32.Parse(Program.getPrevCode("select count(*) FROM vwnotif where type=1;"));
            max = Int32.Parse(Program.getPrevCode("select count(*) FROM vwnotif where type=2"));
            if (exp > 0)
            {
                string strNotif = "A total of " + exp + " items have expired";
                ToastNotifications.Notification notif = new ToastNotifications.Notification("Expiration", strNotif, 7, ToastNotifications.FormAnimator.AnimationMethod.Slide, ToastNotifications.FormAnimator.AnimationDirection.Up, 0);
                notif.Show();
            }
            if (min > 0)
            {
                string strNotif = "A total of " + min + " items have reached their minimum stock level";
                ToastNotifications.Notification notif = new ToastNotifications.Notification("Stock Level", strNotif, 7, ToastNotifications.FormAnimator.AnimationMethod.Slide, ToastNotifications.FormAnimator.AnimationDirection.Up, 1);
                notif.Show();
            }
            if (max > 0)
            {
                string strNotif = "A total of " + max + " items have reached their maximum stock level";
                ToastNotifications.Notification notif = new ToastNotifications.Notification("Stock Level", strNotif, 7, ToastNotifications.FormAnimator.AnimationMethod.Slide, ToastNotifications.FormAnimator.AnimationDirection.Up, 1);
                notif.Show();
            }
        }
Beispiel #3
0
 public override void OnMessage(string message, EChatEntryType type)
 {
     if (Bot.main.InvokeRequired)
     {
         Bot.main.Invoke((Action)(() =>
         {
             var other = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
             Console.WriteLine(OtherSID);
             OpenChat(OtherSID);
             string update = "[" + DateTime.Now + "] - " + other + ": " + message + "\r\n";
             foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
             {
                 if (tab.Text == other)
                 {
                     foreach (var item in tab.Controls)
                     {
                         Friends.chat.chatTab = (ChatTab)item;
                     }
                 }
             }
             Friends.chat.chatTab.UpdateChat(update);
             if (!Chat.hasFocus)
             {
                 int duration = 3;
                 FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                 FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                 string title = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " says:";
                 Notification toastNotification = new Notification(title, message, duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox);
                 toastNotification.Show();
             }
         }));
     }
     else
     {
         var other = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
         OpenChat(OtherSID);
         string update = "[" + DateTime.Now + "] - " + other + ": " + message + "\r\n";
         foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
         {
             if (tab.Text == other)
             {
                 foreach (var item in tab.Controls)
                 {
                     Friends.chat.chatTab = (ChatTab)item;
                 }
             }
         }
         Friends.chat.chatTab.UpdateChat(update);
     }
 }
Beispiel #4
0
 public override void OnTradeMessage(string message)
 {
     Bot.main.Invoke((Action)(() =>
     {
         string send = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + ": " + message + " [" + DateTime.Now.ToLongTimeString() + "]\r\n";
         ShowTrade.UpdateChat(send);
         if (!ShowTrade.focused)
         {
             int duration = 3;
             FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
             FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
             string title = "[Trade Chat] " + Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " says:";
             Notification toastNotification = new Notification(title, message, duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox);
             toastNotification.Show();
         }
     }));
 }
        private void ShowNotification()
        {
            int duration;
            int.TryParse(comboBoxDuration.SelectedItem.ToString(), out duration);
            if (duration <= 0)
            {
                duration = -1;
            }

            var animationMethod = FormAnimator.AnimationMethod.Slide;
            foreach (FormAnimator.AnimationMethod method in Enum.GetValues(typeof(FormAnimator.AnimationMethod)))
            {
                if (string.Equals(method.ToString(), comboBoxAnimation.SelectedItem))
                {
                    animationMethod = method;
                    break;
                }
            }

            var animationDirection = FormAnimator.AnimationDirection.Up;
            foreach (FormAnimator.AnimationDirection direction in Enum.GetValues(typeof(FormAnimator.AnimationDirection)))
            {
                if (string.Equals(direction.ToString(), comboBoxAnimationDirection.SelectedItem))
                {
                    animationDirection = direction;
                    break;
                }
            }

            var toastNotification = new Notification("id", textBoxTitle.Text, duration, animationMethod, animationDirection);
            PlayNotificationSound(comboBoxSound.Text);
            toastNotification.Show();
        }
Beispiel #6
0
 public void TradeButtonMode(int _mode, uint _tradeID = 0)
 {
     int mode = _mode;
     tradeID = _tradeID;
     switch (mode)
     {
         case 1: // not in trade - "Invite to trade"
             tradeMode = 1;
             button_trade.Text = "Invite to Trade";
             button_trade.Enabled = true;
             break;
         case 2: // User sent trade request - "Cancel trade request"
             tradeMode = 2;
             button_trade.Text = "Cancel Trade Request";
             break;
         case 3: // Other sent trade request - "Accept trade request"
             button_trade.Enabled = true;
             tradeMode = 3;
             text_log.AppendText("[" + DateTime.Now + "] " + steam_name.Text + " has requested to trade with you." + Environment.NewLine);
             if (Friends.keepLog)
                 AppendLog(userSteamId, "[" + DateTime.Now + "] " + steam_name.Text + " has requested to trade with you." + Environment.NewLine);
             text_log.ScrollToCaret();
             if (!Chat.hasFocus)
             {
                 try
                 {
                     string soundsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
                     string soundFile = Path.Combine(soundsFolder + "message.wav");
                     using (System.Media.SoundPlayer player = new System.Media.SoundPlayer(soundFile))
                     {
                         player.Play();
                     }
                 }
                 catch (Exception e)
                 {
                     Console.WriteLine(e.Message);
                 }
                 Chat.Flash();
             }
             int duration = 3;
             FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
             FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
             string title = steam_name.Text;
             Notification toastNotification = new Notification(title, Util.GetColorFromPersonaState(bot, userSteamId), "has requested to trade with you.", duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox, new Action(() =>
             {
                 Friends.chat.BringToFront();
             }));
             toastNotification.Show();
             button_trade.Text = "Accept Trade Request";
             break;
     }
 }
Beispiel #7
0
        void HandleSteamMessage(CallbackMsg msg)
        {
            log.Debug(msg.ToString());
            msg.Handle<SteamGameCoordinator.MessageCallback>(callback =>
            {
                Console.WriteLine(callback.EMsg);
            });

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

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

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

            });

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

                if (callback.Result == EResult.OK)
                {
                    MyLoginKey = callback.WebAPIUserNonce;
                    main.Invoke((Action)(() =>
                    {
                        main.label_status.Text = "Logging in to Steam...";
                        log.Info("Logging in to Steam...");
                    }));
                }

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

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

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

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

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

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

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

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

                    }
                }).Start();
            });

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

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

            #region Friends
            msg.Handle<SteamFriends.FriendsListCallback>(callback =>
            {
                foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
                {
                    if (friend.SteamID.AccountType == EAccountType.Clan)
                    {

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

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

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

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

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

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

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

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

            msg.Handle<SteamTrading.TradeProposedCallback>(callback =>
            {
                try
                {
                    tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient);
                }
                catch
                {
                    SteamTrade.RespondToTrade(callback.TradeID, false);
                    return;
                }

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

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

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

            });
            #endregion

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

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

            if (!hasrun && IsLoggedIn)
            {
                Thread main = new Thread(GUI);
                main.Start();
                hasrun = true;
            }
        }
Beispiel #8
0
 public override void OnMessage(string message, EChatEntryType type)
 {
     if (Bot.main.InvokeRequired)
     {
         Bot.main.Invoke((Action)(() =>
         {
             var other = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
             OpenChat(OtherSID);
             string date = "[" + DateTime.Now + "] ";
             string name = other + ": ";
             foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
             {
                 if (tab.Text == other)
                 {
                     foreach (var item in tab.Controls)
                     {
                         Friends.chat.chatTab = (ChatTab)item;
                     }
                 }
             }
             int islink;
             islink = 0;
             if (message.Contains("http://") || (message.Contains("https://")) || (message.Contains("www.")) || (message.Contains("ftp."))){
                 string[] stan = message.Split(' ');
                 foreach (string word in stan)
                 {
                     if (word.Contains("http://") || (word.Contains("https://")) || (word.Contains("www.")) || (word.Contains("ftp.")))
                     {
                         if (word.Contains("."))
                         {
                             islink = 1;
                         }
                     }
                 }
             }
             if (islink == 1)
             {
                 Friends.chat.chatTab.UpdateChat("[INFO] ", "WARNING: ", "Do not click on links that you feel that maybe unsafe. Make sure the link is what it should be by looking at it.");
             }
             Friends.chat.chatTab.UpdateChat(date, name, message);
             new Thread(() =>
             {
                 if (!Chat.hasFocus)
                 {
                     int duration = 3;
                     FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                     FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                     string title = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + " says:";
                     Notification toastNotification = new Notification(title, message, duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox);
                     Bot.main.Invoke((Action)(() =>
                     {
                         toastNotification.Show();
                     }));
                 }
             }).Start();
         }));
     }
     else
     {
         var other = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
         OpenChat(OtherSID);
         string date = "[" + DateTime.Now + "] ";
         string name = other + ": ";
         foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
         {
             if (tab.Text == other)
             {
                 foreach (var item in tab.Controls)
                 {
                     Friends.chat.chatTab = (ChatTab)item;
                 }
             }
         }
         Friends.chat.chatTab.UpdateChat(date, name, message);
     }
 }
Beispiel #9
0
Datei: Bot.cs Projekt: Jamyn/Mist
        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)
                {
                    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 =>
            {
                while (true)
                {
                    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);
                    }
                }

                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.Close));
                        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();
                try
                {
                    main.Invoke((Action)(main.Hide));
                }
                catch (Exception)
                {
                    Environment.Exit(1);
                }
                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;
            }
        }
 public override void OnMessage(string message, EChatEntryType type)
 {
     Bot.main.Invoke((Action)(() =>
     {
         var other = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
         var opened = OpenChat(OtherSID);
         string date = "[" + DateTime.Now + "] ";
         string name = other + ": ";
         foreach (TabPage tab in Friends.chat.ChatTabControl.TabPages)
         {
             if ((SteamID)tab.Tag == OtherSID)
             {
                 foreach (var item in tab.Controls)
                 {
                     Friends.chat.chatTab = (ChatTab)item;
                 }
             }
         }
         int islink;
         islink = 0;
         if (message.Contains("http://") || (message.Contains("https://")) || (message.Contains("www.")) || (message.Contains("ftp.")))
         {
             string[] stan = message.Split(' ');
             foreach (string word in stan)
             {
                 if (word.Contains("http://") || (word.Contains("https://")) || (word.Contains("www.")) || (word.Contains("ftp.")))
                 {
                     if (word.Contains("."))
                     {
                         islink = 1;
                     }
                 }
             }
         }
         if (islink == 1)
         {
             Friends.chat.chatTab.UpdateChat("[INFO] ", "WARNING: ", "Be cautious when clicking unknown links.");
         }
         Friends.chat.chatTab.UpdateChat(date, name, message);
         new Thread(() =>
         {
             if (opened || !Chat.hasFocus)
             {
                 int duration = 3;
                 FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
                 FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
                 string title = Bot.SteamFriends.GetFriendPersonaName(OtherSID);
                 Notification toastNotification = new Notification(title, Util.GetColorFromPersonaState(Bot, OtherSID), message, duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox, new Action(() =>
                 {
                     Friends.chat.BringToFront();
                 }));
                 Bot.main.Invoke((Action)(() =>
                 {
                     toastNotification.Show();
                 }));
             }
         }).Start();
     }));
 }
 public override void OnTradeMessage(string message)
 {
     Bot.main.Invoke((Action)(() =>
     {
         string send = Bot.SteamFriends.GetFriendPersonaName(OtherSID) + ": " + message + " [" + DateTime.Now.ToLongTimeString() + "]\r\n";
         ChatTab.AppendLog(OtherSID, "[Trade Chat] " + send);
         if (!ShowTradeWeb.Focused)
         {
             int duration = 3;
             FormAnimator.AnimationMethod animationMethod = FormAnimator.AnimationMethod.Slide;
             FormAnimator.AnimationDirection animationDirection = FormAnimator.AnimationDirection.Up;
             string title = "[Trade Chat] " + Bot.SteamFriends.GetFriendPersonaName(OtherSID);
             Notification toastNotification = new Notification(title, Util.GetColorFromPersonaState(Bot, OtherSID
             ), message, duration, animationMethod, animationDirection, Friends.chat.chatTab.avatarBox, new Action(() =>
             {
                 ShowTradeWeb.BringToFront();
             }));
             toastNotification.Show();
         }
     }));
 }