/// <summary>
        /// </summary>
        /// <param name="parameter">FortData containing the Pokestop that we're visiting</param>
        /// <param name="mode"></param>
        /// <param name="suspensionState"></param>
        /// <returns></returns>
        public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode,
                                                      IDictionary <string, object> suspensionState)
        {
            if (suspensionState.Any())
            {
                // Recovering the state
                CurrentPokestopInfo   = new FortDetailsResponse();
                CurrentSearchResponse = new FortSearchResponse();
                CurrentPokestop       = JsonConvert.DeserializeObject <FortDataWrapper>((string)suspensionState[nameof(CurrentPokestop)]);
                CurrentPokestopInfo.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(CurrentPokestop)]).CreateCodedInput());
                CurrentSearchResponse.MergeFrom(ByteString.FromBase64((string)suspensionState[nameof(CurrentSearchResponse)]).CreateCodedInput());
            }
            else
            {
                // Navigating from game page, so we need to actually load the Pokestop
                Busy.SetBusy(true, "Loading Pokestop");
                CurrentPokestop = (FortDataWrapper)NavigationHelper.NavigationState[nameof(CurrentPokestop)];
                NavigationHelper.NavigationState.Remove(nameof(CurrentPokestop));
                Logger.Write($"Searching {CurrentPokestop.Id}");
                CurrentPokestopInfo =
                    await GameClient.GetFort(CurrentPokestop.Id, CurrentPokestop.Latitude, CurrentPokestop.Longitude);

                Busy.SetBusy(false);
                // If timeout is expired we can go to to pokestop page
                if (CurrentPokestop.CooldownCompleteTimestampMs >= DateTime.UtcNow.ToUnixTime())
                {
                    // Timeout is not expired yet, player can't get items from the fort
                    SearchInCooldown?.Invoke(null, null);
                }
            }
        }
        private async void getForts()
        {
            var mapObjects = await this._session.Client.Map.GetMapObjects();

            // Wasn't sure how to make this pretty. Edit as needed.
            var forts = mapObjects.Item1.MapCells.SelectMany(i => i.Forts);

            foreach (var fort in forts)
            {
                FortDetailsResponse tmp = new FortDetailsResponse();
                tmp.Name        = "Unknown name";
                tmp.Description = "";

                var fortInfo = tmp;// await this._session.Client.Fort.GetFort(fort.Id, fort.Latitude, fort.Longitude);
                if (fort.Type == FortType.Checkpoint)
                {
                    bool   hasLure = fort.LureInfo != null && fort.LureInfo.LureExpiresTimestampMs > 0;
                    long   exp     = hasLure ? fort.LureInfo.LureExpiresTimestampMs : 0;
                    string marker  = hasLure ? "fort-lure.png" : "fort-pokestop.png";
                    string extra   = $"{{\"hasLure\": {hasLure.ToString().ToLower()}, \"lureGone\": {exp}, \"Description\": \"{fortInfo.Description}\", \"ImageUrls\": \"{/*fortInfo.ImageUrls.ToString().Replace("\"","'")*/""}\",\"marker\" : \"{marker}\" }}";
                    this.setFort(fort.Type.ToString(), fort.Id, fort.Longitude.ToString(), fort.Latitude.ToString(), fortInfo.Name, extra);
                }
                else if (fort.Type == FortType.Gym)
                {
                    bool   hasLure = fort.LureInfo != null && fort.LureInfo.LureExpiresTimestampMs > 0;
                    long   exp     = hasLure ? fort.LureInfo.LureExpiresTimestampMs : 0;
                    string marker  = $"fort-{fort.OwnedByTeam.ToString().ToLower()}.png";
                    string extra   = $"{{\"GuardPokemonCp\": {fort.GuardPokemonCp}, \"GuardPokemonId\": \"{fort.GuardPokemonId.ToString()}\", \"Description\": \"{fortInfo.Description}\", \"ImageUrls\": \"{fortInfo.ImageUrls.ToString().Replace("\"", "")}\",\"marker\": \"{marker}\" }}";
                    this.setFort(fort.Type.ToString(), fort.Id, fort.Longitude.ToString(), fort.Latitude.ToString(), fortInfo.Name, extra);
                }
            }
        }
Exemple #3
0
        public static async Task Execute(ISession session, double lat, double lng, string fortId = "")
        {
            await Task.Run(() =>
            {
                if (!string.IsNullOrEmpty(fortId))
                {
                    var knownFort = session.Forts.FirstOrDefault(x => x.Id == fortId);
                    if (knownFort != null)
                    {
                        _targetStop = knownFort;
                        return;
                    }
                }
                //at this time only allow one target, can't be cancel
                if (_targetStop == null || _targetStop.CooldownCompleteTimestampMs == 0)
                {
                    _targetStop = new FortData()
                    {
                        Latitude  = lat,
                        Longitude = lng,
                        Id        = TARGET_ID,
                        Type      = FortType.Checkpoint,
                        CooldownCompleteTimestampMs = DateTime.UtcNow.AddHours(1).ToUnixTime()  //make sure bot not try to spin this fake pokestop
                    };

                    _fortInfo = new FortDetailsResponse()
                    {
                        Latitude  = lat,
                        Longitude = lng,
                        Name      = "Your selected location"
                    };
                }
            });
        }
Exemple #4
0
        public FortLocation(double lat, double lng, double alt, FortData fortData, FortDetailsResponse fortInfo)  : base(lat, lng, alt)
        {
            this.FortData = fortData;

            if (fortInfo != null)
            {
                this.FortInfo = fortInfo;
                this.Name     = fortInfo.Name;
            }
        }
Exemple #5
0
 public static void CheckSetMoveToTargetStatus(ref FortDetailsResponse fortInfo, ref FortData pokeStop)
 {
     if (SetMoveToTargetEnabled)
     {
         SetMoveToTargetAccept = true;
         fortInfo.Name         = "User Destination.";
         fortInfo.Latitude     = pokeStop.Latitude = SetMoveToTargetLat;
         fortInfo.Longitude    = pokeStop.Longitude = SetMoveToTargetLng;
     }
 }
Exemple #6
0
        private static async Task DeployPokemonToGym(ISession session, FortDetailsResponse fortInfo, GetGymDetailsResponse fortDetails)
        {
            var pokemon = await GetDeployablePokemon(session);

            if (pokemon != null)
            {
                var response = await session.Client.Fort.FortDeployPokemon(fortInfo.FortId, pokemon.Id);

                if (response.Result == FortDeployPokemonResponse.Types.Result.Success)
                {
                    session.EventDispatcher.Send(new GymDeployEvent()
                    {
                        PokemonId = pokemon.PokemonId,
                        Name      = fortDetails.Name
                    });
                }
            }
        }
Exemple #7
0
 public void Save(FortDetailsResponse fortInfo, string filePath, double currentAltitude)
 {
     try
     {
         var data = new Xml.Pokestop();
         data.Id          = fortInfo.FortId;
         data.Latitude    = fortInfo.Latitude;
         data.Longitude   = fortInfo.Longitude;
         data.Altitude    = currentAltitude;
         data.Name        = fortInfo.Name;
         data.Description = fortInfo.Description;
         data.Fp          = fortInfo.Fp;
         foreach (var img in fortInfo.ImageUrls)
         {
             data.ImageUrls.Add(img);
         }
         Xml.Serializer.SerializeToFile(data, filePath);
     }
     catch// (Exception e)
     {
         //Logger.Write($"Could not save the pokestop information file for {fortInfo.FortId} - {e.ToString()}", LogLevel.Error);
     }
 }
Exemple #8
0
 private static async Task WalkingBackGPXPath(ISession session, CancellationToken cancellationToken,
                                              FortData originalPokestop, FortDetailsResponse fortInfo)
 {
     var destination = new FortLocation(
         originalPokestop.Latitude,
         originalPokestop.Longitude,
         LocationUtils.getElevation(
             session.ElevationService,
             originalPokestop.Latitude,
             originalPokestop.Longitude
             ),
         originalPokestop,
         fortInfo
         );
     await session.Navigation.Move(destination,
                                   async() =>
     {
         await MSniperServiceTask.Execute(session, cancellationToken);
         await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
         await UseNearbyPokestopsTask.SpinPokestopNearBy(session, cancellationToken);
     },
                                   session,
                                   cancellationToken);
 }
