Example #1
0
        /// <summary>
        /// Is called whenever a web browser loaded a new page.
        /// Usage: After navigation (has to execute) and after execution (click on button etc.)
        /// In first case execute the task, in second remove it.
        /// </summary>
        /// <param name="acc"></param>
        public static async Task PageLoaded(Account acc)
        {
            if (IsCaptcha(acc) || IsWWMsg(acc) || IsBanMsg(acc) || IsMaintanance(acc)) //Check if a captcha/ban/end of server/maintanance
            {
                acc.Wb.Log("Captcha/WW/Ban/Maintanance found! Stopping bot for this account!");
                acc.TaskTimer.Stop();
                return;
            }
            if (CheckCookies(acc))
            {
                await DriverHelper.ExecuteScript(acc, "document.getElementById('CybotCookiebotDialogBodyLevelButtonLevelOptinDeclineAll').click();");
            }
            if (CheckCookiesNew(acc))
            {
                await DriverHelper.ExecuteScript(acc, "document.getElementsByClassName('cmpboxbtnyes')[0].click();");
            }

            if (CheckContextualHelp(acc) &&
                acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.T4_5)
            {
                AddTaskIfNotExists(acc, new EditPreferences()
                {
                    ExecuteAt      = DateTime.Now.AddHours(-1),
                    TroopsPerPage  = 99,
                    ContextualHelp = true
                });
            }

            if (acc.AccInfo.Tribe == null && CheckSkipTutorial(acc))
            {
                await DriverHelper.ClickByClassName(acc, "questButtonSkipTutorial");
            }

            if (IsLoginScreen(acc)) //Check if you are on login page -> Login task
            {
                AddTask(acc, new LoginTask()
                {
                    ExecuteAt = DateTime.MinValue
                });
                return;
            }
            if (IsSysMsg(acc)) //Check if there is a system message (eg. Artifacts/WW plans appeared)
            {
                await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php?ok");

                await Task.Delay(AccountHelper.Delay());
            }

            //TODO: limit this for performance reasons?
            PostLoadTasks(acc);
        }
