示例#1
0
        /// <summary>
        /// Replaces the bot behavior.
        /// </summary>
        internal static void ReplaceBotBehavior()
        {
            if (!Plugin.Enabled)
            {
                Logr.Log("Plugin not enabled - restoring original BotBehavior");
                RestoreOriginalBotBehavior();
                return;
            }
            if (SimpleFollow.IsFollower)
            {
                return;
            }

            const string hookName = "BotBehavior";

            if (!TreeHooks.Instance.Hooks.ContainsKey(hookName))
            {
                return;
            }

            if (_originalBotBehavior == null)
            {
                _originalBotBehavior = TreeHooks.Instance.Hooks[hookName];
            }

            _leaderBehavior = CreateBehavior();

            Logr.Log("Inserting into BotBehavior hook");
            TreeHooks.Instance.Hooks[hookName].Insert(0, _leaderBehavior);
            _hookReplaced = true;
        }
示例#2
0
        /// <summary>
        /// Initializes the Follower connection to the Leader
        /// </summary>
        private static void StartClient()
        {
            try
            {
                if (!Initialized && Enabled)
                {
                    int serverPort = Settings.Instance.ServerPort;
                    ServerUri = new Uri(ServerUri.AbsoluteUri.Replace(BasePort.ToString(), serverPort.ToString()));

                    SharedComposites.CheckReplaceOutOfGameHook();

                    Logr.Log("Initializing Client Service connection to {0}", ServerUri.AbsoluteUri + "Follow");

                    BasicHttpBinding binding = new BasicHttpBinding
                    {
                        OpenTimeout  = TimeSpan.FromMilliseconds(5000),
                        SendTimeout  = TimeSpan.FromMilliseconds(5000),
                        CloseTimeout = TimeSpan.FromMilliseconds(5000)
                    };

                    EndpointAddress endPointAddress = new EndpointAddress(ServerUri.AbsoluteUri + "Follow");

                    HttpFactory = new ChannelFactory <IFollowService>(binding, endPointAddress);

                    HttpProxy = HttpFactory.CreateChannel();

                    Initialized = true;
                }
            }
            catch (Exception ex)
            {
                Logr.Log("Exception in ClientInitialize() {0}", ex);
            }
        }