Exemple #9
0
        private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false)
        {
            // If the cooldown is in the future than don't farm the pokestop.
            if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime())
            {
                return;
            }

            if (session.Stats.SearchThresholdExceeds(session, true))
            {
                if (session.LogicSettings.AllowMultipleBot && session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit)
                {
                    throw new Exceptions.ActiveSwitchByRuleException(SwitchRules.SpinPokestopReached, session.LogicSettings.PokeStopLimit);
                }
                return;
            }

            //await session.Client.Map.GetMapObjects();
            FortSearchResponse fortSearch;
            var timesZeroXPawarded = 0;
            var fortTry            = 0;                                     //Current check
            int retryNumber        = session.LogicSettings.ByPassSpinCount; //How many times it needs to check to clear softban
            int zeroCheck          = Math.Min(5, retryNumber);              //How many times it checks fort before it thinks it's softban

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                int retry = 3;
                do
                {
                    fortSearch =
                        await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                    if (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange)
                    {
                        if (retry < 2)
                        {
                            await session.Client.Map.GetMapObjects(true);
                        }
                        var distance = LocationUtils.CalculateDistanceInMeters(pokeStop.Latitude, pokeStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);
#if DEBUG
                        Logger.Write($"Loot pokestop result :{fortSearch.Result} , distance to pokestop : {distance:0.00}m");
#endif
                        if (distance > 30)
                        {
                            await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinatePortable.GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), 0);
                        }
                        retry--;
                        //await session.Client.Map.GetMapObjects(true);
                    }
                }while (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange && retry > 0);

                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0 && fortSearch.Result != FortSearchResponse.Types.Result.InventoryFull)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });
                        if (doNotRetry)
                        {
                            break;
                        }
                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                        }
                    }
                }
                else
                {
                    softbanCount = 0;
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id            = pokeStop.Id,
                        Name          = fortInfo.Name,
                        Exp           = fortSearch.ExperienceAwarded,
                        Gems          = fortSearch.GemsAwarded,
                        Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Latitude      = pokeStop.Latitude,
                        Longitude     = pokeStop.Longitude,
                        Altitude      = session.Client.CurrentAltitude,
                        InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull,
                        Fort          = pokeStop
                    });
                    if (fortSearch.Result == FortSearchResponse.Types.Result.Success)
                    {
                        mapEmptyCount = 0;
                        foreach (var item in fortSearch.ItemsAwarded)
                        {
                            await session.Inventory.UpdateInventoryItem(item.ItemId);
                        }
                        if (fortSearch.PokemonDataEgg != null)
                        {
                            fortSearch.PokemonDataEgg.IsEgg = true;
                        }

                        // Update the cache
                        var fortFromCache = session.Client.Map.LastGetMapObjectResponse.MapCells.SelectMany(x => x.Forts).FirstOrDefault(f => f.Id == pokeStop.Id);

                        long newCooldown = TimeUtil.GetCurrentTimestampInMilliseconds() + (5 * 60 * 1000); /* 5 min */
                        fortFromCache.CooldownCompleteTimestampMs = newCooldown;
                        pokeStop.CooldownCompleteTimestampMs      = newCooldown;
                    }
                    MSniperServiceTask.UnblockSnipe(false);
                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        await RecycleItemsTask.Execute(session, cancellationToken);

                        _storeRi = 1;
                    }

                    if (session.LogicSettings.UsePokeStopLimit)
                    {
                        session.Stats.AddPokestopTimestamp(DateTime.Now.Ticks);
                        session.EventDispatcher.Send(new PokestopLimitUpdate(session.Stats.GetNumPokestopsInLast24Hours(), session.LogicSettings.PokeStopLimit));
                    }
                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (session.LogicSettings.AllowMultipleBot)
            {
                if (fortTry >= retryNumber - zeroCheck)
                {
                    softbanCount++;

                    //only check if PokestopSoftbanCount > 0
                    if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings) &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount > 0 &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount <= softbanCount &&
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                    {
                        softbanCount = 0;

                        //Activate switcher by pokestop
                        throw new ActiveSwitchByRuleException()
                              {
                                  MatchedRule  = SwitchRules.PokestopSoftban,
                                  ReachedValue = session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount
                              };
                    }
                }
            }
            else
            {
                softbanCount = 0; //reset softban count
            }

            if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry)
            {
                if (++_randomStop >= _randomNumber)
                {
                    _randomNumber = _rc.Next(4, 11);
                    _randomStop   = 0;
                    int randomWaitTime = _rc.Next(30, 120);
                    await Task.Delay(randomWaitTime, cancellationToken);
                }
            }
        }
Exemple #10
0
        private bool CheckAndFarmNearbyPokeStop(FortData pokeStop, Client client, FortDetailsResponse fortInfo)
        {
            if (Setout.count >= 9)
            {
                Setout.Execute();
            }

            if (pokeStop.CooldownCompleteTimestampMs < (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds && BotSettings.FarmPokestops)
            {
                var fortSearch = objClient.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);
                Logger.Debug("================[VERBOSE LOGGING - Pokestop Search]================");
                Logger.Debug($"Result: {fortSearch.Result}");
                Logger.Debug($"ChainHackSequenceNumber: {fortSearch.ChainHackSequenceNumber}");
                Logger.Debug($"Cooldown Complete (MS): {fortSearch.CooldownCompleteTimestampMs}");
                Logger.Debug($"EXP Award: {fortSearch.ExperienceAwarded}");
                Logger.Debug($"Gems Award: {fortSearch.GemsAwarded}");
                Logger.Debug($"Item Award: {fortSearch.ItemsAwarded}");
                Logger.Debug($"Egg Data: {fortSearch.PokemonDataEgg}");
                Logger.Debug("==================================================================");

                switch (fortSearch.Result.ToString())
                {
                case "NoResultSet":
                    Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: We did not recieve a result from the pokestop.");
                    break;

                case "Success":
                    // It already showed our pokestop Information
                    break;

                case "OutOfRange":
                    Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: The pokestop is out of range!");
                    break;

                case "InCooldownPeriod":
                    Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Pokestop Warning: The current Pokestop is in the cooldown period.");
                    break;

                case "InventoryFull":
                    Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Pokestop Warning: Your Inventory is full. You did not recieve any items.");
                    break;

                case "ExceededDailyLimit":
                    Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: You are above your daily limit of pokestops! You should stop farming pokestops.");
                    break;
                }

                Setout.count++;
                var strDate      = DateTime.Now.ToString("HH:mm:ss");
                var pokeStopInfo = $"{fortInfo.Name}{Environment.NewLine}Visited:{strDate}{Environment.NewLine}";

                if (fortSearch.ExperienceAwarded > 0)
                {
                    var egg = "/";

                    if (fortSearch.PokemonDataEgg != null)
                    {
                        egg = fortSearch.PokemonDataEgg.EggKmWalkedTarget + "km";
                    }

                    var items = "";

                    if (fortSearch.ItemsAwarded != null)
                    {
                        items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded);
                    }

                    var logrestock = false;

                    if (fortSearch.ItemsAwarded != null)
                    {
                        foreach (var item in fortSearch.ItemsAwarded)
                        {
                            if (item.ItemId == ItemId.ItemPokeBall || item.ItemId == ItemId.ItemGreatBall || item.ItemId == ItemId.ItemUltraBall)
                            {
                                logrestock = true;
                            }
                        }

                        if (logrestock && pokeballoutofstock)
                        {
                            Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Detected Pokeball Restock - Enabling Catch Pokemon");

                            CatchingLogic.AllowCatchPokemon = true;
                            pokeballoutofstock = false;
                        }

                        FailedSoftban = 0;
                        BotStats.AddExperience(fortSearch.ExperienceAwarded);
                        Setout.RefreshConsoleTitle(client);
                        Setout.pokeStopFarmedCount++;
                        Setout.SaveSession();

                        Logger.Info($"Farmed XP: {fortSearch.ExperienceAwarded}, Gems: {fortSearch.GemsAwarded}, Egg: {egg}, Items: {items}");

                        var strItems = items.Replace(",", Environment.NewLine);
                        pokeStopInfo += $"{fortSearch.ExperienceAwarded} XP{Environment.NewLine}{fortSearch.GemsAwarded}{Environment.NewLine}{egg}{Environment.NewLine}{strItems}";

                        Logger.Debug("LureInfo: " + pokeStop.LureInfo);
                        if (pokeStop.LureInfo != null)
                        {
                            var pokedata = new MapPokemon();
                            pokedata.EncounterId           = pokeStop.LureInfo.EncounterId;
                            pokedata.PokemonId             = pokeStop.LureInfo.ActivePokemonId;
                            pokedata.Latitude              = pokeStop.Latitude;
                            pokedata.Longitude             = pokeStop.Longitude;
                            pokedata.ExpirationTimestampMs = pokeStop.LureInfo.LureExpiresTimestampMs;
                            pokedata.SpawnPointId          = pokeStop.LureInfo.FortId;

                            infoObservable.PushNewPokemonLocation(pokedata);
                            Logger.Debug("Lured Pokemon: " + pokedata);

                            if (!BotSettings.catchPokemonSkipList.Contains(pokedata.PokemonId) && GlobalVars.CatchPokemon)
                            {
                                if (!lureEncounters.Contains(pokedata.EncounterId.ToString()))
                                {
                                    Logger.ColoredConsoleWrite(ConsoleColor.Green, "Catching Lured Pokemon");
                                    CatchingLogic.CatchLuredPokemon(pokedata.EncounterId, pokedata.SpawnPointId, pokedata.PokemonId, pokedata.Longitude, pokedata.Latitude);

                                    lureEncounters.Add(pokedata.EncounterId.ToString());
                                }
                                else
                                {
                                    Logger.ColoredConsoleWrite(ConsoleColor.Green, "Skipped Lure Pokemon: " + pokedata.PokemonId + " because we have already caught him, or catching pokemon is disabled");
                                }
                            }
                        }

                        double eggs = 0;

                        if (fortSearch.PokemonDataEgg != null)
                        {
                            eggs = fortSearch.PokemonDataEgg.EggKmWalkedTarget;
                        }

                        Telegram?.sendInformationText(TelegramUtil.TelegramUtilInformationTopics.Pokestop, fortInfo.Name, fortSearch.ExperienceAwarded, eggs, fortSearch.GemsAwarded, StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded));
                    }
                }

                Task.Factory.StartNew(() => infoObservable.PushPokeStopInfoUpdate(pokeStop, pokeStopInfo));

                return(true);
            }

            if (!BotSettings.FarmPokestops)
            {
                Logger.ColoredConsoleWrite(ConsoleColor.Green, "Farm Pokestop option unchecked, skipping and only looking for pokemon");

                return(false);
            }

            Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokestop not ready to farm again, skipping and only looking for pokemon");

            return(false);
        }