Example #2
0
        /// <summary>
        /// Called PageLoaded (after navigating to a specific url) or from
        /// Task timer, if there is no url/bot is already on the url
        /// </summary>
        /// <param name="acc">Account</param>
        /// <param name="task">Task to be executed</param>
        /// <returns></returns>
        public static async Task Execute(Account acc, BotTask task)
        {
            // Before every execution, wait a random delay
            if (acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.T4_5)
            {
                await Task.Delay(AccountHelper.Delay());
            }

            if (acc.Wb?.CurrentUrl == null && task.GetType() != typeof(CheckProxy))
            {
                await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php");
            }

            if (task.Vill == null)
            {
                task.Vill = acc.Villages.FirstOrDefault(x => x.Active);
            }

            try
            {
                acc.Wb.Log($"Executing task {task.GetName()}" + (task.Vill == null ? "" : $" in village {task.Vill.Name}"));

                switch (await task.Execute(acc))
                {
                case TaskRes.Retry:
                    task.RetryCounter++;
                    if (task.NextExecute == null)
                    {
                        task.NextExecute = DateTime.Now.AddMinutes(3);
                    }
                    break;

                default:
                    task.RetryCounter = 0;
                    if (task.NextTask != null)
                    {
                        task.NextTask.ExecuteAt = DateTime.MinValue.AddHours(5);
                        task.NextTask.Stage     = TaskStage.Start;
                        TaskExecutor.AddTask(acc, task.NextTask);
                        task.NextTask = null;
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                if (acc.Wb != null)
                {
                    acc.Wb.Log($"Error executing task {task.GetName()}! Vill {task.Vill?.Name}", e);
                }
                task.RetryCounter++;
                if (task.NextExecute == null)
                {
                    task.NextExecute = DateTime.Now.AddMinutes(3);
                }
            }

            //We want to re-execute the same task later
            if (task.NextExecute != null && task.RetryCounter < 3)
            {
                task.ExecuteAt   = task.NextExecute ?? default;
                task.NextExecute = null;
                ReorderTaskList(acc);
                task.Stage = TaskStage.Start;
                return;
            }
            // Remove the task from the task list
            acc.Tasks.Remove(task);
        }
        /// <summary>
        /// Used by BotTasks to insert resources/coordinates into the page.
        /// </summary>
        /// <param name="acc">Account</param>
        /// <param name="resources">Target resources</param>
        /// <param name="coordinates">Target coordinates</param>
        /// <returns>Time it will take for transit to complete</returns>
        public static async Task <TimeSpan> MarketSendResource(Account acc, long[] resources, Village targetVillage, BotTask botTask)
        {
            var times = 1;

            if (acc.AccInfo.GoldClub ?? false)
            {
                times = 3;
            }
            else if (acc.AccInfo.PlusAccount)
            {
                times = 2;
            }

            var sendRes = resources.Select(x => x / times).ToArray();

            //round the resources that we want to send, so it looks less like a bot

            //TODO: check if we have enough merchants
            (var merchantsCapacity, var merchantsNum) = MarketHelper.ParseMerchantsInfo(acc.Wb.Html);
            // We don't have any merchants.
            if (merchantsNum == 0)
            {
                //Parse currently ongoing transits
                var transits   = MarketParser.ParseTransits(acc.Wb.Html);
                var activeVill = acc.Villages.FirstOrDefault(x => x.Active); // Could also just pass that in params

                var nextTry = SoonestAvailableMerchants(acc, activeVill, targetVillage, transits);

                botTask.NextExecute = nextTry.AddSeconds(5);
                // Just return something, will get overwritten anyways.
                return(new TimeSpan((int)(nextTry - DateTime.Now).TotalHours + 1, 0, 0));
            }

            var maxRes = merchantsCapacity * times;
            var allRes = resources.Sum();

            if (allRes > maxRes)
            {
                // We don't have enough merchants to transit all the resources. Divide all resources by some divider.
                var     resDivider = (float)allRes / maxRes;
                float[] resFloat   = sendRes.Select(x => x / resDivider).ToArray();
                sendRes = resFloat.Select(x => (long)Math.Floor(x)).ToArray();
            }

            var wb = acc.Wb.Driver;

            for (int i = 0; i < 4; i++)
            {
                // To avoid exception devide by zero
                if (sendRes[i] != 0)
                {
                    //round the number to about -1%, for rounder numbers
                    var digits    = Math.Ceiling(Math.Log10(sendRes[i]));
                    var remainder = sendRes[i] % (long)Math.Pow(10, digits - 2);
                    sendRes[i] -= remainder;
                }
                wb.ExecuteScript($"document.getElementById('r{i + 1}').value='{sendRes[i]}'");
                await Task.Delay(AccountHelper.Delay() / 5);
            }

            wb.ExecuteScript($"document.getElementById('xCoordInput').value='{targetVillage.Coordinates.x}'");
            await Task.Delay(AccountHelper.Delay() / 5);

            wb.ExecuteScript($"document.getElementById('yCoordInput').value='{targetVillage.Coordinates.y}'");
            await Task.Delay(AccountHelper.Delay() / 5);

            //Select x2/x3
            if (times != 1)
            {
                wb.ExecuteScript($"document.getElementById('x2').value='{times}'");
                await Task.Delay(AccountHelper.Delay() / 5);
            }

            // Some bot protection here I guess. Just remove the class of the DOM.
            var script = @"
                    var button = document.getElementById('enabledButton');
                    button.click();
                    ";

            wb.ExecuteScript(script); //Prepare

            //update htmlDoc, parse duration, TODO: maybe some other method to wait until the page is loaded?
            HtmlNode durNode = null;

            do
            {
                await Task.Delay(AccountHelper.Delay());

                HtmlDocument html2 = new HtmlDocument();
                html2.LoadHtml(wb.PageSource);
                durNode = html2.GetElementbyId("target_validate");
            }while (durNode == null);

            //get duration of transit
            var dur = durNode.Descendants("td").ToList()[3].InnerText.Replace("\t", "").Replace("\n", "");

            // Will NOT trigger a page reload! Thus we should await some time before continuing.
            wb.ExecuteScript("document.getElementById('enabledButton').click()"); //SendRes

            await Task.Delay(AccountHelper.Delay() * 2);

            var duration = TimeParser.ParseDuration(dur);

            return(TimeSpan.FromTicks(duration.Ticks * (times * 2 - 1)));
        }
Example #4
0
        /// <summary>
        /// Used by BotTasks to insert resources/coordinates into the page.
        /// </summary>
        /// <param name="acc">Account</param>
        /// <param name="resources">Target resources</param>
        /// <param name="coordinates">Target coordinates</param>
        /// <returns>Time it will take for transit to complete</returns>
        public static async Task <TimeSpan> MarketSendResource(Account acc, long[] resources, Village targetVillage, BotTask botTask)
        {
            var times = 1;

            if (acc.AccInfo.GoldClub ?? false)
            {
                times = 3;
            }
            else if (acc.AccInfo.PlusAccount)
            {
                times = 2;
            }

            // No resources to send
            if (resources.Sum() == 0)
            {
                return(TimeSpan.Zero);
            }

            var sendRes = resources.Select(x => x / times).ToArray();

            //round the resources that we want to send, so it looks less like a bot

            (var merchantsCapacity, var merchantsNum) = MarketHelper.ParseMerchantsInfo(acc.Wb.Html);
            // We don't have any merchants.
            if (merchantsNum == 0)
            {
                //Parse currently ongoing transits
                var transits   = MarketParser.ParseTransits(acc.Wb.Html);
                var activeVill = acc.Villages.FirstOrDefault(x => x.Active); // Could also just pass that in params

                var nextTry = SoonestAvailableMerchants(acc, activeVill, targetVillage, transits);
                if (nextTry != DateTime.MaxValue)
                {
                    nextTry = nextTry.AddSeconds(5);
                }

                botTask.NextExecute = nextTry;
                // Just return something, will get overwritten anyways.
                return(new TimeSpan((int)(nextTry - DateTime.Now).TotalHours + 1, 0, 0));
            }

            var maxRes = merchantsCapacity * times;
            var allRes = resources.Sum();

            if (allRes > maxRes)
            {
                // We don't have enough merchants to transit all the resources. Divide all resources by some divider.
                var     resDivider = (float)allRes / maxRes;
                float[] resFloat   = sendRes.Select(x => x / resDivider).ToArray();
                sendRes = resFloat.Select(x => (long)Math.Floor(x)).ToArray();
            }

            var wb = acc.Wb.Driver;

            for (int i = 0; i < 4; i++)
            {
                // To avoid exception devide by zero
                if (50 <= sendRes[i])
                {
                    //round the number to about -1%, for rounder numbers
                    var digits    = Math.Ceiling(Math.Log10(sendRes[i]));
                    var remainder = sendRes[i] % (long)Math.Pow(10, digits - 2);
                    sendRes[i] -= remainder;
                    await DriverHelper.WriteById(acc, "r" + (i + 1), sendRes[i]);
                }
                await Task.Delay(AccountHelper.Delay() / 5);
            }

            // Input coordinates
            await DriverHelper.WriteCoordinates(acc, targetVillage.Coordinates);

            //Select x2/x3
            if (times != 1)
            {
                wb.ExecuteScript($"document.getElementById('x2').value='{times}'");
                await Task.Delay(AccountHelper.Delay() / 5);
            }
            await DriverHelper.ClickById(acc, "enabledButton");

            var durNode = acc.Wb.Html.GetElementbyId("target_validate");

            if (durNode == null && acc.Wb.Html.GetElementbyId("prepareError") != null)
            {
                // Error "Abuse! You have not enough resources." is displayed.
            }
            //get duration of transit
            var dur = durNode.Descendants("td").ToList()[3].InnerText.Replace("\t", "").Replace("\n", "");

            // Will NOT trigger a page reload! Thus we should await some time before continuing.
            await DriverHelper.ClickById(acc, "enabledButton");

            targetVillage.Market.LastTransit = DateTime.Now;

            var duration = TimeParser.ParseDuration(dur);

            return(TimeSpan.FromTicks(duration.Ticks * (times * 2 - 1)));
        }
        /// <summary>
        /// Will be called before each task to update resources/msg?,villages,quests,hero health, adventures num, gold/silver
        /// </summary>
        /// <param name="acc">Account</param>
        /// <returns>True if successful, false if error</returns>
        private static bool PreTaskRefresh(Account acc)
        {
            var html = acc.Wb.Html;

            try
            {
                //check & update dorf1/dorf2
                if (!UpdateAccountObject.UpdateVillages(html, acc))
                {
                    return(false);                                                //Web browser not initiali
                }
                var activeVill = acc.Villages.FirstOrDefault(x => x.Active);
                //update dorf1/dorf2
                if (acc.Wb.CurrentUrl.Contains("dorf1"))
                {
                    UpdateDorf1Info(acc);
                }
                else if (acc.Wb.CurrentUrl.Contains("dorf2"))
                {
                    UpdateDorf2Info(acc);
                }


                acc.AccInfo.CulturePoints = RightBarParser.GetCulurePoints(html, acc.AccInfo.ServerVersion);

                var villExpansionReady = acc.Villages.FirstOrDefault(x => x.Expansion.ExpensionAvailable);
                if (acc.AccInfo.CulturePoints.MaxVillages > acc.AccInfo.CulturePoints.VillageCount &&
                    villExpansionReady != null)
                {
                    villExpansionReady.Expansion.ExpensionAvailable = false;
                    TaskExecutor.AddTaskIfNotExists(acc, new SendSettlers()
                    {
                        ExecuteAt = DateTime.Now, vill = villExpansionReady
                    });
                }

                acc.AccInfo.Tribe = LeftBarParser.GetAccountTribe(acc, html);
                acc.Quests        = RightBarParser.GetQuests(html);
                var goldSilver = RightBarParser.GetGoldAndSilver(html, acc.AccInfo.ServerVersion);
                acc.AccInfo.Gold        = goldSilver[0];
                acc.AccInfo.Silver      = goldSilver[1];
                acc.AccInfo.PlusAccount = RightBarParser.HasPlusAccount(html, acc.AccInfo.ServerVersion);
                //Check reports/msg count
                if (MsgParser.UnreadMessages(html, acc.AccInfo.ServerVersion) > 0 &&
                    !acc.Wb.CurrentUrl.Contains("messages.php") &&
                    !IsTaskOnQueue(acc, typeof(ReadMessage)))
                {
                    TaskExecutor.AddTask(acc, new ReadMessage()
                    {
                        ExecuteAt = DateTime.Now.AddMilliseconds(AccountHelper.Delay() * 30)
                    });
                }

                //update loyalty of village


                activeVill.Res.FreeCrop = RightBarParser.GetFreeCrop(html);
                activeVill.Res.Capacity = ResourceParser.GetResourceCapacity(html, acc.AccInfo.ServerVersion);
                activeVill.Res.Stored   = ResourceParser.GetResources(html);

                float ratio = (float)activeVill.Res.Stored.Resources.Crop / activeVill.Res.Capacity.GranaryCapacity;
                if (ratio >= 0.99 &&
                    acc.AccInfo.Gold >= 3 &&
                    activeVill.Market.Npc.Enabled &&
                    (activeVill.Market.Npc.NpcIfOverflow || !MarketHelper.NpcWillOverflow(activeVill)))
                {  //npc crop!
                    TaskExecutor.AddTaskIfNotExistInVillage(acc, activeVill, new NPC()
                    {
                        ExecuteAt = DateTime.MinValue,
                        vill      = activeVill
                    });
                }
                if (acc.Settings.AutoActivateProductionBoost && CheckProductionBoost(acc))
                {
                    TaskExecutor.AddTask(acc, new TTWarsPlusAndBoost()
                    {
                        ExecuteAt = DateTime.Now.AddSeconds(1)
                    });
                }

                acc.Hero.AdventureNum    = HeroParser.GetAdventureNum(html, acc.AccInfo.ServerVersion);
                acc.Hero.Status          = HeroParser.HeroStatus(html, acc.AccInfo.ServerVersion);
                acc.Hero.HeroInfo.Health = HeroParser.GetHeroHealth(html, acc.AccInfo.ServerVersion);

                bool heroReady = (acc.Hero.HeroInfo.Health > acc.Hero.Settings.MinHealth &&
                                  acc.Hero.Settings.AutoSendToAdventure &&
                                  acc.Hero.Status == Hero.StatusEnum.Home &&
                                  acc.Hero.NextHeroSend < DateTime.Now);
                // Update adventures
                if (heroReady &&
                    (acc.Hero.AdventureNum != acc.Hero.Adventures.Count() || HeroHelper.AdventureInRange(acc))) //update adventures
                {
                    AddTaskIfNotExists(acc, new StartAdventure()
                    {
                        ExecuteAt = DateTime.Now.AddSeconds(10)
                    });
                }
                if (acc.Hero.AdventureNum == 0 && acc.Hero.Settings.BuyAdventures) //for UNL servers, buy adventures
                {
                    AddTaskIfNotExists(acc, new TTWarsBuyAdventure()
                    {
                        ExecuteAt = DateTime.Now.AddSeconds(5)
                    });
                }
                if (acc.Hero.Status == Hero.StatusEnum.Dead && acc.Hero.Settings.AutoReviveHero) //if hero is dead, revive him
                {
                    AddTaskIfNotExists(acc, new ReviveHero()
                    {
                        ExecuteAt = DateTime.Now.AddSeconds(5), vill = AccountHelper.GetHeroReviveVillage(acc)
                    });
                }
                if (HeroParser.LeveledUp(html) && acc.Hero.Settings.AutoSetPoints)
                {
                    AddTaskIfNotExists(acc, new HeroSetPoints()
                    {
                        ExecuteAt = DateTime.Now
                    });
                }
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in PreTask " + e.Message + "\n\nStack Trace: " + e.StackTrace + "\n-----------------------");
                return(false);
            }
        }