示例#3
0
        /// <summary>
        /// This is a thread running on the leader bot to watch the current profile behavior, to speed up followers going to the right place at the right time
        /// </summary>
        internal static void BehaviorWatcher()
        {
            try
            {
                if (Enabled && !IsFollower)
                {
                    ProfileBehavior currentBehavior = ProfileManager.CurrentProfileBehavior;
                    if (currentBehavior != null)
                    {
                        if (currentBehavior.GetType().Name.ToLower().Contains("town"))
                        {
                            Leader.IsInTown = true;
                        }
                        if (currentBehavior.GetType().Name.ToLower().Contains("leavegame"))
                        {
                            Leader.IsInGame = false;
                        }

                        // The profile position for look-ahead
                        Leader.ProfilePosition = Message.GetProfilePosition();
                        Leader.ProfileActorSNO = Message.GetProfileActorSNO();
                    }

                    if (BrainBehavior.IsVendoring)
                    {
                        Leader.IsInTown = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Logr.Log("Exception in BehaviorWatcher: {0}", ex);
            }
        }
示例#4
0
        private static bool ClickTimerRandomNotReady()
        {
            long timeRemaining = clickTimerRandomVal - clickTimer.ElapsedMilliseconds;

            Logr.Log("Pausing bot -  waiting for button timer {0}ms", clickTimerRandomVal);
            return(clickTimer.IsRunning && clickTimer.ElapsedMilliseconds < clickTimerRandomVal);
        }
示例#5
0
        public void OnDisabled()
        {
            Logr.Log("Plugin disabled! ");
            Enabled = false;

            BotMain.OnStart                   -= BotMain_OnStart;
            BotMain.OnStop                    -= BotMain_OnStop;
            GameEvents.OnGameLeft             -= GameEvents_OnGameLeft;
            GameEvents.OnGameJoined           -= GameEvents_OnGameJoined;
            GameEvents.OnWorldTransferStart   -= GameEvents_OnWorldTransferStart;
            GameEvents.OnWorldChanged         -= GameEvents_OnWorldChanged;
            TreeHooks.Instance.OnHooksCleared -= OnHooksCleared;

            ServiceBase.Initialized = false;
            SharedComposites.CheckReplaceOutOfGameHook();

            try
            {
                if (ServiceBase.Host != null)
                {
                    ServiceBase.Host.Close();
                }
            }
            catch
            {
            }
        }
示例#6
0
        /// <summary>
        /// Leader Out Of Game Coroutine
        /// </summary>
        /// <param name="children">The children.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        internal static async Task <bool> LeaderOutOfGameTask()
        {
            LeaderService.LeaderOutOfGameUpdate();
            SimpleFollow.Pulse();

            // Some safety checks
            if (ZetaDia.IsInGame)
            {
                return(true);
            }

            if (ZetaDia.IsLoadingWorld)
            {
                return(true);
            }

            if (!ZetaDia.Service.Hero.IsValid)
            {
                return(true);
            }

            if (!ZetaDia.Service.Platform.IsConnected)
            {
                return(true);
            }

            if (!ZetaDia.Service.IsValid || !ZetaDia.Service.Hero.IsValid)
            {
                return(true);
            }

            // In Party but no followers connected - just wait!
            if (Settings.Instance.WaitForFollowers && Social.IsInParty && Social.IsPartyleader && Social.NumPartyMembers - 1 != SimpleFollow.Followers.Count)
            {
                Logr.Log("Waiting for followers to connect to SimpleFollow server...");
                return(false);
            }
            if (!Social.IsPartyleader)
            {
                Logr.Log("Waiting to become party leader...");
                return(false);
            }

            if (!SimpleFollow.Followers.Any())
            {
                return(true);
            }

            var followersInGame = SimpleFollow.Followers.Where(f => DateTime.UtcNow.Subtract(f.Value.LastTimeInGame).TotalSeconds < 10).ToList();

            if (Social.IsInParty && followersInGame.Any() && !GameUI.PlayGameButton.IsEnabled)
            {
                Logr.Log("Waiting for {0} followers to leave game...", followersInGame.Count());
                await Coroutine.Sleep(500);

                return(false);
            }

            return(true);
        }
示例#7
0
        private static void StartServer()
        {
            try
            {
                var bindAddress = Settings.Instance.BindAddress;
                var serverPort  = Settings.Instance.ServerPort;

                IPGlobalProperties igp = IPGlobalProperties.GetIPGlobalProperties();
                bool isAvailable       =
                    igp.GetActiveTcpConnections().All(tcpi => tcpi.LocalEndPoint.Port != serverPort) &&
                    igp.GetActiveTcpListeners().All(l => l.Port != serverPort);

                // At this point, if isAvailable is true, we can proceed accordingly.
                if (isAvailable)
                {
                    ServerUri = new Uri("http://" + bindAddress + ":" + serverPort);

                    Logr.Log("Initializing Server Service @ {0}", ServerUri.AbsoluteUri);
                    Host = new ServiceHost(typeof(Server), new[] { ServerUri });
                    Host.AddServiceEndpoint(typeof(IFollowService), new BasicHttpBinding(), "Follow");
                    Host.Open();
                    Leader = Message.GetMessage();
                }
            }
            catch (Exception ex)
            {
                Logr.Log("ERROR: Could not initialize follow service. Do you already have a leader started?");
                Logr.Log(ex.ToString());

                Logr.Log("Disabling Plugin and Resetting Game Creation Wait Timers to default");
                Plugin.DisablePlugin();
            }
        }
示例#8
0
        /// <summary>
        /// Restores the original bot behavior.
        /// </summary>
        internal static void RestoreOriginalBotBehavior()
        {
            const string hookName = "BotBehavior";

            if (_originalBotBehavior != null && TreeHooks.Instance.Hooks.ContainsKey(hookName) && _hookReplaced)
            {
                Logr.Log("Replacing {0} hook to original", hookName);
                TreeHooks.Instance.ReplaceHook(hookName, new Sequence(_originalBotBehavior.ToArray()));
                _hookReplaced = false;
            }
        }
示例#9
0
        /// <summary>
        /// Handles bot-start
        /// </summary>
        /// <param name="bot"></param>
        private void BotMain_OnStart(IBot bot)
        {
            LeaderComposite.ReplaceBotBehavior();
            if (Enabled)
            {
                Logr.Log("Bot Starting");
                SharedComposites.OutOfGameHookReplaced = false;
                SharedComposites.CheckReplaceOutOfGameHook();
                LeaderService.LeaderOutOfGameUpdate();

                ServiceBase.Communicate();
            }
        }
示例#10
0
 /// <summary>
 /// This method is processed by the leader (e.g. followers invoke it, the leader receives it and executes the body below)
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 public Message GetUpdate()
 {
     try
     {
         Message m = SimpleFollow.Leader;
         //Logging.Write(m.ToString());
         return(m);
     }
     catch (Exception ex)
     {
         Logr.Log("Exception in GetUpdate() {0}", ex);
         return(new Message());
     }
 }
示例#11
0
        public static void Pulse()
        {
            try
            {
                LeaderService.CleanExpiredFollowers();
                ServiceBase.Communicate();

                LeaderService.PulseInbox();

                SharedComposites.CheckReplaceOutOfGameHook();
            }
            catch (Exception ex)
            {
                Logr.Log("Exception thrown on Pulse: {0}", ex.ToString());
            }

            GameUI.SafeCheckClickButtons();
        }
示例#12
0
        /// <summary>
        /// Leaders the in game task.
        /// </summary>
        /// <param name="children">The children.</param>
        /// <returns>Task&lt;System.Boolean&gt;.</returns>
        internal static async Task <bool> LeaderInGameTask()
        {
            if (ValidCombatCheck() && AnyFollowersInCombat())
            {
                SimpleFollow.Pulse();
                Logr.Log("A friend is in combat - to the rescue!");

                ZetaDia.Me.TeleportToPlayerByIndex(SimpleFollow.Followers.FirstOrDefault(f => f.Value.IsInCombat).Value.CPlayerIndex);
                await Coroutine.Sleep(200);

                await Coroutine.Yield();
            }

            // In Party but no followers connected - just wait!
            while (Settings.Instance.WaitForFollowers && ValidCheck() && Social.NumPartyMembers - 1 != SimpleFollow.Followers.Count)
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to connect to SimpleFollow server...");
                await Coroutine.Yield();
            }

            while (Settings.Instance.WaitForFollowers && ValidCheck() && !AllFollowersInGame())
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to join same game...");
                await Coroutine.Yield();
            }

            while (Settings.Instance.WaitForFollowers && ValidCheck() && AnyFollowersNotInTown())
            {
                SimpleFollow.Pulse();
                Logr.Log("Waiting for party members to come to town...");
                await Coroutine.Yield();
            }

            /* Wait for followers to open greater rift
             * while (ValidCheck() && ShouldFollowerOpenRift())
             * {
             *  SimpleFollow.Pulse();
             *  Logr.Log("Waiting for follower to open rift...");
             *  await Coroutine.Yield();
             * }*/
            return(false);
        }