Exemple #11
0
        public void Save(GetGymDetailsResponse fortDetails, FortDetailsResponse fortInfo, string filePath, double currentAltitude)
        {
            //write data file
            try
            {
                var data = new Xml.Gym2();
                data.Id          = fortInfo.FortId;
                data.Latitude    = fortDetails.GymState.FortData.Latitude;
                data.Longitude   = fortDetails.GymState.FortData.Longitude;
                data.Altitude    = currentAltitude;
                data.Name        = fortDetails.Name;
                data.Description = fortDetails.Description;
                data.Fp          = fortInfo.Fp;
                data.CooldownCompleteTimestampMs = fortDetails.GymState.FortData.CooldownCompleteTimestampMs;
                data.GymPoints = fortDetails.GymState.FortData.GymPoints;
                data.LastModifiedTimestampMs = fortDetails.GymState.FortData.LastModifiedTimestampMs;
                data.Sponsor = fortDetails.GymState.FortData.Sponsor.ToString();
                data.Team    = fortDetails.GymState.FortData.OwnedByTeam.ToString();
                if (fortDetails.GymState.Memberships != null && fortDetails.GymState.Memberships.Count() > 0)
                {
                    foreach (var membership in fortDetails.GymState.Memberships)
                    {
                        var m = new Xml.Membership2();
                        m.Player.Name             = membership.TrainerPublicProfile.Name;
                        m.Player.Level            = membership.TrainerPublicProfile.Level;
                        m.Pokemon.BattlesAttacked = membership.PokemonData.BattlesAttacked;
                        m.Pokemon.BattlesDefended = membership.PokemonData.BattlesDefended;
                        m.Pokemon.Cp                = membership.PokemonData.Cp;
                        m.Pokemon.Hp                = membership.PokemonData.StaminaMax;
                        m.Pokemon.HeightM           = membership.PokemonData.HeightM;
                        m.Pokemon.WeightKg          = membership.PokemonData.WeightKg;
                        m.Pokemon.Id                = membership.PokemonData.Id;
                        m.Pokemon.IndividualAttack  = membership.PokemonData.IndividualAttack;
                        m.Pokemon.IndividualDefense = membership.PokemonData.IndividualDefense;
                        m.Pokemon.IndividualStamina = membership.PokemonData.IndividualStamina;
                        m.Pokemon.PlayerLevel       = membership.TrainerPublicProfile.Level;
                        m.Pokemon.PlayerTeam        = fortDetails.GymState.FortData.OwnedByTeam.ToString();
                        m.Pokemon.IV                = membership.PokemonData.GetPerfection();
                        m.Pokemon.Nickname          = membership.PokemonData.Nickname;
                        m.Pokemon.V        = CalculatePokemonValue(membership.PokemonData);
                        m.Pokemon.Move1    = membership.PokemonData.Move1.ToString();
                        m.Pokemon.Move2    = membership.PokemonData.Move2.ToString();
                        m.Pokemon.Nickname = membership.PokemonData.Nickname;
                        m.Pokemon.Level    = membership.PokemonData.NumUpgrades;
                        m.Pokemon.Origin   = membership.PokemonData.Origin;
                        m.Pokemon.Type     = membership.PokemonData.PokemonId.ToString();
                        data.Memberships.Add(m);
                    }
                }

                foreach (var img in fortInfo.ImageUrls)
                {
                    data.ImageUrls.Add(img);
                }
                Xml.Serializer.SerializeToFile(data, filePath);
            }
            catch// (Exception e)
            {
                //Logger.Write($"Could not save the gym information file for {fortInfo.FortId} - {e.ToString()}", LogLevel.Error);
            }
        }
Exemple #12
0
        private static bool CheckAndPutInNearbyGym(FortData gym, Client client, FortDetailsResponse fortInfo)
        {
            var gymColorLog = ConsoleColor.DarkGray;

            if (gymsVisited.IndexOf(gym.Id) > -1)
            {
                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - This gym was already visited.");
                return(false);
            }

            if (!GlobalVars.FarmGyms)
            {
                return(false);
            }

            ReviveAndCurePokemons(client);
            var pokemons = (client.Inventory.GetPokemons().Result).ToList();

            PokemonData pokemon = getPokeToPut(client);

            if (pokemon == null)
            {
                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There are no pokemons to assign.");
                return(false);
            }

            RandomHelper.RandomSleep(100, 200);
            var profile = client.Player.GetPlayer().Result;

            if ((gym.OwnedByTeam == profile.PlayerData.Team) || (gym.OwnedByTeam == POGOProtos.Enums.TeamColor.Neutral))
            {
                RandomHelper.RandomSleep(100, 200);
                var gymDetails = client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude).Result;
                Logger.ColoredConsoleWrite(gymColorLog, "Team:" + GetTeamName(gym.OwnedByTeam) + ". Members: " + gymDetails.GymState.Memberships.Count + ". Level: " + GetGymLevel(gym.GymPoints));
                if (gymDetails.GymState.Memberships.Count < GetGymLevel(gym.GymPoints))
                {
                    putInGym(client, gym, pokemon, pokemons);
                }
                else if (GlobalVars.AttackGyms && gymDetails.GymState.Memberships.Count == 1)
                {
                    GlobalVars.PauseTheWalking = true;
                    Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There is only one defender. Let's go to train");
                    var pokeAttackers = pokemons.Where(x => ((!x.IsEgg) && (x.DeployedFortId == "") && (x.Stamina > 0))).OrderByDescending(x => x.Cp).Take(6);
                    Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Selected pokemons to train:");
                    ShowPokemons(pokeAttackers);
                    var defenders = gymDetails.GymState.Memberships.Select(x => x.PokemonData);
                    var defender  = defenders.FirstOrDefault();
                    var attResp   = AttackGym(gym, client, fortInfo, pokeAttackers, defender.Id, gymDetails.GymState.Memberships.Count);
                    if (attResp != null)
                    {
                        if (attResp.Result == AttackGymResponse.Types.Result.Success)
                        {
                            if (attResp.BattleLog.State == BattleState.Defeated)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have lost");
                            }
                            else if (attResp.BattleLog.State == BattleState.Victory)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have won");
                                ReviveAndCurePokemons(client);
                                putInGym(client, gym, getPokeToPut(client), pokemons);
                            }
                            else if (attResp.BattleLog.State == BattleState.TimedOut)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Timed Out");
                            }
                            gymsVisited.Add(gym.Id);
                        }
                    }
                    GlobalVars.PauseTheWalking = false;
                }
                else
                {
                    Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There is no free space in the gym");
                }
            }
            else
            {
                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - This gym is not from your team.");
                if (!GlobalVars.AttackGyms)
                {
                    return(false);
                }

                Shared.GlobalVars.PauseTheWalking = true;
                Logger.Debug("(Gym) - Stop walking");
                var gymDetails = client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude).Result;
                Logger.ColoredConsoleWrite(gymColorLog, "Team:" + GetTeamName(gym.OwnedByTeam) + ". Members: " + gymDetails.GymState.Memberships.Count + ". Level: " + GetGymLevel(gym.GymPoints));

                // TODO: ATTACK more than 1 defender
                if (gymDetails.GymState.Memberships.Count >= 1 && gymDetails.GymState.Memberships.Count <= 2)
                {
                    if (gymDetails.GymState.Memberships.Count == 1)
                    {
                        Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There is only one rival. Let's go to fight");
                    }
                    else if (gymDetails.GymState.Memberships.Count == 2)
                    {
                        Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - There are two rivals. Let's go to fight");
                    }
                    var pokeAttackers = pokemons.Where(x => ((!x.IsEgg) && (x.DeployedFortId == "") && (x.Stamina > 0))).OrderByDescending(x => x.Cp).Take(6);
                    Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Selected Atackers:");
                    ShowPokemons(pokeAttackers);
                    var defenders = gymDetails.GymState.Memberships.Select(x => x.PokemonData);
                    var defender  = defenders.FirstOrDefault();
                    var attResp   = AttackGym(gym, client, fortInfo, pokeAttackers, defender.Id, gymDetails.GymState.Memberships.Count);
                    if (attResp != null)
                    {
                        if (attResp.Result == AttackGymResponse.Types.Result.Success)
                        {
                            if (attResp.BattleLog.State == BattleState.Defeated)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have lost");
                            }
                            else if (attResp.BattleLog.State == BattleState.Victory)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have won");
                                ReviveAndCurePokemons(client);
                                putInGym(client, gym, getPokeToPut(client), pokemons);
                            }
                            else if (attResp.BattleLog.State == BattleState.TimedOut)
                            {
                                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Timed Out");
                            }
                            gymsVisited.Add(gym.Id);
                        }
                    }
                }
                GlobalVars.PauseTheWalking = false;
                Logger.Debug("(Gym) - Continnue walking");
            }
            return(true);
        }
Exemple #13
0
        private static async Task DoActionAtPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo, bool doNotTrySpin = false)
        {
            if (pokeStop.Type != FortType.Checkpoint)
            {
                return;
            }

            //Catch Lure Pokemon
            if (pokeStop.LureInfo != null)
            {
                // added for cooldowns
                await Task.Delay(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, 3000));

                await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken);
            }

            // Spin as long as we haven't reached the user defined limits
            if (!_pokestopLimitReached && !_pokestopTimerReached)
            {
                await FarmPokestop(session, pokeStop, fortInfo, cancellationToken, doNotTrySpin);
            }

            if (++_stopsHit >= _storeRi)     //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing.
            {
                _storeRi  = _rc.Next(6, 12); //set new storeRI for new random value
                _stopsHit = 0;

                if (session.LogicSettings.UseNearActionRandom)
                {
                    await HumanRandomActionTask.Execute(session, cancellationToken);
                }
                else
                {
                    await RecycleItemsTask.Execute(session, cancellationToken);

                    if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.UseLuckyEggConstantly)
                    {
                        await UseLuckyEggConstantlyTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.UseIncenseConstantly)
                    {
                        await UseIncenseConstantlyTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.TransferWeakPokemon)
                    {
                        await TransferWeakPokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.RenamePokemon)
                    {
                        await RenamePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.AutomaticallyLevelUpPokemon)
                    {
                        await LevelUpPokemonTask.Execute(session, cancellationToken);
                    }

                    await GetPokeDexCount.Execute(session, cancellationToken);
                }
            }
        }
Exemple #14
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken,
                                         FortData originalPokestop, FortDetailsResponse fortInfo)
        {
            StartAsyncPollingTask(session, cancellationToken);

            pokestopCount++;
            pokestopCount = pokestopCount % 3;

            if (pokestopCount > 0 && !prioritySnipeFlag)
            {
                return;
            }

            InitSession(session);
            if (!_setting.CatchPokemon && !prioritySnipeFlag)
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (_setting.HumanWalkingSnipeTryCatchEmAll)
            {
                var checkBall = CheckPokeballsToSnipe(_setting.HumanWalkingSnipeCatchEmAllMinBalls, session,
                                                      cancellationToken);
                if (!checkBall && !prioritySnipeFlag)
                {
                    return;
                }
            }

            bool             caughtAnyPokemonInThisWalk = false;
            SnipePokemonInfo pokemon = null;

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                prioritySnipeFlag = false;
                pokemon           = await GetNextSnipeablePokemon(session.Client.CurrentLatitude, session.Client.CurrentLongitude,
                                                                  !caughtAnyPokemonInThisWalk);

                if (pokemon != null)
                {
                    caughtAnyPokemonInThisWalk = true;
                    CalculateDistanceAndEstTime(pokemon);
                    var remainTimes = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds * 0.95; //just use 90% times

                    //assume that 100m we catch 1 pokemon and it took 10 second for each.
                    var catchPokemonTimeEST =
                        (pokemon.Distance / 100) * 10;
                    string strPokemon      = session.Translation.GetPokemonTranslation(pokemon.PokemonId);
                    var    spinPokestopEST = (pokemon.Distance / 100) * 5;

                    bool catchPokemon = (pokemon.EstimatedTime + catchPokemonTimeEST) < remainTimes &&
                                        pokemon.Setting.CatchPokemonWhileWalking;
                    bool spinPokestop = pokemon.Setting.SpinPokestopWhileWalking &&
                                        (pokemon.EstimatedTime + catchPokemonTimeEST + spinPokestopEST) < remainTimes;
                    lock (threadLocker)
                    {
                        pokemon.IsCatching = true;
                    }
                    session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                    {
                        PokemonId        = pokemon.PokemonId,
                        Latitude         = pokemon.Latitude,
                        Longitude        = pokemon.Longitude,
                        Distance         = pokemon.Distance,
                        Expires          = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds,
                        Estimate         = (int)pokemon.EstimatedTime,
                        Setting          = pokemon.Setting,
                        CatchPokemon     = catchPokemon,
                        Pokemons         = ApplyFilter(rarePokemons.ToList()),
                        SpinPokeStop     = pokemon.Setting.SpinPokestopWhileWalking,
                        WalkSpeedApplied = pokemon.Setting.AllowSpeedUp
                            ? pokemon.Setting.MaxSpeedUpSpeed
                            : _session.LogicSettings.WalkingSpeedInKilometerPerHour,
                        Type   = HumanWalkSnipeEventTypes.StartWalking,
                        Rarity = PokemonGradeHelper.GetPokemonGrade(pokemon.PokemonId).ToString()
                    });
                    var snipeTarget = new SnipeLocation(pokemon.Latitude, pokemon.Longitude,
                                                        LocationUtils.getElevation(session.ElevationService, pokemon.Latitude, pokemon.Longitude));

                    await session.Navigation.Move(
                        snipeTarget,
                        async() =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        await ActionsWhenTravelToSnipeTarget(session, cancellationToken, pokemon, catchPokemon, spinPokestop);
                    },
                        session,
                        cancellationToken,
                        pokemon.Setting.AllowSpeedUp?pokemon.Setting.MaxSpeedUpSpeed : 0
                        );

                    session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                    {
                        Latitude      = pokemon.Latitude,
                        Longitude     = pokemon.Longitude,
                        PauseDuration = pokemon.Setting.DelayTimeAtDestination / 1000,
                        Type          = HumanWalkSnipeEventTypes.DestinationReached,
                        UniqueId      = pokemon.UniqueId
                    });

                    //await Task.Delay(pokemon.Setting.DelayTimeAtDestination, cancellationToken);
                    await CatchNearbyPokemonsTask
                    .Execute(session, cancellationToken, pokemon.PokemonId, pokemon.Setting.AllowTransferWhileWalking);

                    await Task.Delay(1000, cancellationToken);

                    if (!pokemon.IsVisited)
                    {
                        await CatchLurePokemonsTask.Execute(session, cancellationToken);
                    }

                    lock (threadLocker)
                    {
                        pokemon.IsVisited  = true;
                        pokemon.IsCatching = false;
                    }

                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.TransferWeakPokemon)
                    {
                        await TransferWeakPokemonTask.Execute(session, cancellationToken);
                    }

                    if (session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken);
                    }
                }
            } while (pokemon != null && _setting.HumanWalkingSnipeTryCatchEmAll);

            if (caughtAnyPokemonInThisWalk && (!_setting.HumanWalkingSnipeAlwaysWalkBack || _setting.UseGpxPathing))
            {
                if (session.LogicSettings.UseGpxPathing)
                {
                    await WalkingBackGPXPath(session, cancellationToken, originalPokestop, fortInfo);
                }
                else
                {
                    await UpdateFarmingPokestop(session, cancellationToken);
                }
            }
        }