示例#13
0
        public void OnEnabled()
        {
            Logr.Log("Plugin v{0} Enabled", Version);
            Enabled = true;

            BotMain.OnStart                   += BotMain_OnStart;
            BotMain.OnStop                    += BotMain_OnStop;
            GameEvents.OnGameLeft             += GameEvents_OnGameLeft;
            GameEvents.OnGameJoined           += GameEvents_OnGameJoined;
            GameEvents.OnWorldTransferStart   += GameEvents_OnWorldTransferStart;
            GameEvents.OnWorldChanged         += GameEvents_OnWorldChanged;
            TreeHooks.Instance.OnHooksCleared += OnHooksCleared;

            SharedComposites.OutOfGameHookReplaced = false;
            SharedComposites.CheckReplaceOutOfGameHook();
            LeaderService.LeaderOutOfGameUpdate();

            ServiceBase.Communicate();
        }
示例#14
0
 public void OpenSocialWindow()
 {
     if (DateTime.UtcNow.Subtract(lastOpenedSocialWindow).TotalMilliseconds <= 500)
     {
         return;
     }
     // only click social button to open social window if window is not visible
     if (!IsSocialWindowOpen)
     {
         GameUI.SafeClick(SocialFlyoutButton, ClickDelay.NoDelay, "Social Flyout Button", 500);
         GameUI.SafeClick(ToggleSocialButton, ClickDelay.NoDelay, "Social Window", 500);
         lastOpenedSocialWindow = DateTime.UtcNow;
         recheckInvites         = true;
         return;
     }
     if (IsSocialWindowOpen && !GameUI.ElementIsVisible(AddFriendButton, "Add Friend Button"))
     {
         Logr.Log("Unable to open social window!");
     }
 }
示例#15
0
 /// <summary>
 /// Pulsing this will update both the follower and leader messages.
 /// </summary>
 internal static void Communicate()
 {
     if (Enabled)
     {
         if (!IsFollower)
         {
             LeaderService.BehaviorWatcher();
             LeaderService.ServerUpdate();
         }
         else
         {
             FollowerService.AsyncClientUpdate();
         }
     }
     else
     {
         Logr.Log("Error - Main pulsed but plugin is disabled!");
         SharedComposites.CheckReplaceOutOfGameHook();
     }
 }
示例#16
0
        internal static void CheckReplaceOutOfGameHook()
        {
            // Plugin was diabled, replace hook to original
            if (!SimpleFollow.Enabled)
            {
                if (_originalOutOfGameComposites != null)
                {
                    Logr.Log("Replacing OutOfGame hook to original");
                    TreeHooks.Instance.ReplaceHook("OutOfGame", new PrioritySelector(_originalOutOfGameComposites.ToArray()));
                }
                _outOfGameHookReplaced = false;
                return;
            }

            if (ProfileManager.CurrentProfile != null)
            {
                if (SimpleFollow.IsFollower && !_outOfGameHookReplaced)
                {
                    Logr.Log("Replacing OutOfGame hook with Follower Behavior");
                    StoreOriginalOutOfGameComposite();
                    _followerBehavior = FollowerComposite.CreateBehavior();
                    TreeHooks.Instance.ReplaceHook("OutOfGame", _followerBehavior);
                    _outOfGameHookReplaced = true;
                }
                else if (!SimpleFollow.IsFollower && !_outOfGameHookReplaced)
                {
                    Logr.Log("Replacing OutOfGame hook with Leader Behavior");
                    if (SimpleFollow.Enabled)
                    {
                        StoreOriginalOutOfGameComposite();

                        if (_originalOutOfGameComposites != null)
                        {
                            // Reference the leader composite (since we're no longer a follower)
                            TreeHooks.Instance.ReplaceHook("OutOfGame", LeaderComposite.CreateOutOfGameBehavior(_originalOutOfGameComposites));
                            _outOfGameHookReplaced = true;
                        }
                    }
                }
            }
        }
示例#17
0
        internal static void PulseInbox()
        {
            // Process Messages
            Queue <Message> messages = new Queue <Message>();

            try
            {
                lock (Inbox)
                    while (Inbox.ToList().Any())
                    {
                        Message msg;
                        if (Inbox.TryDequeue(out msg) && msg != null)
                        {
                            messages.Enqueue(msg);
                        }
                    }
            }
            catch (Exception ex)
            {
                Logr.Log(ex.ToString());
            }

            CleanExpiredFollowers();

            while (messages.ToList().Any())
            {
                var message = messages.Dequeue();

                if (message == null)
                {
                    continue;
                }

                try
                {
                    if (message.BattleTagHash != 0)
                    {
                        if (Followers.ContainsKey(message.BattleTagHash))
                        {
                            Followers[message.BattleTagHash] = message;
                        }
                        else
                        {
                            Followers.Add(message.BattleTagHash, message);
                        }
                    }

                    if (Settings.Instance.DebugLogging)
                    {
                        Logr.Debug("Received follower message: {0}", message);
                    }

                    if (!message.IsInParty && !message.IsInGame && Leader.IsInGame)
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Not in game. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (!message.IsInParty && (message.GameId.FactoryId == 0 && message.GameId.High == 0 && message.GameId.Low == 0) && !Leader.IsInGame)
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Needs Invite. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (!Leader.GameId.Equals(message.GameId))
                    {
                        Logr.Debug("Inviting {0} ({1}) to the party - Incorrect Game. IsInGame={2} IsInParty={3} NumPartyMembers={4}",
                                   message.ActorClass, message.BattleTagHash, message.IsInGame, message.IsInParty, message.NumPartymembers);
                        Social.Instance.CheckInvites();
                        continue;
                    }

                    if (Leader.GameId.Equals(message.GameId))
                    {
                        Social.Instance.CheckCloseSocialWindow();
                        continue;
                    }

                    Logr.Log("Message response: invalid/unknown state");
                }
                catch (Exception ex)
                {
                    Logr.Log("Exception receiving update from client!");
                    Logr.Log(ex.ToString());
                    return;
                }
            }
        }