Exemple #15
0
        private static async Task DeployPokemonToGym(ISession session, FortDetailsResponse fortInfo, GetGymDetailsResponse fortDetails, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var points   = fortDetails.GymState.FortData.GymPoints;
            var maxCount = GetGymLevel(points);

            var availableSlots = maxCount - fortDetails.GymState.Memberships.Count();

            if (availableSlots > 0)
            {
                var deployed = await session.Inventory.GetDeployedPokemons();

                if (!deployed.Any(a => a.DeployedFortId == fortInfo.FortId))
                {
                    var pokemon = await GetDeployablePokemon(session);

                    if (pokemon != null)
                    {
                        FortDeployPokemonResponse response = null;
                        try
                        {
                            response = await session.Client.Fort.FortDeployPokemon(fortInfo.FortId, pokemon.Id);
                        }
                        catch (APIBadRequestException)
                        {
                            Logger.Write("Failed to deploy pokemon. Trying again...", LogLevel.Gym, ConsoleColor.Magenta);
                            await Execute(session, cancellationToken, fortDetails.GymState.FortData, fortInfo);

                            return;
                        }
                        if (response?.Result == FortDeployPokemonResponse.Types.Result.Success)
                        {
                            session.EventDispatcher.Send(new GymDeployEvent()
                            {
                                PokemonId = pokemon.PokemonId,
                                Name      = fortDetails.Name
                            });
                            if (session.LogicSettings.GymConfig.CollectCoinAfterDeployed > 0)
                            {
                                var count = deployed.Count() + 1;
                                if (count >= session.LogicSettings.GymConfig.CollectCoinAfterDeployed)
                                {
                                    try
                                    {
                                        if (session.Profile.PlayerData.DailyBonus.NextDefenderBonusCollectTimestampMs <= DateTime.Now.ToUnixTime())
                                        {
                                            var collectDailyBonusResponse = await session.Client.Player.CollectDailyDefenderBonus();

                                            if (collectDailyBonusResponse.Result == CollectDailyDefenderBonusResponse.Types.Result.Success)
                                            {
                                                Logger.Write($"Collected {count * 10} coins", LogLevel.Gym, ConsoleColor.DarkYellow);
                                            }
                                            else
                                            {
                                                Logger.Write($"Hmm, we have failed with gaining a reward: {collectDailyBonusResponse}", LogLevel.Gym, ConsoleColor.Magenta);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Write($"You will be able to collect bonus at {DateTimeFromUnixTimestampMillis(session.Profile.PlayerData.DailyBonus.NextDefenderBonusCollectTimestampMs)}", LogLevel.Info, ConsoleColor.Magenta);
                                        }
                                    }
                                    catch (APIBadRequestException)
                                    {
                                        Logger.Write("Can't get coins", LogLevel.Warning);
                                        //Debug.WriteLine(e.Message, "GYM");
                                        //Debug.WriteLine(e.StackTrace, "GYM");

                                        await Task.Delay(500);
                                    }
                                }
                                else
                                {
                                    Logger.Write(string.Format("You have only {0} defenders deployed but {1} required to get reward", count, session.LogicSettings.GymConfig.CollectCoinAfterDeployed), LogLevel.Gym, ConsoleColor.Magenta);
                                }
                            }
                            else
                            {
                                Logger.Write("You have disabled reward collecting in config file", LogLevel.Gym, ConsoleColor.Magenta);
                            }
                        }
                        else
                        {
                            Logger.Write(string.Format("Deploy pokemon failed with result: {0}", response.Result), LogLevel.Gym, ConsoleColor.Magenta);
                        }
                    }
                    else
                    {
                        Logger.Write($"You don't have pokemons to be deployed!", LogLevel.Gym);
                    }
                }
                else
                {
                    Logger.Write($"You already have pokemon deployed here", LogLevel.Gym);
                }
            }
            else
            {
                string message = string.Format("No action. No FREE slots in GYM {0}/{1} ({2})", fortDetails.GymState.Memberships.Count(), maxCount, points);
                Logger.Write(message, LogLevel.Gym, ConsoleColor.White);
            }
        }
Exemple #16
0
        public static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false)
        {
            var manager = TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            // If the cooldown is in the future than don't farm the pokestop.
            if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime())
            {
                return;
            }

            if (session.Stats.SearchThresholdExceeds(session, true))
            {
                if (manager.AllowMultipleBot() && session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit)
                {
                    throw new Exceptions.ActiveSwitchByRuleException(SwitchRules.SpinPokestopReached, session.LogicSettings.PokeStopLimit);
                }
                return;
            }

            //await session.Client.Map.GetMapObjects().ConfigureAwait(false);
            FortSearchResponse fortSearch;
            var timesZeroXPawarded = 0;
            var fortTry            = 0;                                     //Current check
            int retryNumber        = session.LogicSettings.ByPassSpinCount; //How many times it needs to check to clear softban
            int zeroCheck          = Math.Min(5, retryNumber);              //How many times it checks fort before it thinks it's softban

            var distance = LocationUtils.CalculateDistanceInMeters(pokeStop.Latitude, pokeStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);

            //This should be < ## not > ##. > makes bot jump to pokestop if < then when in range will just spin.
            if (distance < 50) //if (distance > 30)
            {
                await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), 0).ConfigureAwait(false);

                await session.Client.Misc.RandomAPICall().ConfigureAwait(false);
            }

            do
            {
                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                int    retry     = 3;
                double latitude  = pokeStop.Latitude;
                double longitude = pokeStop.Longitude;
                do
                {
                    fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude).ConfigureAwait(false);

                    if (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange)
                    {
                        if (retry > 2)
                        {
                            await Task.Delay(500).ConfigureAwait(false);
                        }
                        else
                        {
                            await session.Client.Map.GetMapObjects(true).ConfigureAwait(false);
                        }

                        Logger.Debug($"Loot pokestop result: {fortSearch.Result}, distance to pokestop:[{pokeStop.Latitude}, {pokeStop.Longitude}] {distance:0.00}m, retry: #{4 - retry}");

                        latitude  += 0.000003;
                        longitude += 0.000005;
                        await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude), 0).ConfigureAwait(false);

                        retry--;
                    }
                }while (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange && retry > 0);
                Logger.Debug($"Loot pokestop result: {fortSearch.Result}");
                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0 && fortSearch.Result != FortSearchResponse.Types.Result.InventoryFull)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });
                        if (doNotRetry)
                        {
                            break;
                        }
                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            await DelayingUtils.DelayAsync(session.LogicSettings.DelayBetweenPlayerActions, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);
                        }
                    }
                }
                else
                {
                    softbanCount = 0;
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id             = pokeStop.Id,
                        Name           = fortInfo.Name,
                        Exp            = fortSearch.ExperienceAwarded,
                        Gems           = fortSearch.GemsAwarded > 0 ? $"Yes {fortSearch.GemsAwarded}" : "No",
                        Items          = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Badges         = fortSearch.AwardedGymBadge != null ? fortSearch.AwardedGymBadge.GymBadgeType.ToString() : "No",
                        BonusLoot      = fortSearch.BonusLoot != null ? StringUtils.GetSummedFriendlyNameOfGetLootList(fortSearch.BonusLoot.LootItem) : "No",
                        RaidTickets    = fortSearch.RaidTickets > 0 ? $"{fortSearch.RaidTickets} tickets" : "No",
                        TeamBonusLoot  = fortSearch.TeamBonusLoot != null ? StringUtils.GetSummedFriendlyNameOfGetLootList(fortSearch.TeamBonusLoot.LootItem) : "No",
                        PokemonDataEgg = fortSearch.PokemonDataEgg != null ? fortSearch.PokemonDataEgg : null,
                        Latitude       = pokeStop.Latitude,
                        Longitude      = pokeStop.Longitude,
                        Altitude       = session.Client.CurrentAltitude,
                        InventoryFull  = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull,
                        Fort           = pokeStop
                    });

                    if (fortSearch.Result == FortSearchResponse.Types.Result.Success)
                    {
                        mapEmptyCount = 0;
                        foreach (var item in fortSearch.ItemsAwarded)
                        {
                            await session.Inventory.UpdateInventoryItem(item.ItemId).ConfigureAwait(false);
                        }
                        if (fortSearch.PokemonDataEgg != null)
                        {
                            fortSearch.PokemonDataEgg.IsEgg = true;
                        }

                        // Update the cache
                        var fortFromCache = session.Client.Map.LastGetMapObjectResponse.MapCells.SelectMany(x => x.Forts).FirstOrDefault(f => f.Id == pokeStop.Id);

                        long newCooldown = TimeUtil.GetCurrentTimestampInMilliseconds() + (5 * 60 * 1000); /* 5 min */
                        fortFromCache.CooldownCompleteTimestampMs = newCooldown;
                        pokeStop.CooldownCompleteTimestampMs      = newCooldown;

                        if (session.SaveBallForByPassCatchFlee)
                        {
                            var totalBalls = (await session.Inventory.GetItems().ConfigureAwait(false)).Where(x => x.ItemId == ItemId.ItemPokeBall || x.ItemId == ItemId.ItemGreatBall || x.ItemId == ItemId.ItemUltraBall).Sum(x => x.Count);
                            Logger.Write($"Ball requires for by pass catch flee {totalBalls}/{CatchPokemonTask.BALL_REQUIRED_TO_BYPASS_CATCHFLEE}");
                        }
                        else
                        {
                            MSniperServiceTask.UnblockSnipe(false);
                        }
                    }
                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        await RecycleItemsTask.Execute(session, cancellationToken).ConfigureAwait(false);

                        _storeRi = 1;
                    }

                    if (session.LogicSettings.UsePokeStopLimit)
                    {
                        session.Stats.AddPokestopTimestamp(DateTime.Now.Ticks);
                        session.EventDispatcher.Send(new PokestopLimitUpdate(session.Stats.GetNumPokestopsInLast24Hours(), session.LogicSettings.PokeStopLimit));
                    }
                    //add pokeStops to Map
                    OnLootPokestopEvent(pokeStop);
                    //end pokeStop to Map

                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (manager.AllowMultipleBot())
            {
                if (fortTry >= retryNumber - zeroCheck)
                {
                    softbanCount++;

                    //only check if PokestopSoftbanCount > 0
                    if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings, manager) &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount > 0 &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount <= softbanCount &&
                        TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                    {
                        softbanCount = 0;

                        //Activate switcher by pokestop
                        throw new ActiveSwitchByRuleException()
                              {
                                  MatchedRule  = SwitchRules.PokestopSoftban,
                                  ReachedValue = session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount
                              };
                    }
                }
            }
            else
            {
                softbanCount = 0; //reset softban count
            }

            if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry)
            {
                if (++_randomStop >= _randomNumber)
                {
                    _randomNumber = _rc.Next(4, 11);
                    _randomStop   = 0;
                    int randomWaitTime = _rc.Next(30, 120);
                    await Task.Delay(randomWaitTime, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #17
0
        private static AttackGymResponse AttackGym(FortData gym, Client client, FortDetailsResponse fortInfo,
                                                   IEnumerable <PokemonData> pokeAttackers, ulong defenderId, int numDefenders)
        {
            var gymColorLog      = ConsoleColor.DarkGray;
            var pokeAttackersIds = pokeAttackers.Select(x => x.Id);
            var moveSettings     = GetMoveSettings(client);

            RandomHelper.RandomSleep(1000, 1500);
            var resp = client.Fort.StartGymBattle(gym.Id, defenderId, pokeAttackersIds).Result;

            // Sometimes we get a null from startgymBattle
            if (resp == null)
            {
                Logger.Debug("Response to start battle was null");
                return(null);
            }
            if (resp.BattleLog == null)
            {
                Logger.Debug("BatlleLog to start battle was null");
                return(null);
            }
            if (resp.BattleLog.State == POGOProtos.Data.Battle.BattleState.Active)
            {
                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Battle Started");
                RandomHelper.RandomSleep(2500, 3000);

                var battleActions       = new List <BattleAction>();
                var lastRetrievedAction = new BattleAction();
                var battleStartMs       = resp.BattleLog.BattleStartTimestampMs;
                var attResp             = client.Fort.AttackGym(gym.Id, resp.BattleId, battleActions, lastRetrievedAction).Result;
                Logger.Debug("(Gym) - Attack Result: " + attResp.Result);
                Logger.Debug("(Gym) - Battle State: " + attResp.BattleLog.State);
                var inBattle = (attResp.Result == AttackGymResponse.Types.Result.Success);
                inBattle = inBattle && (attResp.BattleLog.State == BattleState.Active);
                var count = 1;
                while (inBattle)
                {
                    var timeMs        = attResp.BattleLog.ServerMs;
                    var move1Settings = moveSettings.FirstOrDefault(x => x.MoveSettings.MovementId == attResp.ActiveAttacker.PokemonData.Move1).MoveSettings;
                    var attack        = new BattleAction();
                    attack.Type       = BattleActionType.ActionAttack;
                    attack.DurationMs = move1Settings.DurationMs;
                    attack.DamageWindowsStartTimestampMs = move1Settings.DamageWindowStartMs;
                    attack.DamageWindowsEndTimestampMs   = move1Settings.DamageWindowEndMs;
                    attack.ActionStartMs   = timeMs + move1Settings.DurationMs;
                    attack.TargetIndex     = -1;
                    attack.ActivePokemonId = attResp.ActiveAttacker.PokemonData.Id;
                    attack.TargetPokemonId = attResp.ActiveDefender.PokemonData.Id;
                    battleActions.Clear();
                    battleActions.Add(attack);
                    lastRetrievedAction = attResp.BattleLog.BattleActions.LastOrDefault();
                    attResp             = client.Fort.AttackGym(gym.Id, resp.BattleId, battleActions, lastRetrievedAction).Result;
                    Logger.Debug("(Gym) - Attack Result: " + attResp.Result);
                    inBattle = (attResp.Result == AttackGymResponse.Types.Result.Success);
                    if (inBattle)
                    {
                        Logger.Debug("(Gym) - Battle State: " + attResp.BattleLog.State);
                        inBattle = inBattle && (attResp.BattleLog.State == BattleState.Active);
                        Logger.Debug($"Attack {count} done.");
                        count++;
                        Logger.Debug("(Gym) - Wait a moment before next attact");
                        RandomHelper.RandomSleep(move1Settings.DurationMs + 30, move1Settings.DurationMs + 50);
                    }
                }
                Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Battle Finished in {count} attacks.");
                if (attResp.Result == AttackGymResponse.Types.Result.Success)
                {
                    if (attResp.BattleLog.State == BattleState.Defeated)
                    {
                        Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have lost");
                        if (numDefenders > 1)
                        {
                            var timeMs = attResp.BattleLog.ServerMs;
                            var attack = new BattleAction();
                            attack.Type       = BattleActionType.ActionPlayerQuit;
                            attack.DurationMs = 0;
                            attack.DamageWindowsStartTimestampMs = 0;
                            attack.DamageWindowsEndTimestampMs   = 0;
                            attack.ActionStartMs   = timeMs;
                            attack.TargetIndex     = -1;
                            attack.ActivePokemonId = attResp.ActiveAttacker.PokemonData.Id;
                            attack.TargetPokemonId = attResp.ActiveDefender.PokemonData.Id;
                            battleActions.Clear();
                            battleActions.Add(attack);
                            lastRetrievedAction = attResp.BattleLog.BattleActions.LastOrDefault();
                            attResp             = client.Fort.AttackGym(gym.Id, resp.BattleId, battleActions, lastRetrievedAction).Result;
                        }
                    }
                    else if (attResp.BattleLog.State == BattleState.Victory)
                    {
                        Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - We have won");
                        ReviveAndCurePokemons(client);
                        var pokemons = (client.Inventory.GetPokemons().Result).ToList();
                        putInGym(client, gym, getPokeToPut(client), pokemons);
                    }
                    else if (attResp.BattleLog.State == BattleState.TimedOut)
                    {
                        Logger.ColoredConsoleWrite(gymColorLog, "(Gym) - Timed Out");
                    }
                    gymsVisited.Add(gym.Id);
                }
                return(attResp);
            }
            return(null);
        }
 /// <summary>
 /// Provides a safe way to invoke the <see cref="FortDetailsReceived" /> event.
 /// </summary>
 /// <param name="value"></param>
 public void RaiseFortDetailsReceived(FortDetailsResponse value) => FortDetailsReceived?.Invoke(this, value);
        private static async Task StartGymAttackLogic(ISession session, FortDetailsResponse fortInfo,
                                                      GetGymDetailsResponse fortDetails, FortData gym, CancellationToken cancellationToken)
        {
            bool fighting      = true;
            var  badassPokemon = await session.Inventory.GetHighestCpForGym(6);

            var pokemonDatas = badassPokemon as PokemonData[] ?? badassPokemon.ToArray();

            while (fighting)
            {
                // Heal pokemon
                foreach (var pokemon in pokemonDatas)
                {
                    if (pokemon.Stamina <= 0)
                    {
                        await RevivePokemon(session, pokemon);
                    }
                    if (pokemon.Stamina < pokemon.StaminaMax)
                    {
                        await HealPokemon(session, pokemon);
                    }
                }
                await Task.Delay(4000);

                int tries = 0;
                StartGymBattleResponse result;
                do
                {
                    tries++;
                    result = await StartBattle(session, pokemonDatas, gym);

                    if (result.Result == StartGymBattleResponse.Types.Result.Unset)
                    {
                        // Try to refresh information about pokemons and gym
                        await session.Inventory.RefreshCachedInventory();

                        badassPokemon = await session.Inventory.GetHighestCpForGym(6);

                        pokemonDatas = badassPokemon as PokemonData[] ?? badassPokemon.ToArray();
                        Logger.Write($"Failed to Start Gym Battle at try: {tries}, waiting 20 seconds before make another one.", LogLevel.Gym, ConsoleColor.Red);
                        await Task.Delay(20000);
                    }
                } while (result.Result == StartGymBattleResponse.Types.Result.Unset && tries <= 10);

                // If we can't start battle in 10 tries, let's skip the gym
                if (result.Result == StartGymBattleResponse.Types.Result.Unset)
                {
                    session.EventDispatcher.Send(new GymErrorUnset {
                        GymName = fortInfo.Name
                    });
                    break;
                }

                if (result.Result != StartGymBattleResponse.Types.Result.Success)
                {
                    break;
                }
                switch (result.BattleLog.State)
                {
                case BattleState.Active:
                    Logger.Write($"Time to start Attack Mode", LogLevel.Gym, ConsoleColor.Red);
                    await AttackGym(session, cancellationToken, gym, result);

                    break;

                case BattleState.Defeated:
                    break;

                case BattleState.StateUnset:
                    break;

                case BattleState.TimedOut:
                    break;

                case BattleState.Victory:
                    fighting = false;
                    break;

                default:
                    Logger.Write($"Unhandled result starting gym battle:\n{result}");
                    break;
                }

                fortDetails = await session.Client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude);

                if (fortDetails.GymState.FortData.OwnedByTeam == TeamColor.Neutral ||
                    fortDetails.GymState.FortData.OwnedByTeam == session.Profile.PlayerData.Team)
                {
                    break;
                }
            }

            // Finished battling.. OwnedByTeam should be neutral when we reach here
            if (fortDetails.GymState.FortData.OwnedByTeam == TeamColor.Neutral ||
                fortDetails.GymState.FortData.OwnedByTeam == session.Profile.PlayerData.Team)
            {
                await Execute(session, cancellationToken, gym, fortInfo);
            }
            else
            {
                Logger.Write($"Hmmm, for some reason the gym was not taken over...");
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken, FortData gym, FortDetailsResponse fortInfo)
        {
            if (!session.LogicSettings.GymAllowed || gym.Type != FortType.Gym)
            {
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            var distance = session.Navigation.WalkStrategy.CalculateDistance(session.Client.CurrentLatitude, session.Client.CurrentLongitude, gym.Latitude, gym.Longitude);

            if (fortInfo != null)
            {
                session.EventDispatcher.Send(new GymWalkToTargetEvent()
                {
                    Name      = fortInfo.Name,
                    Distance  = distance,
                    Latitude  = fortInfo.Latitude,
                    Longitude = fortInfo.Longitude
                });

                var fortDetails = await session.Client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude);

                if (fortDetails.Result == GetGymDetailsResponse.Types.Result.Success)
                {
                    if (fortDetails.Result == GetGymDetailsResponse.Types.Result.Success)
                    {
                        var player = session.Profile.PlayerData;
                        await EnsureJoinTeam(session, player);

                        //Do gym tutorial - tobe coded

                        session.EventDispatcher.Send(new GymDetailInfoEvent()
                        {
                            Team  = fortDetails.GymState.FortData.OwnedByTeam,
                            Point = gym.GymPoints,
                            Name  = fortDetails.Name,
                        });

                        if (player.Team != TeamColor.Neutral && fortDetails.GymState.FortData.OwnedByTeam == player.Team)
                        {
                            //trainning logic will come here
                            await DeployPokemonToGym(session, fortInfo, fortDetails);
                        }
                        else
                        {
                            //await StartGymAttackLogic(session, fortInfo, fortDetails, gym, cancellationToken);
                            Logger.Write($"No action... This gym is defending by other color", LogLevel.Gym, ConsoleColor.White);
                        }
                    }
                    else
                    {
                        Logger.Write($"You are not level 5 yet, come back later...", LogLevel.Gym, ConsoleColor.White);
                    }
                }
            }
            else
            {
                // ReSharper disable once PossibleNullReferenceException
                Logger.Write($"Ignoring  Gym : {fortInfo.Name} - ", LogLevel.Gym, ConsoleColor.Cyan);
            }
        }
        private static async Task DeployPokemonToGym(ISession session, FortDetailsResponse fortInfo, GetGymDetailsResponse fortDetails)
        {
            var maxCount = 0;
            var points   = fortDetails.GymState.FortData.GymPoints;

            if (points < 1600)
            {
                maxCount = 1;
            }
            else if (points < 4000)
            {
                maxCount = 2;
            }
            else if (points < 8000)
            {
                maxCount = 3;
            }
            else if (points < 12000)
            {
                maxCount = 4;
            }
            else if (points < 16000)
            {
                maxCount = 5;
            }
            else if (points < 20000)
            {
                maxCount = 6;
            }
            else if (points < 30000)
            {
                maxCount = 7;
            }
            else if (points < 40000)
            {
                maxCount = 8;
            }
            else if (points < 50000)
            {
                maxCount = 9;
            }
            else
            {
                maxCount = 10;
            }

            var availableSlots = maxCount - fortDetails.GymState.Memberships.Count();

            if (availableSlots > 0)
            {
                var pokemon = await GetDeployablePokemon(session);

                if (pokemon != null)
                {
                    var response = await session.Client.Fort.FortDeployPokemon(fortInfo.FortId, pokemon.Id);

                    if (response.Result == FortDeployPokemonResponse.Types.Result.Success)
                    {
                        session.EventDispatcher.Send(new GymDeployEvent()
                        {
                            PokemonId = pokemon.PokemonId,
                            Name      = fortDetails.Name
                        });
                        if (session.LogicSettings.GymCollectRewardAfter > 0)
                        {
                            var deployed = await session.Inventory.GetDeployedPokemons();

                            var count = deployed.Count();
                            if (count >= session.LogicSettings.GymCollectRewardAfter)
                            {
                                var collectDailyBonusResponse = await session.Client.Player.CollectDailyBonus();

                                if (collectDailyBonusResponse.Result == CollectDailyBonusResponse.Types.Result.Success)
                                {
                                    Logger.Write($"Collected {count * 10} coins", LogLevel.Gym, ConsoleColor.DarkYellow);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                string message = "No action. No FREE slots in GYM " + fortDetails.GymState.Memberships.Count() + "/" + maxCount;
                Logger.Write(message, LogLevel.Gym, ConsoleColor.White);
            }
        }
Exemple #22
0
        private static async Task WalkingToPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo)
        {
            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                   session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);

            // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX
            // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally.
            if (!session.LogicSettings.UseGpxPathing)
            {
                var eggWalker = new EggWalker(1000, session);

                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                // Always set the fort info in base walk strategy.

                var pokeStopDestination = new FortLocation(pokeStop.Latitude, pokeStop.Longitude,
                                                           await LocationUtils.GetElevation(session.ElevationService, pokeStop.Latitude, pokeStop.Longitude).ConfigureAwait(false), pokeStop, fortInfo);

                await session.Navigation.Move(pokeStopDestination,
                                              async() =>
                {
                    await OnWalkingToPokeStopOrGym(session, pokeStop, cancellationToken).ConfigureAwait(false);
                },
                                              session,
                                              cancellationToken).ConfigureAwait(false);

                // we have moved this distance, so apply it immediately to the egg walker.
                await eggWalker.ApplyDistance(distance, cancellationToken).ConfigureAwait(false);
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            _logger.Debug("UseNearbyPokestopsTask called.");

            cancellationToken.ThrowIfCancellationRequested();

            var pokestopsTuple = await GetPokeStops(session);

            _pokestopList = pokestopsTuple.Item2;

            while (_pokestopList.Any())
            {
                cancellationToken.ThrowIfCancellationRequested();
                await SnipeMSniperTask.CheckMSniperLocation(session, cancellationToken);

                _pokestopList =
                    _pokestopList.OrderBy(
                        i =>
                        LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();

                var pokeStop = _pokestopList[0];
                _pokestopList.RemoveAt(0);

                // this logic should only be called when we reach a pokestop either via GPX path or normal walking
                // as when walk-sniping, we want to get to the snipe ASAP rather than stop for lured pokemon upon
                // calling FarmPokestop; in that situation we are also always within 40m of the pokestop, so no
                // need to walk to it
                FortDetailsResponse fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX
                // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally.
                if (!session.LogicSettings.UseGpxPathing)
                {
                    var eggWalker = new EggWalker(1000, session);

                    var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                           session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);
                    cancellationToken.ThrowIfCancellationRequested();

                    if (!session.LogicSettings.UseGoogleWalk && !session.LogicSettings.UseYoursWalk)
                    {
                        session.EventDispatcher.Send(new FortTargetEvent {
                            Name = fortInfo.Name, Distance = distance, Route = "NecroBot"
                        });
                    }
                    else
                    {
                        BaseWalkStrategy.FortInfo = fortInfo;
                    }

                    await session.Navigation.Move(new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude,
                                                                    LocationUtils.getElevation(session, pokeStop.Latitude, pokeStop.Longitude)),
                                                  async() =>
                    {
                        // Catch normal map Pokemon
                        await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                        //Catch Incense Pokemon
                        await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                        // Minor fix google route ignore pokestop
                        await LookPokestops(session, pokeStop, cancellationToken);
                        return(true);
                    },
                                                  session,
                                                  cancellationToken);

                    // we have moved this distance, so apply it immediately to the egg walker.
                    await eggWalker.ApplyDistance(distance, cancellationToken);
                }

                await FortAction(session, pokeStop, fortInfo, cancellationToken);

                if (session.LogicSettings.SnipeAtPokestops || session.LogicSettings.UseSnipeLocationServer)
                {
                    await SnipePokemonTask.Execute(session, cancellationToken);
                }

                if (session.LogicSettings.EnableHumanWalkingSnipe)
                {
                    //refactore to move this code inside the task later.
                    await HumanWalkSnipeTask.Execute(session, cancellationToken,
                                                     async (double lat, double lng) =>
                    {
                        var reachablePokestops = _pokestopList.Where(i =>
                                                                     LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                             session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40).ToList();
                        reachablePokestops = reachablePokestops.OrderBy(i =>
                                                                        LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                                session.Client.CurrentLongitude, i.Latitude, i.Longitude)).ToList();

                        foreach (var ps in reachablePokestops)
                        {
                            if (!session.LogicSettings.UseGpxPathing)
                            {
                                _pokestopList.Remove(ps);
                            }

                            var fi = await session.Client.Fort.GetFort(ps.Id, ps.Latitude, ps.Longitude);
                            await FortAction(session, ps, fi, cancellationToken);
                        }
                    },
                                                     async() =>
                    {
                        // if using GPX we have to move back to the original pokestop, to resume the path.
                        // we do not try to use pokestops on the way back, as we will have used them getting
                        // here.
                        if (session.LogicSettings.UseGpxPathing)
                        {
                            var eggWalker = new EggWalker(1000, session);

                            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                   session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);
                            var geo = new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude);

                            await session.Navigation.Move(geo,
                                                          async() =>
                            {
                                await CatchNearbyPokemonsTask.Execute(session, cancellationToken);
                                //Catch Incense Pokemon
                                await CatchIncensePokemonsTask.Execute(session, cancellationToken);
                                return(true);
                            },
                                                          session,
                                                          cancellationToken);

                            await eggWalker.ApplyDistance(distance, cancellationToken);
                            return;
                        }

                        var nearestStop = _pokestopList.OrderBy(i =>
                                                                LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                                                        session.Client.CurrentLongitude, i.Latitude, i.Longitude)).FirstOrDefault();

                        var walkedDistance = LocationUtils.CalculateDistanceInMeters(nearestStop.Latitude, nearestStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude);
                        if (walkedDistance > session.LogicSettings.HumanWalkingSnipeWalkbackDistanceLimit)
                        {
                            await Task.Delay(3000);
                            var nearbyPokeStops = await UpdateFortsData(session);
                            var notexists       = nearbyPokeStops.Where(p => !_pokestopList.Any(x => x.Id == p.Id)).ToList();
                            _pokestopList.AddRange(notexists);
                            session.EventDispatcher.Send(new PokeStopListEvent {
                                Forts = _pokestopList
                            });
                            session.EventDispatcher.Send(new HumanWalkSnipeEvent()
                            {
                                Type            = HumanWalkSnipeEventTypes.PokestopUpdated,
                                Pokestops       = notexists,
                                NearestDistance = walkedDistance
                            });
                        }
                    });
                }
            }
        }
Exemple #24
0
        private static async Task DoActionAtPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo, bool doNotTrySpin = false)
        {
            //Catch Lure Pokemon
            if (pokeStop.LureInfo != null)
            {
                // added for cooldowns
                await Task.Delay(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, 3000)).ConfigureAwait(false);

                await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken).ConfigureAwait(false);
            }

            // Spin as long as we haven't reached the user defined limits
            if (!_pokestopLimitReached && !_pokestopTimerReached)
            {
                await FarmPokestop(session, pokeStop, fortInfo, cancellationToken, doNotTrySpin).ConfigureAwait(false);
            }
            else
            {
                // We hit the pokestop limit but not the pokemon limit. So we want to set the cooldown on the pokestop so that
                // we keep moving and don't walk back and forth between 2 pokestops.
                pokeStop.CooldownCompleteTimestampMs = DateTime.UtcNow.ToUnixTime() + 5 * 60 * 1000; // 5 minutes to cooldown for pokestop.
            }

            if (++_stopsHit >= _storeRi)     //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing.
            {
                _storeRi  = _rc.Next(6, 12); //set new storeRI for new random value
                _stopsHit = 0;

                if (session.LogicSettings.UseNearActionRandom)
                {
                    await HumanRandomActionTask.Execute(session, cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    await RecycleItemsTask.Execute(session, cancellationToken).ConfigureAwait(false);

                    if (session.LogicSettings.UseLuckyEggConstantly)
                    {
                        await UseLuckyEggConstantlyTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.UseIncenseConstantly)
                    {
                        await UseIncenseConstantlyTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.TransferWeakPokemon)
                    {
                        await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.AutomaticallyLevelUpPokemon)
                    {
                        await LevelUpPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                    if (session.LogicSettings.RenamePokemon)
                    {
                        await RenamePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }

                    await GetPokeDexCount.Execute(session, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #25
0
        private void PrintPokestopTakeInfos(FortDetailsResponse fortInfo, FortSearchResponse fortSearch)
        {
            StringWriter PokeStopOutput = new StringWriter();
            if (fortSearch.ExperienceAwarded == 0)
            {
                ColoredConsoleWrite(Color.Cyan, "Wait for unlock catchs ...");
                return;
            }     
            PokeStopOutput.Write($"");
            if (fortInfo.Name != string.Empty)
                PokeStopOutput.Write("PokeStop: " + fortInfo.Name);
            if (fortSearch.ExperienceAwarded != 0)
                PokeStopOutput.Write($", XP: {fortSearch.ExperienceAwarded}");
            if (fortSearch.GemsAwarded != 0)
                PokeStopOutput.Write($", Gems: {fortSearch.GemsAwarded}");
            if (fortSearch.PokemonDataEgg != null)
                PokeStopOutput.Write($", Eggs: {fortSearch.PokemonDataEgg}");
            if (GetFriendlyItemsString(fortSearch.ItemsAwarded) != string.Empty)
                PokeStopOutput.Write($", Items: {GetFriendlyItemsString(fortSearch.ItemsAwarded)} ");
            ColoredConsoleWrite(Color.Cyan, PokeStopOutput.ToString());
            if (fortSearch.ExperienceAwarded != 0)
                TotalExperience += (fortSearch.ExperienceAwarded);

            PokeStopOutput.Dispose();
        }
Exemple #26
0
        private static async Task WalkingToPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo)
        {
            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                   session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);

            // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX
            // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally.
            if (!session.LogicSettings.UseGpxPathing)
            {
                var eggWalker = new EggWalker(1000, session);

                cancellationToken.ThrowIfCancellationRequested();

                // Always set the fort info in base walk strategy.
                BaseWalkStrategy.FortInfo = fortInfo;

                var pokeStopDestination = new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude,
                                                            LocationUtils.getElevation(session, pokeStop.Latitude, pokeStop.Longitude));

                if (pokeStop.Type == FortType.Gym)
                {
                    session.EventDispatcher.Send(new GymWalkToTargetEvent()
                    {
                        Name      = fortInfo.Name,
                        Distance  = distance,
                        Latitude  = fortInfo.Latitude,
                        Longitude = fortInfo.Longitude
                    });
                }

                await session.Navigation.Move(pokeStopDestination,
                                              async() =>
                {
                    await OnWalkingToPokeStopOrGym(session, pokeStop, cancellationToken);
                },
                                              session,
                                              cancellationToken);

                // we have moved this distance, so apply it immediately to the egg walker.
                await eggWalker.ApplyDistance(distance, cancellationToken);
            }
        }
        private static async Task WalkingToPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo)
        {
            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                   session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude);

            // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX
            // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally.
            if (!session.LogicSettings.UseGpxPathing)
            {
                // Will modify Lat,Lng and Name to fake position
                //Need refactor it to speparate from pokestop logic -> samuraitruong will do it.
                SetMoveToTargetTask.CheckSetMoveToTargetStatus(ref fortInfo, ref pokeStop);

                var eggWalker = new EggWalker(1000, session);

                cancellationToken.ThrowIfCancellationRequested();

                if (!session.LogicSettings.UseGoogleWalk && !session.LogicSettings.UseYoursWalk)
                {
                    session.EventDispatcher.Send(new FortTargetEvent {
                        Name = fortInfo.Name, Distance = distance, Route = "NecroBot"
                    });
                }
                else
                {
                    BaseWalkStrategy.FortInfo = fortInfo;
                }
                var pokeStopDestination = new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude,
                                                            LocationUtils.getElevation(session, pokeStop.Latitude, pokeStop.Longitude));

                if (pokeStop.Type == FortType.Gym)
                {
                    session.EventDispatcher.Send(new GymWalkToTargetEvent()
                    {
                        Name      = fortInfo.Name,
                        Distance  = distance,
                        Latitude  = fortInfo.Latitude,
                        Longitude = fortInfo.Longitude
                    });
                }

                await session.Navigation.Move(pokeStopDestination,
                                              async() =>
                {
                    await OnWalkingToPokeStopOrGym(session, pokeStop, cancellationToken);
                },
                                              session,
                                              cancellationToken);

                // we have moved this distance, so apply it immediately to the egg walker.
                await eggWalker.ApplyDistance(distance, cancellationToken);
            }
        }