示例#18
0
        /// <summary>
        /// Called by followers through FollowTag->Communicate()
        /// </summary>
        private static void ClientUpdate()
        {
            if (Enabled)
            {
                _updateRunning = true;
                try
                {
                    if (Host != null && Host.State == CommunicationState.Opened)
                    {
                        Logr.Log("Shutting down Server Service");
                        Host.Close();
                        Host = null;
                    }
                }
                catch (Exception ex)
                {
                    Logr.Error("Error shutting down server service: " + ex);
                }

                StartClient();

                try
                {
                    if (Initialized && Leader.GetMillisecondsSinceLastUpdate() >= 250)
                    {
                        // Get the leader message and store it
                        Leader = HttpProxy.GetUpdate();

                        // Send our follower message to the leader
                        HttpProxy.SendUpdate(_lastMessage);


                        if (LastLeaderUpdateMessage == null || LastLeaderUpdateMessage != Leader)
                        {
                            LastLeaderUpdateMessage = Leader;

                            SetQuestToolsOptionsFromLeader();

                            if (Settings.Instance.DebugLogging)
                            {
                                Logr.Debug("Leader {0}", Leader.ToString());
                            }
                        }
                    }
                }
                catch (EndpointNotFoundException ex)
                {
                    Logr.Error("Error 201: Could not get an update from the leader using {0}. Is the leader running? ({1})", HttpFactory.Endpoint.Address.Uri.AbsoluteUri, ex.Message);
                    Initialized = false;
                }
                catch (CommunicationException ex)
                {
                    Logr.Error("Error 202: Could not get an update from the leader using {0}. Is the leader running? ({1})", HttpFactory.Endpoint.Address.Uri.AbsoluteUri, ex.Message);
                    Initialized = false;
                }
                catch (Exception ex)
                {
                    Logr.Error("Error 203: Could not get an update from the leader using {0}. Is the leader running?", HttpFactory.Endpoint.Address.Uri.AbsoluteUri);
                    Initialized = false;
                    Logr.Log(ex.ToString());
                }
                _updateRunning = false;
            }
        }
 public void Run(BrowserHost host, PipeServer server)
 {
     Logr.Log("Received shutdown request from network.");
     Program.ShutDown();
 }
示例#20
0
        private static void SetQuestToolsOptionsFromLeader()
        {
            bool questToolsSettingsChanged = false;

            if (Leader.RiftKeyPriority == null || Leader.MinimumGemChance == 0f || Leader.LimitRiftLevel == 0 || Leader.TrialRiftMaxLevel == 0)
            {
                return;
            }
            string thingsThatChanged = "";

            // Force followers to use leader's rift key priority
            if (!QuestToolsSettings.Instance.RiftKeyPriority.SequenceEqual(Leader.RiftKeyPriority))
            {
                QuestToolsSettings.Instance.RiftKeyPriority = Leader.RiftKeyPriority;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "RiftKeyPriority,";
                thingsThatChanged         = Leader.RiftKeyPriority.Aggregate(thingsThatChanged, (current, k) => current + (k + "-"));
                thingsThatChanged        += " ";
                thingsThatChanged         = QuestToolsSettings.Instance.RiftKeyPriority.Aggregate(thingsThatChanged, (current, k) => current + (k + "-"));
            }

            if (QuestToolsSettings.Instance.UseHighestKeystone != Leader.UseHighestKeystone)
            {
                QuestToolsSettings.Instance.UseHighestKeystone = Leader.UseHighestKeystone;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "UseHighestKeystone,";
            }

            if (QuestToolsSettings.Instance.MinimumGemChance != Leader.MinimumGemChance)
            {
                QuestToolsSettings.Instance.MinimumGemChance = Leader.MinimumGemChance;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "MinimumGemChance,";
            }

            if (QuestToolsSettings.Instance.EnableLimitRiftLevel != Leader.EnableLimitRiftLevel)
            {
                QuestToolsSettings.Instance.EnableLimitRiftLevel = Leader.EnableLimitRiftLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "EnableLimitRiftLevel,";
            }

            if (QuestToolsSettings.Instance.LimitRiftLevel != Leader.LimitRiftLevel)
            {
                QuestToolsSettings.Instance.LimitRiftLevel = Leader.LimitRiftLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "LimitRiftLevel,";
            }

            if (QuestToolsSettings.Instance.EnableTrialRiftMaxLevel != Leader.EnableTrialRiftMaxLevel)
            {
                QuestToolsSettings.Instance.EnableTrialRiftMaxLevel = Leader.EnableTrialRiftMaxLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "EnableTrialRiftMaxLevel,";
            }

            if (QuestToolsSettings.Instance.TrialRiftMaxLevel != Leader.TrialRiftMaxLevel)
            {
                QuestToolsSettings.Instance.TrialRiftMaxLevel = Leader.TrialRiftMaxLevel;
                questToolsSettingsChanged = true;
                thingsThatChanged        += "TrialRiftMaxLevel,";
            }

            if (questToolsSettingsChanged)
            {
                Logr.Log("Updated QuestTools Settings From Leader: " + thingsThatChanged);
                QuestToolsSettings.Instance.Save();
            }
        }
示例#21
0
        /// <summary>
        /// Clicks a UI Element after a random interval.
        /// </summary>
        /// <param name="uiElement"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        internal static bool SafeClick(UIElement uiElement, ClickDelay delayOption, string name = "", int postClickThreadSleepDuration = 0, bool fireWorldTransferStart = false)
        {
            try
            {
                if (DateTime.UtcNow.Subtract(_lastClick).TotalMilliseconds < 500)
                {
                    return(false);
                }

                if (ElementIsVisible(uiElement, name))
                {
                    if (!String.IsNullOrEmpty(name))
                    {
                        Logr.Debug("{0} button is visible", name);
                    }
                    else
                    {
                        Logr.Debug("{0}={1} is visible", uiElement.Hash, uiElement.Name);
                    }

                    if (!clickTimer.IsRunning && delayOption == ClickDelay.Delay)
                    {
                        clickTimer.Start();
                        SetClickTimerRandomVal();
                    }
                    else if ((ClickTimerRandomReady() && ElementIsVisible(uiElement, name)) || delayOption == ClickDelay.NoDelay)
                    {
                        if (!String.IsNullOrEmpty(name))
                        {
                            Logr.Log("Clicking {0} button", name);
                        }
                        else
                        {
                            Logr.Log("Clicking {0}={1}", uiElement.Hash, uiElement.Name);
                        }

                        // sleep plugins for a bit
                        if (ZetaDia.IsInGame && fireWorldTransferStart)
                        {
                            GameEvents.FireWorldTransferStart();
                        }

                        _lastClick = DateTime.UtcNow;
                        uiElement.Click();
                        //BotMain.PauseFor(TimeSpan.FromMilliseconds(ClickThreadSleepInterval));

                        //if (postClickThreadSleepDuration > 0)
                        //    BotMain.PauseFor(TimeSpan.FromMilliseconds(postClickThreadSleepDuration));

                        clickTimer.Reset();
                    }
                    else
                    {
                        Logr.Debug("Pausing bot, waiting for {0}={1}", uiElement.Hash, uiElement.Name);
                        BotMain.PauseWhile(ClickTimerRandomNotReady, 0, ClickTimerTimeout);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Logr.Log("Error clicking UI button {0}: " + ex.ToString(), name);
                return(false);
            }
        }
示例#22
0
        private static async Task <bool> OpenRiftTask()
        {
            // Move to and use Greater Rift Portal
            if (ZetaDia.Me.IsParticipatingInTieredLootRun && ZetaDia.IsInTown && ZetaDia.CurrentLevelAreaId == (int)SNOLevelArea.x1_Westm_Hub &&
                ConditionParser.IsActiveQuestAndStep((int)SNOQuest.X1_LR_DungeonFinder, 13))
            {
                // [202EBD3C] GizmoType: Portal Name: X1_OpenWorld_Tiered_Rifts_Portal-5041 ActorSNO: 396751 Distance: 11.58544 Position: <606.84, 750.39, 2.53> Barracade: False Radius: 8.316568
                var moveToPortal = new MoveToActorTag
                {
                    QuestId       = (int)SNOQuest.X1_LR_DungeonFinder,
                    StepId        = 13,
                    ActorId       = GreaterRiftPortalSNO,
                    X             = 606,
                    Y             = 750,
                    Z             = 2,
                    IsPortal      = true,
                    InteractRange = 9,
                    Timeout       = 10
                };
                Logr.Log("Queueing MoveToActor for interacting with Greater Rift Portal");
                BotBehaviorQueue.Queue(moveToPortal,
                                       ret => ZetaDia.Me.IsParticipatingInTieredLootRun && ZetaDia.IsInTown && ZetaDia.CurrentLevelAreaId == (int)SNOLevelArea.x1_Westm_Hub &&
                                       !ConditionParser.IsActiveQuestAndStep(337492, 10));
                return(true);
            }

            if (!SimpleFollow.Leader.RequestOpenRift)
            {
                return(false);
            }

            if (HighestLevelTieredRiftKey > SimpleFollow.Leader.HighestTeamRiftKey)
            {
                return(false);
            }

            // In regular rift quests
            if (ConditionParser.IsActiveQuestAndStep(337492, 1) ||
                ConditionParser.IsActiveQuestAndStep(337492, 3) ||
                ConditionParser.IsActiveQuestAndStep(337492, 13) ||
                ConditionParser.IsActiveQuestAndStep(337492, 16))
            {
                return(false);
            }

            // In Rift Trial
            if (ZetaDia.ActInfo.ActiveQuests.Any(q => q.QuestSNO == (int)SNOQuest.p1_TieredRift_Challenge))
            {
                return(false);
            }

            // Our rift key is the lowest of the team, lets open a rift!

            var keyPriorityList = SimpleFollow.Leader.RiftKeyPriority;

            if (keyPriorityList.Count != 3)
            {
                throw new ArgumentOutOfRangeException("RiftKeyPriority", "Expected 3 Rift keys, API is broken?");
            }

            if (ZetaDia.Actors.GetActorsOfType <DiaObject>(true).Any(i => i.IsValid && i.ActorSNO == RiftPortalSNO))
            {
                Logr.Log("Rift Portal already open!");
                return(false);
            }

            if (!ZetaDia.IsInTown)
            {
                return(await CommonCoroutines.UseTownPortal("Going to town to open rift"));
            }

            bool needsGreaterKeys = !ZetaDia.Me.Inventory.Backpack.Any(i => IsRiftKey(i) && IsGreaterRiftKey(i)) &&
                                    ZetaDia.Me.Inventory.StashItems.Any(i => IsRiftKey(i) && IsGreaterRiftKey(i));
            bool needsTrialKeys = !ZetaDia.Me.Inventory.Backpack.Any(i => IsRiftKey(i) && IsTrialRiftKey(i)) &&
                                  ZetaDia.Me.Inventory.StashItems.Any(i => IsRiftKey(i) && IsTrialRiftKey(i));
            bool needsNormalKeys = !ZetaDia.Me.Inventory.Backpack.Any(i => IsRiftKey(i) && IsNormalKey(i)) &&
                                   ZetaDia.Me.Inventory.StashItems.Any(i => IsRiftKey(i) && IsNormalKey(i));

            if (needsGreaterKeys)
            {
                Logr.Log("Moving to stash to get Greater Rift Keys");
                BotBehaviorQueue.Queue(new GetItemFromStashTag {
                    GreaterRiftKey = true, StackCount = 1
                });
                return(true);
            }

            if (needsTrialKeys)
            {
                Logr.Log("Moving to stash to get Trial Rift Keys");
                BotBehaviorQueue.Queue(new GetItemFromStashTag {
                    ActorId = 408416, StackCount = 1
                });
                return(true);
            }

            if (needsNormalKeys)
            {
                Logr.Log("Moving to stash to get Rift Keys");
                BotBehaviorQueue.Queue(new GetItemFromStashTag {
                    ActorId = (int)SNOActor.LootRunKey, StackCount = 1
                });
                return(true);
            }

            int questStepId = 1;
            var quest       = ZetaDia.ActInfo.ActiveQuests.FirstOrDefault(q => q.QuestSNO == (int)SNOQuest.X1_LR_DungeonFinder);

            if (quest != null)
            {
                questStepId = quest.QuestStep;
            }

            if (ZetaDia.IsInTown && !ConditionParser.ActorExistsAt(RiftPortalSNO, 606, 750, 2, 50) && !ConditionParser.ActorExistsAt(GreaterRiftPortalSNO, 606, 750, 2, 50))
            {
                BotBehaviorQueue.Reset();
                Logr.Log("Queueing QTOpenRiftWrapper");
                BotBehaviorQueue.Queue(new QTOpenRiftWrapperTag());
                BotBehaviorQueue.Queue(new WaitTimerTag {
                    QuestId = 337492, StepId = questStepId, WaitTime = 2000
                });
                FollowTag.LastInteractTime = DateTime.Now.AddSeconds(15);
            }

            if (ZetaDia.IsInTown && ConditionParser.ActorExistsAt(RiftPortalSNO, 606, 750, 2, 50) && ConditionParser.IsActiveQuestAndStep(337492, questStepId))
            {
                Logr.Log("Queueing MoveToActor for Rift Portal");
                BotBehaviorQueue.Reset();
                BotBehaviorQueue.Queue(new MoveToActorTag {
                    QuestId = 337492, StepId = questStepId, ActorId = RiftPortalSNO, Timeout = 10
                });
                BotBehaviorQueue.Queue(new WaitTimerTag {
                    QuestId = 337492, StepId = questStepId, WaitTime = 2000
                });
                FollowTag.LastInteractTime = DateTime.Now.AddSeconds(15);
            }
            if (ZetaDia.IsInTown && ConditionParser.ActorExistsAt(GreaterRiftPortalSNO, 606, 750, 2, 50) && ConditionParser.IsActiveQuestAndStep(337492, questStepId))
            {
                Logr.Log("Queueing MoveToActor for Greater Rift Portal");
                BotBehaviorQueue.Reset();
                BotBehaviorQueue.Queue(new MoveToActorTag {
                    QuestId = 337492, StepId = questStepId, ActorId = GreaterRiftPortalSNO, Timeout = 10
                });
                BotBehaviorQueue.Queue(new WaitTimerTag {
                    QuestId = 337492, StepId = questStepId, WaitTime = 2000
                });
                FollowTag.LastInteractTime = DateTime.Now.AddSeconds(15);
            }
            return(true);
        }
示例#23
0
 private static void SetClickTimerRandomVal()
 {
     clickTimerRandomVal = clickDelayRnd.Next(1250, 2250);
     Logr.Log("Random timer set to {0}ms", clickTimerRandomVal);
 }
示例#24
0
        /// <summary>
        /// Checks for known windows, buttons, etc and clicks them
        /// </summary>
        internal static void SafeCheckClickButtons()
        {
            try
            {
                if (!ZetaDia.IsInGame)
                {
                    SafeClick(BattleNetOK, ClickDelay.NoDelay, "Battle.Net OK", 1000, true);
                }

                // limit this thing running to once a second, to save CPU
                if (DateTime.UtcNow.Subtract(lastSafeClickCheck).TotalMilliseconds < 1000)
                {
                    return;
                }

                if (ZetaDia.IsLoadingWorld)
                {
                    return;
                }

                if (ZetaDia.IsPlayingCutscene)
                {
                    return;
                }

                if (!ZetaDia.Service.IsValid)
                {
                    return;
                }

                lastSafeClickCheck = DateTime.UtcNow;

                // Handled seperately out of game
                if (ZetaDia.IsInGame)
                {
                    SafeClick(PartyInviteOK, ClickDelay.Delay, "Party Invite", 750, true);
                }

                SafeClick(GenericOK, ClickDelay.Delay, "Generic OK", 0, true);
                SafeClick(BattleNetOK, ClickDelay.NoDelay, "Battle.Net OK", 1000, true);

                if (!ZetaDia.IsInGame)
                {
                    return;
                }

                if (ZetaDia.Me == null)
                {
                    return;
                }

                if (ZetaDia.Me.IsDead)
                {
                    return;
                }

                if (!ZetaDia.Me.IsValid)
                {
                    return;
                }

                SafeClick(PartyLeaderBossAccept, ClickDelay.NoDelay, "Boss Portal Accept", 0, true);
                SafeClick(PartyFollowerBossAccept, ClickDelay.NoDelay, "Boss Portal Accept", 0, true);
                SafeClick(MercenaryPartyOK, ClickDelay.NoDelay, "Mercenary Party OK");
                SafeClick(CustomizeBannerClose, ClickDelay.NoDelay, "Customize Banner Close");
            }
            catch (Exception ex)
            {
                Logr.Log("Error clicking UI Button: " + ex.ToString());
            }
        }
示例#25
0
        /// <summary>
        /// Out of game check
        /// </summary>
        /// <returns>RunStatus.</returns>
        internal static RunStatus FollowerOutOfGame()
        {
            if (ZetaDia.Service.Hero == null)
            {
                Logr.Log("Error: ZetaDia.Service.Hero is null!");
                return(RunStatus.Failure);
            }

            if (!ZetaDia.Service.Hero.IsValid)
            {
                Logr.Log("Error: ZetaDia.Service.Hero is invalid!");
                return(RunStatus.Failure);
            }

            bool isPartyLeader = Social.IsPartyleader;

            if (!SimpleFollow.Enabled)
            {
                SharedComposites.CheckReplaceOutOfGameHook();
                return(RunStatus.Failure);
            }

            FollowerService.AsyncClientUpdate();

            GameUI.SafeCheckClickButtons();

            if (ZetaDia.IsInGame)
            {
                return(RunStatus.Success);
            }

            const int inviteWaitDelaySeconds = 3;

            if (DateTime.UtcNow.Subtract(_lastClickedOutOfGameInvite).TotalSeconds < inviteWaitDelaySeconds)
            {
                return(RunStatus.Running);
            }

            if (GameUI.ElementIsVisible(GameUI.PartyInviteOK) && DateTime.UtcNow.Subtract(_lastClickedOutOfGameInvite).TotalMilliseconds > inviteWaitDelaySeconds)
            {
                _lastClickedOutOfGameInvite = DateTime.UtcNow;
                GameUI.SafeClick(GameUI.PartyInviteOK, ClickDelay.NoDelay, "Party Invite", 1500, true);
                GameEvents.FireWorldTransferStart();
                return(RunStatus.Running);
            }

            if (Social.IsPartyleader && GameUI.ElementIsVisible(GameUI.OutOfGameLeavePartyButton) && DateTime.UtcNow.Subtract(_lastClickedOutOfGameInvite).TotalSeconds > inviteWaitDelaySeconds)
            {
                Logr.Log("We are party leader and out of game, leaving party to re-create");
                GameUI.SafeClick(GameUI.OutOfGameLeavePartyButton, ClickDelay.NoDelay, "Leave Party Button", 1000);
                return(RunStatus.Running);
            }

            if (!isPartyLeader && SimpleFollow.Leader.IsInGame && GameUI.ElementIsVisible(GameUI.OutOfGameLeavePartyButton))
            {
                Logr.Log("We are Out of game, Leader is In Game - Leaving Party for re-invite");
                GameUI.SafeClick(GameUI.OutOfGameLeavePartyButton, ClickDelay.NoDelay, "Leave Party Button", 1000);
                return(RunStatus.Running);
            }

            if (SimpleFollow.Leader.IsInGame && !isPartyLeader && GameUI.ElementIsVisible(GameUI.PartySlot2Icon, "Party Slot 2 Icon"))
            {
                Logr.Log("We are Out of game, Leader is In Game - Resuming game");
                GameUI.SafeClick(GameUI.PlayGameButton, ClickDelay.NoDelay, "Play Game Button", 1000);
                return(RunStatus.Running);
            }

            if (isPartyLeader && !Social.IsInParty)
            {
                Logr.Log("Out of game, Waiting for Invite");
                return(RunStatus.Running);
            }

            Logr.Log("Out of game, Waiting for leader");
            return(RunStatus.Running);
        }
示例#26
0
 public void Run(BrowserHost host, PipeServer server)
 {
     Logr.Log("Received NavigateTask request from network.");
     host.LoadPageAsync(url);
 }
示例#27
0
        /// <summary>
        /// Used by leaders and followers to pass updates
        /// </summary>
        /// <returns></returns>
        public static Message GetMessage()
        {
            try
            {
                Message m;

                if (!ZetaDia.Service.IsValid || !ZetaDia.Service.Platform.IsConnected)
                {
                    m = new Message
                    {
                        LastTimeUpdated = DateTime.UtcNow,
                        IsInGame        = false
                    };
                    return(m);
                }
                if (ZetaDia.IsInGame && !ZetaDia.IsLoadingWorld && ZetaDia.Me.IsFullyValid())
                {
                    m = new Message
                    {
                        LastTimeUpdated       = DateTime.UtcNow,
                        LastTimeInGame        = DateTime.UtcNow,
                        IsInGame              = ZetaDia.IsInGame,
                        BattleTagHash         = ZetaDia.Service.Hero.BattleTagName.GetHashCode(),
                        IsInParty             = Social.IsInParty,
                        NumPartymembers       = Social.NumPartyMembers,
                        IsLoadingWorld        = ZetaDia.IsLoadingWorld,
                        ActorClass            = ZetaDia.Me.ActorClass,
                        ActorSNO              = ZetaDia.Me.ActorSNO,
                        GameId                = ZetaDia.Service.CurrentGameId,
                        HitpointsCurrent      = ZetaDia.Me.HitpointsCurrent,
                        HitpointsMaxTotal     = ZetaDia.Me.HitpointsMaxTotal,
                        LevelAreaId           = Player.LevelAreaId,
                        IsInTown              = Player.LevelAreaId != 55313 && ZetaDia.IsInTown, // A2 Caldeum Bazaar
                        Position              = ZetaDia.Me.Position,
                        ProfilePosition       = GetProfilePosition(),
                        ProfileActorSNO       = GetProfileActorSNO(),
                        ProfilePathPrecision  = GetProfilePathPrecision(),
                        ProfileWaypointNumber = GetProfileWaypointNumber(),
                        ProfileTagName        = GetProfileTagname(),
                        IsInCombat            = GetIsInCombat(),
                        WorldId               = ZetaDia.CurrentWorldId,
                        IsVendoring           = BrainBehavior.IsVendoring,
                        IsInGreaterRift       = Player.IsInGreaterRift,
                        CPlayerIndex          = ZetaDia.CPlayer.Index,
                    };

                    if (m.IsInTown)
                    {
                        List <ACDItem> riftKeys = ZetaDia.Me.Inventory.StashItems.Where(i => i.IsValid && i.ItemType == ItemType.KeystoneFragment).ToList();
                        riftKeys.AddRange(ZetaDia.Me.Inventory.Backpack.Where(i => i.IsValid && i.GoodFood == 0xCEFAEDFE && i.ItemType == ItemType.KeystoneFragment).ToList());
                        m.HasRiftKeys = riftKeys.Any();
                        int maxLevel = -1;
                        try
                        {
                            // m.HighestLevelTieredRiftKey = riftKeys.Any() ? riftKeys.Max(i => i.TieredLootRunKeyLevel) : -1;
                            foreach (var key in riftKeys)
                            {
                                try
                                {
                                    int level = key.TieredLootRunKeyLevel;
                                    if (level > maxLevel)
                                    {
                                        maxLevel = level;
                                    }
                                }
                                catch {
                                    // Tell me you love me
                                }
                            }
                        }
                        catch
                        {
                            // You lose!!
                        }
                        m.HighestLevelTieredRiftKey = maxLevel;

                        if (SimpleFollow.IsLeader)
                        {
                            m.RequestOpenRift         = LeaderComposite.ShouldFollowerOpenRift();
                            m.RiftKeyPriority         = QuestToolsSettings.Instance.RiftKeyPriority;
                            m.UseHighestKeystone      = QuestToolsSettings.Instance.UseHighestKeystone;
                            m.MinimumGemChance        = QuestToolsSettings.Instance.MinimumGemChance;
                            m.EnableLimitRiftLevel    = QuestToolsSettings.Instance.EnableLimitRiftLevel;
                            m.LimitRiftLevel          = QuestToolsSettings.Instance.LimitRiftLevel;
                            m.EnableTrialRiftMaxLevel = QuestToolsSettings.Instance.EnableTrialRiftMaxLevel;
                            m.TrialRiftMaxLevel       = QuestToolsSettings.Instance.TrialRiftMaxLevel;
                        }
                    }
                }
                else if (ZetaDia.IsInGame && ZetaDia.IsLoadingWorld)
                {
                    m = new Message
                    {
                        IsInGame        = true,
                        IsLoadingWorld  = true,
                        GameId          = ZetaDia.Service.CurrentGameId,
                        LastTimeInGame  = DateTime.UtcNow,
                        BattleTagHash   = ZetaDia.Service.Hero.BattleTagName.GetHashCode(),
                        IsInTown        = false,
                        WorldId         = -1,
                        LevelAreaId     = -1,
                        LastTimeUpdated = DateTime.UtcNow,
                        IsInParty       = Social.IsInParty,
                        NumPartymembers = Social.NumPartyMembers,
                        ActorClass      = ZetaDia.Service.Hero.Class,
                    };
                }
                else
                {
                    m = new Message
                    {
                        IsInGame        = false,
                        IsInTown        = false,
                        BattleTagHash   = ZetaDia.Service.Hero.BattleTagName.GetHashCode(),
                        WorldId         = -1,
                        LastTimeUpdated = DateTime.UtcNow,
                        IsInParty       = Social.IsInParty,
                        NumPartymembers = Social.NumPartyMembers,
                        ActorClass      = ZetaDia.Service.Hero.Class,
                    };
                }
                return(m);
            }
            catch (Exception ex)
            {
                Logr.Log("Exception in GetMessage() {0}", ex);
                return(new Message());
            }
        }