Exemple #28
0
        private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false)
        {
            if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime())
            {
                return;
            }

            FortSearchResponse fortSearch;
            var       timesZeroXPawarded = 0;
            var       fortTry            = 0;  //Current check
            const int retryNumber        = 50; //How many times it needs to check to clear softban
            const int zeroCheck          = 5;  //How many times it checks fort before it thinks it's softban

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (SearchThresholdExceeds(session))
                {
                    break;
                }

                fortSearch =
                    await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });
                        if (doNotRetry)
                        {
                            break;
                        }
                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                        }
                    }
                }
                else
                {
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id            = pokeStop.Id,
                        Name          = fortInfo.Name,
                        Exp           = fortSearch.ExperienceAwarded,
                        Gems          = fortSearch.GemsAwarded,
                        Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Latitude      = pokeStop.Latitude,
                        Longitude     = pokeStop.Longitude,
                        Altitude      = session.Client.CurrentAltitude,
                        InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull
                    });

                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        _storeRi = 1;
                    }

                    if (session.LogicSettings.UsePokeStopLimit)
                    {
                        session.Stats.PokeStopTimestamps.Add(DateTime.Now.Ticks);
                        UpdateTimeStampsPokestop?.Invoke();
                        Logger.Write($"(POKESTOP LIMIT) {session.Stats.PokeStopTimestamps.Count}/{session.LogicSettings.PokeStopLimit}",
                                     LogLevel.Info, ConsoleColor.Yellow);
                    }
                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry)
            {
                if (++_randomStop >= _randomNumber)
                {
                    _randomNumber = _rc.Next(4, 11);
                    _randomStop   = 0;
                    int randomWaitTime = _rc.Next(30, 120);
                    await Task.Delay(randomWaitTime, cancellationToken);
                }
            }
        }
        private static async Task FortAction(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken)
        {
            //Catch Lure Pokemon
            if (pokeStop.LureInfo != null)
            {
                // added for cooldowns
                await Task.Delay(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, 3000));

                await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken);
            }

            await FarmPokestop(session, pokeStop, fortInfo, cancellationToken);

            if (++stopsHit >= storeRI)     //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing.
            {
                storeRI  = rc.Next(6, 12); //set new storeRI for new random value
                stopsHit = 0;

                if (session.LogicSettings.UseNearActionRandom)
                {
                    await HumanRandomActionTask.Execute(session, cancellationToken);
                }
                else
                {
                    await RecycleItemsTask.Execute(session, cancellationToken);

                    if (session.LogicSettings.EvolveAllPokemonWithEnoughCandy ||
                        session.LogicSettings.EvolveAllPokemonAboveIv ||
                        session.LogicSettings.UseLuckyEggsWhileEvolving ||
                        session.LogicSettings.KeepPokemonsThatCanEvolve)
                    {
                        await EvolvePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.UseLuckyEggConstantly)
                    {
                        await UseLuckyEggConstantlyTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.UseIncenseConstantly)
                    {
                        await UseIncenseConstantlyTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.TransferDuplicatePokemon)
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.TransferWeakPokemon)
                    {
                        await TransferWeakPokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.RenamePokemon)
                    {
                        await RenamePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.AutoFavoritePokemon)
                    {
                        await FavoritePokemonTask.Execute(session, cancellationToken);
                    }
                    if (session.LogicSettings.AutomaticallyLevelUpPokemon)
                    {
                        await LevelUpPokemonTask.Execute(session, cancellationToken);
                    }

                    await GetPokeDexCount.Execute(session, cancellationToken);
                }
            }
        }
        private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false)
        {
            // If the cooldown is in the future than don't farm the pokestop.
            if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime())
            {
                return;
            }

            if (session.Stats.SearchThresholdExceeds(session))
            {
                if (session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit)
                {
                    throw new Exceptions.ActiveSwitchByRuleException()
                          {
                              MatchedRule = SwitchRules.SpinPokestopReached, ReachedValue = session.LogicSettings.PokeStopLimit
                          };
                }
                return;
            }

            FortSearchResponse fortSearch;
            var timesZeroXPawarded = 0;
            var fortTry            = 0;                                     //Current check
            int retryNumber        = session.LogicSettings.ByPassSpinCount; //How many times it needs to check to clear softban
            int zeroCheck          = Math.Min(5, retryNumber);              //How many times it checks fort before it thinks it's softban

            do
            {
                cancellationToken.ThrowIfCancellationRequested();

                fortSearch =
                    await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude);

                if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0)
                {
                    timesZeroXPawarded = 0;
                }
                if (fortSearch.ExperienceAwarded == 0 && fortSearch.Result != FortSearchResponse.Types.Result.InventoryFull)
                {
                    timesZeroXPawarded++;

                    if (timesZeroXPawarded > zeroCheck)
                    {
                        if ((int)fortSearch.CooldownCompleteTimestampMs != 0)
                        {
                            break; // Check if successfully looted, if so program can continue as this was "false alarm".
                        }

                        fortTry += 1;

                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry,
                            Max    = retryNumber - zeroCheck,
                            Looted = false
                        });
                        if (doNotRetry)
                        {
                            break;
                        }
                        if (!session.LogicSettings.FastSoftBanBypass)
                        {
                            DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                        }
                    }
                }
                else
                {
                    softbanCount = 0;
                    if (fortTry != 0)
                    {
                        session.EventDispatcher.Send(new FortFailedEvent
                        {
                            Name   = fortInfo.Name,
                            Try    = fortTry + 1,
                            Max    = retryNumber - zeroCheck,
                            Looted = true
                        });
                    }

                    session.EventDispatcher.Send(new FortUsedEvent
                    {
                        Id            = pokeStop.Id,
                        Name          = fortInfo.Name,
                        Exp           = fortSearch.ExperienceAwarded,
                        Gems          = fortSearch.GemsAwarded,
                        Items         = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded),
                        Latitude      = pokeStop.Latitude,
                        Longitude     = pokeStop.Longitude,
                        Altitude      = session.Client.CurrentAltitude,
                        InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull
                    });
                    foreach (var item in fortSearch.ItemsAwarded)
                    {
                        await session.Inventory.UpdateInventoryItem(item.ItemId, item.ItemCount);
                    }
                    if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull)
                    {
                        await RecycleItemsTask.Execute(session, cancellationToken);

                        _storeRi = 1;
                    }

                    if (session.LogicSettings.UsePokeStopLimit)
                    {
                        session.Stats.AddPokestopTimestamp(DateTime.Now.Ticks);
                        Logger.Write($"(POKESTOP LIMIT) {session.Stats.GetNumPokestopsInLast24Hours()}/{session.LogicSettings.PokeStopLimit}",
                                     LogLevel.Info, ConsoleColor.Yellow);
                    }
                    break; //Continue with program as loot was succesfull.
                }
            } while (fortTry < retryNumber - zeroCheck);
            //Stop trying if softban is cleaned earlier or if 40 times fort looting failed.

            if (session.LogicSettings.AllowMultipleBot)
            {
                if (fortTry >= retryNumber - zeroCheck)
                {
                    softbanCount++;

                    //only check if PokestopSoftbanCount > 0
                    if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings) &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount > 0 &&
                        session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount <= softbanCount)
                    {
                        softbanCount = 0;

                        //Activate switcher by pokestop
                        throw new ActiveSwitchByRuleException()
                              {
                                  MatchedRule  = SwitchRules.PokestopSoftban,
                                  ReachedValue = session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount
                              };
                    }
                }
            }
            else
            {
                softbanCount = 0; //reset softban count
            }

            if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry)
            {
                if (++_randomStop >= _randomNumber)
                {
                    _randomNumber = _rc.Next(4, 11);
                    _randomStop   = 0;
                    int randomWaitTime = _rc.Next(30, 120);
                    await Task.Delay(randomWaitTime, cancellationToken);
                }
            }
        }
 public GymHasBeenTakenMessage(FortData mapGymData, FortDetailsResponse gymDetails, InstanceConfiguration configuration) : base(configuration)
 {
     this.mapGymData = mapGymData;
     this.gymDetails = gymDetails;
 }