Exemple #1
0
        /// <summary>
        /// Because this function sometime being called inside loop, return true it mean we don't want break look, false it mean not need to call this , break a loop from caller function
        /// </summary>
        /// <param name="session"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="encounter"></param>
        /// <param name="pokemon"></param>
        /// <param name="currentFortData"></param>
        /// <param name="sessionAllowTransfer"></param>
        /// <returns></returns>
        public static async Task <bool> Execute(ISession session,
                                                CancellationToken cancellationToken,
                                                dynamic encounter,
                                                MapPokemon pokemon,
                                                FortData currentFortData,
                                                bool sessionAllowTransfer)
        {
            var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            manager.ThrowIfSwitchAccountRequested();
            // If the encounter is null nothing will work below, so exit now
            if (encounter == null)
            {
                return(true);
            }

            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);

            if (session.SaveBallForByPassCatchFlee && totalBalls < BALL_REQUIRED_TO_BYPASS_CATCHFLEE)
            {
                return(false);
            }

            // Exit if user defined max limits reached
            if (session.Stats.CatchThresholdExceeds(session))
            {
                if (manager.AllowMultipleBot() &&
                    session.LogicSettings.MultipleBotConfig.SwitchOnCatchLimit &&
                    TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                {
                    throw new ActiveSwitchByRuleException()
                          {
                              MatchedRule  = SwitchRules.CatchLimitReached,
                              ReachedValue = session.LogicSettings.CatchPokemonLimit
                          };
                }

                return(false);
            }
            using (var block = new BlockableScope(session, BotActions.Catch))
            {
                if (!await block.WaitToRun().ConfigureAwait(false))
                {
                    return(true);
                }

                AmountOfBerries = new Dictionary <ItemId, int>();

                cancellationToken.ThrowIfCancellationRequested();

                float probability = encounter.CaptureProbability?.CaptureProbability_[0];

                PokemonData encounteredPokemon;
                long        unixTimeStamp;
                ulong       _encounterId;
                string      _spawnPointId;

                // Calling from CatchNearbyPokemonTask and SnipePokemonTask
                if (encounter is EncounterResponse &&
                    (encounter?.Status == EncounterResponse.Types.Status.EncounterSuccess))
                {
                    encounteredPokemon = encounter.WildPokemon?.PokemonData;
                    unixTimeStamp      = encounter.WildPokemon?.LastModifiedTimestampMs
                                         + encounter.WildPokemon?.TimeTillHiddenMs;
                    _spawnPointId = encounter.WildPokemon?.SpawnPointId;
                    _encounterId  = encounter.WildPokemon?.EncounterId;
                }
                // Calling from CatchIncensePokemonTask
                else if (encounter is IncenseEncounterResponse &&
                         (encounter?.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = pokemon.ExpirationTimestampMs;
                    _spawnPointId      = pokemon.SpawnPointId;
                    _encounterId       = pokemon.EncounterId;
                }
                // Calling from CatchLurePokemon
                else if (encounter is DiskEncounterResponse &&
                         encounter?.Result == DiskEncounterResponse.Types.Result.Success &&
                         !(currentFortData == null))
                {
                    encounteredPokemon = encounter?.PokemonData;
                    unixTimeStamp      = currentFortData.LureInfo.LureExpiresTimestampMs;
                    _spawnPointId      = currentFortData.Id;
                    _encounterId       = currentFortData.LureInfo.EncounterId;
                }
                else
                {
                    return(true); // No success to work with, exit
                }
                // Check for pokeballs before proceeding
                var pokeball = await GetBestBall(session, encounteredPokemon, probability).ConfigureAwait(false);

                if (pokeball == ItemId.ItemUnknown)
                {
                    Logger.Write(session.Translation.GetTranslation(TranslationString.ZeroPokeballInv));
                    return(false);
                }

                // Calculate CP and IV
                var pokemonCp = encounteredPokemon?.Cp;
                var pokemonIv = PokemonInfo.CalculatePokemonPerfection(encounteredPokemon);
                var lv        = PokemonInfo.GetLevel(encounteredPokemon);

                // Calculate distance away
                var latitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Latitude
                    : currentFortData.Latitude;
                var longitude = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Longitude
                    : currentFortData.Longitude;

                var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                       session.Client.CurrentLongitude, latitude, longitude);
                if (session.LogicSettings.ActivateMSniper)
                {
                    var newdata = new MSniperServiceTask.EncounterInfo()
                    {
                        EncounterId  = _encounterId.ToString(),
                        Iv           = Math.Round(pokemonIv, 2),
                        Latitude     = latitude.ToString("G17", CultureInfo.InvariantCulture),
                        Longitude    = longitude.ToString("G17", CultureInfo.InvariantCulture),
                        PokemonId    = (int)(encounteredPokemon?.PokemonId ?? 0),
                        PokemonName  = encounteredPokemon?.PokemonId.ToString(),
                        SpawnPointId = _spawnPointId,
                        Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString(),
                        Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString(),
                        Expiration   = unixTimeStamp
                    };
                    session.EventDispatcher.Send(newdata);
                }

                DateTime expiredDate =
                    new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(unixTimeStamp));
                var encounterEV = new EncounteredEvent()
                {
                    Latitude        = latitude,
                    Longitude       = longitude,
                    PokemonId       = encounteredPokemon.PokemonId,
                    IV              = pokemonIv,
                    Level           = (int)lv,
                    Expires         = expiredDate.ToUniversalTime(),
                    ExpireTimestamp = unixTimeStamp,
                    SpawnPointId    = _spawnPointId,
                    EncounterId     = _encounterId.ToString(),
                    Move1           = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString(),
                    Move2           = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString(),
                };

                //add catch to avoid snipe duplicate
                string uniqueCacheKey = CatchPokemonTask.GetUsernameGeoLocationCacheKey(session.Settings.Username, encounterEV.PokemonId, encounterEV.Latitude, encounterEV.Longitude);
                session.Cache.Add(uniqueCacheKey, encounterEV, DateTime.Now.AddMinutes(30));

                session.EventDispatcher.Send(encounterEV);

                if (IsNotMetWithCatchCriteria(session, encounteredPokemon, pokemonIv, lv, pokemonCp))
                {
                    session.EventDispatcher.Send(new NoticeEvent
                    {
                        Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped,
                                                                     encounteredPokemon.PokemonId)
                    });
                    session.Cache.Add(CatchPokemonTask.GetEncounterCacheKey(_encounterId), encounteredPokemon, expiredDate);
                    Logger.Write(
                        $"Filter catch not met. {encounteredPokemon.PokemonId.ToString()} IV {pokemonIv} lv {lv} {pokemonCp} move1 {PokemonInfo.GetPokemonMove1(encounteredPokemon)} move 2 {PokemonInfo.GetPokemonMove2(encounteredPokemon)}");
                    return(true);
                }

                CatchPokemonResponse caughtPokemonResponse = null;
                var lastThrow      = CatchPokemonResponse.Types.CatchStatus.CatchSuccess; // Initializing lastThrow
                var attemptCounter = 1;

                // Main CatchPokemon-loop
                do
                {
                    if (session.LogicSettings.UseHumanlikeDelays)
                    {
                        await DelayingUtils.DelayAsync(session.LogicSettings.BeforeCatchDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);
                    }

                    if ((session.LogicSettings.MaxPokeballsPerPokemon > 0 &&
                         attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                    {
                        break;
                    }

                    pokeball = await GetBestBall(session, encounteredPokemon, probability).ConfigureAwait(false);

                    if (pokeball == ItemId.ItemUnknown)
                    {
                        session.EventDispatcher.Send(new NoPokeballEvent
                        {
                            Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId,
                            Cp = encounteredPokemon.Cp
                        });
                        return(false);
                    }

                    // Determine whether to use berries or not
                    if (lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                    {
                        //AmountOfBerries++;
                        //if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                        await UseBerry(session,
                                       encounterEV.PokemonId,
                                       _encounterId,
                                       _spawnPointId,
                                       pokemonIv,
                                       pokemonCp ?? 10000, //unknown CP pokemon, want to use berry
                                       encounterEV.Level,
                                       probability,
                                       cancellationToken).ConfigureAwait(false);
                    }

                    bool hitPokemon = true;

                    //default to excellent throw
                    var normalizedRecticleSize = 1.95;

                    //default spin
                    var spinModifier = 1.0;

                    //Humanized throws
                    if (session.LogicSettings.EnableHumanizedThrows)
                    {
                        //thresholds: https://gist.github.com/anonymous/077d6dea82d58b8febde54ae9729b1bf
                        var spinTxt = "Curve";
                        var hitTxt  = "Excellent";
                        if (pokemonCp > session.LogicSettings.ForceExcellentThrowOverCp ||
                            pokemonIv > session.LogicSettings.ForceExcellentThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.7) + 1.7;
                        }
                        else if (pokemonCp >= session.LogicSettings.ForceGreatThrowOverCp ||
                                 pokemonIv >= session.LogicSettings.ForceGreatThrowOverIv)
                        {
                            normalizedRecticleSize = Random.NextDouble() * (1.95 - 1.3) + 1.3;
                            hitTxt = "Great";
                        }
                        else
                        {
                            var regularThrow = 100 - (session.LogicSettings.ExcellentThrowChance +
                                                      session.LogicSettings.GreatThrowChance +
                                                      session.LogicSettings.NiceThrowChance);
                            var rnd = Random.Next(1, 101);

                            if (rnd <= regularThrow)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1 - 0.1) + 0.1;
                                hitTxt = "Ordinary";
                            }
                            else if (rnd <= regularThrow + session.LogicSettings.NiceThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.3 - 1) + 1;
                                hitTxt = "Nice";
                            }
                            else if (rnd <=
                                     regularThrow + session.LogicSettings.NiceThrowChance +
                                     session.LogicSettings.GreatThrowChance)
                            {
                                normalizedRecticleSize = Random.NextDouble() * (1.7 - 1.3) + 1.3;
                                hitTxt = "Great";
                            }

                            if (Random.NextDouble() * 100 > session.LogicSettings.CurveThrowChance)
                            {
                                spinModifier = 0.0;
                                spinTxt      = "Straight";
                            }
                        }


                        // Round to 2 decimals
                        normalizedRecticleSize = Math.Round(normalizedRecticleSize, 2);

                        // Missed throw check
                        int missChance = Random.Next(1, 101);
                        if (missChance <= session.LogicSettings.ThrowMissPercentage &&
                            session.LogicSettings.EnableMissedThrows)
                        {
                            hitPokemon = false;
                        }

                        Logger.Write($"(Threw ball) {hitTxt} throw, {spinTxt}-ball, HitPokemon = {hitPokemon}...",
                                     LogLevel.Debug);
                    }

                    if (CatchFleeContinuouslyCount >= 3 && session.LogicSettings.ByPassCatchFlee)
                    {
                        MSniperServiceTask.BlockSnipe();

                        if (totalBalls <= BALL_REQUIRED_TO_BYPASS_CATCHFLEE)
                        {
                            Logger.Write("You don't have enough balls to bypass catchflee");
                            return(false);
                        }
                        List <ItemId> ballToByPass = new List <ItemId>();
                        var           numPokeBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemPokeBall).ConfigureAwait(false);

                        for (int i = 0; i < numPokeBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemPokeBall);
                        }
                        var numGreatBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemGreatBall).ConfigureAwait(false);

                        for (int i = 0; i < numGreatBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemGreatBall);
                        }
                        var numUltraBalls = await session.Inventory.GetItemAmountByType(ItemId.ItemUltraBall).ConfigureAwait(false);

                        for (int i = 0; i < numUltraBalls - 1; i++)
                        {
                            ballToByPass.Add(ItemId.ItemUltraBall);
                        }
                        bool catchMissed = true;

                        Random r = new Random();
                        for (int i = 0; i < ballToByPass.Count - 1; i++)
                        {
                            if (i > 130 && r.Next(0, 100) <= 30)
                            {
                                catchMissed = false;
                            }
                            else
                            {
                                catchMissed = true;
                            }

                            caughtPokemonResponse =
                                await session.Client.Encounter.CatchPokemon(
                                    encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                    ?pokemon.EncounterId
                                    : _encounterId,
                                    encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                    ?pokemon.SpawnPointId
                                    : currentFortData.Id, ballToByPass[i], 1.0, 1.0, !catchMissed).ConfigureAwait(false);

                            await session.Inventory.UpdateInventoryItem(ballToByPass[i]).ConfigureAwait(false);

                            await Task.Delay(100).ConfigureAwait(false);

                            Logger.Write($"CatchFlee By pass : {ballToByPass[i].ToString()} , Attempt {i}, result {caughtPokemonResponse.Status}");

                            if (caughtPokemonResponse.Status != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                            {
                                session.SaveBallForByPassCatchFlee = false;
                                CatchFleeContinuouslyCount         = 0;
                                break;
                            }
                        }
                    }
                    else
                    {
                        caughtPokemonResponse =
                            await session.Client.Encounter.CatchPokemon(
                                encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                ?pokemon.EncounterId
                                : _encounterId,
                                encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                ?pokemon.SpawnPointId
                                : currentFortData.Id, pokeball, normalizedRecticleSize, spinModifier, hitPokemon).ConfigureAwait(false);

                        await session.Inventory.UpdateInventoryItem(pokeball).ConfigureAwait(false);
                    }


                    var evt = new PokemonCaptureEvent()
                    {
                        Status        = caughtPokemonResponse.Status,
                        CaptureReason = caughtPokemonResponse.CaptureReason,
                        Latitude      = latitude,
                        Longitude     = longitude
                    };

                    lastThrow = caughtPokemonResponse.Status; // sets lastThrow status


                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                    {
                        evt.Shiny   = (await session.Inventory.GetPokemons().ConfigureAwait(false)).First(x => x.Id == caughtPokemonResponse.CapturedPokemonId).PokemonDisplay.Shiny ? "Yes" : "No";
                        evt.Form    = (await session.Inventory.GetPokemons().ConfigureAwait(false)).First(x => x.Id == caughtPokemonResponse.CapturedPokemonId).PokemonDisplay.Form.ToString().Replace("Unown", "").Replace("Unset", "Normal");
                        evt.Costume = (await session.Inventory.GetPokemons().ConfigureAwait(false)).First(x => x.Id == caughtPokemonResponse.CapturedPokemonId).PokemonDisplay.Costume.ToString().Replace("Unset", "Regular");
                        evt.Gender  = (await session.Inventory.GetPokemons().ConfigureAwait(false)).First(x => x.Id == caughtPokemonResponse.CapturedPokemonId).PokemonDisplay.Gender.ToString();

                        var totalExp      = 0;
                        var stardust      = caughtPokemonResponse.CaptureAward.Stardust.Sum();
                        var totalStarDust = session.Inventory.UpdateStarDust(stardust);
                        var CaptuerXP     = caughtPokemonResponse.CaptureAward.Xp.Sum();

                        if (encounteredPokemon != null)
                        {
                            encounteredPokemon.Id = caughtPokemonResponse.CapturedPokemonId;
                        }
                        foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                        {
                            totalExp += xp;
                        }

                        //This accounts for XP for CatchFlee
                        if (totalExp < 1)
                        {
                            totalExp = 25;
                        }

                        evt.Exp      = totalExp;
                        evt.Stardust = stardust;
                        evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;
                        evt.Candy    = await session.Inventory.GetCandyFamily(pokemon.PokemonId).ConfigureAwait(false);

                        evt.totalStarDust = totalStarDust;

                        if (session.LogicSettings.AutoFavoriteShinyOnCatch)
                        {
                            if (evt.Shiny == "Yes")
                            {
                                await FavoritePokemonTask.Execute(session, encounteredPokemon.Id, true);

                                Logger.Write($"You've caught a Shiny Pokemon ({encounteredPokemon.Nickname}) and it has been Favorited.");
                            }
                        }
                    }

                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess ||
                        caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                    {
                        // Also count catch flee against the catch limit
                        if (session.LogicSettings.UseCatchLimit)
                        {
                            session.Stats.AddPokemonTimestamp(DateTime.Now.Ticks);
                            session.EventDispatcher.Send(new CatchLimitUpdate(session.Stats.GetNumPokemonsInLast24Hours(), session.LogicSettings.CatchPokemonLimit));
                        }
                    }

                    evt.CatchType = encounter is EncounterResponse
                        ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal)
                        : encounter is DiskEncounterResponse
                            ? session.Translation.GetTranslation(TranslationString.CatchTypeLure)
                            : session.Translation.GetTranslation(TranslationString.CatchTypeIncense);

                    evt.CatchTypeText = encounter is EncounterResponse
                        ? "normal"
                        : encounter is DiskEncounterResponse
                            ? "lure"
                            : "incense";
                    evt.Id = encounter is EncounterResponse
                        ? pokemon.PokemonId
                        : encounter?.PokemonData.PokemonId;
                    evt.EncounterId  = _encounterId;
                    evt.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon);
                    evt.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon);
                    evt.Expires      = pokemon?.ExpirationTimestampMs ?? 0;
                    evt.SpawnPointId = _spawnPointId;
                    evt.Level        = PokemonInfo.GetLevel(encounteredPokemon);
                    evt.Cp           = encounteredPokemon.Cp;
                    evt.MaxCp        = PokemonInfo.CalculateMaxCp(encounteredPokemon.PokemonId);
                    evt.Perfection   = Math.Round(PokemonInfo.CalculatePokemonPerfection(encounteredPokemon), 2);
                    evt.Probability  = Math.Round(probability * 100, 2);
                    evt.Distance     = distance;
                    evt.Pokeball     = pokeball;
                    evt.Attempt      = attemptCounter;

                    //await session.Inventory.RefreshCachedInventory().ConfigureAwait(false);

                    evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball).ConfigureAwait(false);

                    evt.Rarity = PokemonGradeHelper.GetPokemonGrade(evt.Id).ToString();

                    session.EventDispatcher.Send(evt);

                    attemptCounter++;

                    // If Humanlike delays are used
                    if (session.LogicSettings.UseHumanlikeDelays)
                    {
                        switch (caughtPokemonResponse.Status)
                        {
                        case CatchPokemonResponse.Types.CatchStatus.CatchError:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchErrorDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchSuccess:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchSuccessDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchEscape:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchEscapeDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchFlee:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchFleeDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        case CatchPokemonResponse.Types.CatchStatus.CatchMissed:
                            await DelayingUtils.DelayAsync(session.LogicSettings.CatchMissedDelay, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);

                            break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        await DelayingUtils.DelayAsync(session.LogicSettings.DelayBetweenPlayerActions, 0, session.CancellationTokenSource.Token).ConfigureAwait(false);
                    }
                } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                         caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                {
                    CatchFleeContinuouslyCount++;
                    if (CatchFleeContinuouslyCount >= 3 && session.LogicSettings.ByPassCatchFlee)
                    {
                        session.SaveBallForByPassCatchFlee = true;
                        Logger.Write("Seem that bot has been catch flee softban, Bot will start save 100 balls to by pass it.");
                    }
                    if (manager.AllowMultipleBot() && !session.LogicSettings.ByPassCatchFlee)
                    {
                        if (CatchFleeContinuouslyCount > session.LogicSettings.MultipleBotConfig.CatchFleeCount &&
                            TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch())
                        {
                            CatchFleeContinuouslyCount         = 0;
                            session.SaveBallForByPassCatchFlee = false;

                            throw new ActiveSwitchByRuleException()
                                  {
                                      MatchedRule  = SwitchRules.CatchFlee,
                                      ReachedValue = session.LogicSettings.MultipleBotConfig.CatchFleeCount
                                  };
                        }
                    }
                }
                else
                {
                    //reset if not catch flee.
                    if (caughtPokemonResponse.Status != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                    {
                        CatchFleeContinuouslyCount = 0;
                        MSniperServiceTask.UnblockSnipe();
                    }
                }

                session.Actions.RemoveAll(x => x == BotActions.Catch);

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings, manager))
                {
                    ExecuteSwitcher(session, encounterEV);
                }

                if (session.LogicSettings.TransferDuplicatePokemonOnCapture &&
                    session.LogicSettings.TransferDuplicatePokemon &&
                    sessionAllowTransfer &&
                    caughtPokemonResponse != null &&
                    caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.TransferRandom(session, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                    }
                }
            }
            return(true);
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            cancellationToken.ThrowIfCancellationRequested();
            if (!session.LogicSettings.CatchPokemon || session.CatchBlockTime > DateTime.Now)
            {
                return;
            }

            Logger.Write(
                session.Translation.GetTranslation(TranslationString.LookingForIncensePokemon),
                LogLevel.Debug
                );

            var incensePokemon = await session.Client.Map.GetIncensePokemons().ConfigureAwait(false);

            if (incensePokemon.Result == GetIncensePokemonResponse.Types.Result.IncenseEncounterAvailable)
            {
                var pokemon = new MapPokemon
                {
                    EncounterId           = incensePokemon.EncounterId,
                    ExpirationTimestampMs = incensePokemon.DisappearTimestampMs,
                    Latitude     = incensePokemon.Latitude,
                    Longitude    = incensePokemon.Longitude,
                    PokemonId    = incensePokemon.PokemonId,
                    SpawnPointId = incensePokemon.EncounterLocation
                };

                //add delegate function
                OnPokemonEncounterEvent(new List <MapPokemon> {
                    pokemon
                });

                if (session.Cache.Get(CatchPokemonTask.GetEncounterCacheKey(incensePokemon.EncounterId)) != null)
                {
                    return; //pokemon been ignore before
                }
                if ((session.LogicSettings.UsePokemonToCatchLocallyListOnly && !session.LogicSettings.PokemonToCatchLocally.Pokemon.Contains(pokemon.PokemonId)) ||
                    (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)))
                {
                    Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonIgnoreFilter,
                                                                    session.Translation.GetPokemonTranslation(pokemon.PokemonId)));
                }
                else
                {
                    var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                           session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude);
                    await Task.Delay(distance > 100? 500 : 100, cancellationToken).ConfigureAwait(false);

                    var encounter =
                        await
                        session.Client.Encounter.EncounterIncensePokemon((ulong)pokemon.EncounterId,
                                                                         pokemon.SpawnPointId).ConfigureAwait(false);

                    if (encounter.Result == IncenseEncounterResponse.Types.Result.IncenseEncounterSuccess &&
                        session.LogicSettings.CatchPokemon)
                    {
                        //await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon).ConfigureAwait(false);
                        await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon,
                                                       currentFortData : null, sessionAllowTransfer : true).ConfigureAwait(false);
                    }
                    else if (encounter.Result == IncenseEncounterResponse.Types.Result.PokemonInventoryFull)
                    {
                        if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon)
                        {
                            session.EventDispatcher.Send(new WarnEvent
                            {
                                Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring)
                            });
                            if (session.LogicSettings.TransferDuplicatePokemon)
                            {
                                await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                            }
                            if (session.LogicSettings.TransferWeakPokemon)
                            {
                                await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                            }
                            if (EvolvePokemonTask.IsActivated(session))
                            {
                                await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            session.EventDispatcher.Send(new WarnEvent
                            {
                                Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                            });
                        }
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message =
                                session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Result)
                        });
                    }
                }
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken,
                                         PokemonId priority = PokemonId.Missingno, bool sessionAllowTransfer = true)
        {
            var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();

            manager.ThrowIfSwitchAccountRequested();
            cancellationToken.ThrowIfCancellationRequested();

            if (!session.LogicSettings.CatchPokemon)
            {
                return;
            }

            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);

            if (session.SaveBallForByPassCatchFlee && totalBalls < 130)
            {
                return;
            }

            if (session.Stats.CatchThresholdExceeds(session))
            {
                if (manager.AllowMultipleBot() &&
                    session.LogicSettings.MultipleBotConfig.SwitchOnCatchLimit &&
                    manager.AllowSwitch()
                    )
                {
                    throw new ActiveSwitchByRuleException()
                          {
                              MatchedRule  = SwitchRules.CatchLimitReached,
                              ReachedValue = session.LogicSettings.CatchPokemonLimit
                          };
                }

                return;
            }

            Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForPokemon), LogLevel.Debug);

            var nearbyPokemons = await GetNearbyPokemons(session).ConfigureAwait(false);

            Logger.Write($"There are {nearbyPokemons.Count()} pokemon nearby.", LogLevel.Debug);

            if (nearbyPokemons == null)
            {
                return;
            }

            var priorityPokemon = nearbyPokemons.Where(p => p.PokemonId == priority).FirstOrDefault();
            var pokemons        = nearbyPokemons.Where(p => p.PokemonId != priority).ToList();

            //add pokemons to map
            OnPokemonEncounterEvent(pokemons.ToList());

            EncounterResponse encounter = null;

            //if that is snipe pokemon and inventories if full, execute transfer to get more room for pokemon
            if (priorityPokemon != null)
            {
                pokemons.Insert(0, priorityPokemon);
                await LocationUtils.UpdatePlayerLocationWithAltitude(session,
                                                                     new GeoCoordinate(priorityPokemon.Latitude, priorityPokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed.

                encounter = await session.Client.Encounter
                            .EncounterPokemon(priorityPokemon.EncounterId, priorityPokemon.SpawnPointId).ConfigureAwait(false);

                if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull)
                {
                    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);
                    }
                }
            }

            var allitems = await session.Inventory.GetItems().ConfigureAwait(false);

            var pokeBallsCount   = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemPokeBall)?.Count;
            var greatBallsCount  = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemGreatBall)?.Count;
            var ultraBallsCount  = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemUltraBall)?.Count;
            var masterBallsCount = allitems.FirstOrDefault(i => i.ItemId == ItemId.ItemMasterBall)?.Count;

            masterBallsCount = masterBallsCount ?? 0; //return null ATM. need this code to logic check work
            var PokeBalls = pokeBallsCount + greatBallsCount + ultraBallsCount + masterBallsCount;

            if (0 < pokemons.Count && PokeBalls >= session.LogicSettings.PokeballsToKeepForSnipe) // Don't display if not enough Pokeballs - TheWizrad1328
            {
                Logger.Write($"Catching {pokemons.Count} Pokemon Nearby...", LogLevel.Info);
            }

            foreach (var pokemon in pokemons)
            {
                await MSniperServiceTask.Execute(session, cancellationToken).ConfigureAwait(false);

                /*
                 * if (LocationUtils.CalculateDistanceInMeters(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude) > session.Client.GlobalSettings.MapSettings.EncounterRangeMeters)
                 * {
                 *  Logger.Debug($"THIS POKEMON IS TOO FAR, {pokemon.Latitude}, {pokemon.Longitude}");
                 *  continue;
                 * }
                 */

                cancellationToken.ThrowIfCancellationRequested();
                TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();

                if (session.Cache.GetCacheItem(CatchPokemonTask.GetEncounterCacheKey(pokemon.EncounterId)) != null)
                {
                    continue; //this pokemon has been skipped because not meet with catch criteria before.
                }

                if (PokeBalls < session.LogicSettings.PokeballsToKeepForSnipe && session.CatchBlockTime < DateTime.Now)
                {
                    session.CatchBlockTime = DateTime.Now.AddMinutes(session.LogicSettings.OutOfBallCatchBlockTime);
                    Logger.Write(session.Translation.GetTranslation(TranslationString.CatchPokemonDisable,
                                                                    session.LogicSettings.OutOfBallCatchBlockTime, session.LogicSettings.PokeballsToKeepForSnipe));
                    return;
                }

                if (session.CatchBlockTime > DateTime.Now)
                {
                    return;
                }

                if ((session.LogicSettings.UsePokemonToCatchLocallyListOnly &&
                     !session.LogicSettings.PokemonToCatchLocally.Pokemon.Contains(pokemon.PokemonId)) ||
                    (session.LogicSettings.UsePokemonToNotCatchFilter &&
                     session.LogicSettings.PokemonsNotToCatch.Contains(pokemon.PokemonId)))
                {
                    Logger.Write(session.Translation.GetTranslation(TranslationString.PokemonSkipped,
                                                                    session.Translation.GetPokemonTranslation(pokemon.PokemonId)));
                    continue;
                }

                /*
                 * var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                 *  session.Client.CurrentLongitude, pokemon.Latitude, pokemon.Longitude);
                 * await Task.Delay(distance > 100 ? 500 : 100, cancellationToken).ConfigureAwait(false);
                 */

                //to avoid duplicated encounter when snipe priority pokemon

                if (encounter == null || encounter.Status != EncounterResponse.Types.Status.EncounterSuccess)
                {
                    await LocationUtils.UpdatePlayerLocationWithAltitude(session,
                                                                         new GeoCoordinate(pokemon.Latitude, pokemon.Longitude, session.Client.CurrentAltitude), 0).ConfigureAwait(false); // Set speed to 0 for random speed.

                    encounter =
                        await session.Client.Encounter.EncounterPokemon(pokemon.EncounterId, pokemon.SpawnPointId).ConfigureAwait(false);
                }

                if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess &&
                    session.LogicSettings.CatchPokemon)
                {
                    // Catch the Pokemon
                    await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon,
                                                   currentFortData : null, sessionAllowTransfer : sessionAllowTransfer).ConfigureAwait(false);
                }
                else if (encounter.Status == EncounterResponse.Types.Status.PokemonInventoryFull)
                {
                    if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring)
                        });
                        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);
                        }
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                        });
                    }
                }
                else
                {
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.EncounterProblem, encounter.Status)
                    });
                }
                encounter = null;
                // If pokemon is not last pokemon in list, create delay between catches, else keep moving.
                if (!Equals(pokemons.ElementAtOrDefault(pokemons.Count() - 1), pokemon))
                {
                    await Task.Delay(session.LogicSettings.DelayBetweenPokemonCatch, cancellationToken).ConfigureAwait(false);
                }
            }
        }
Exemple #4
0
        public static async Task Execute(ISession session, CancellationToken cancellationToken)
        {
            if (!CheckSnipeConditions(session))
            {
                return;
            }

            inProgress = true;
            double originalLatitude  = session.Client.CurrentLatitude;
            double originalLongitude = session.Client.CurrentLongitude;

            session.KnownLatitudeBeforeSnipe  = originalLatitude;
            session.KnownLongitudeBeforeSnipe = originalLongitude;

            //Logger.Write($"DEBUG : Location before snipe : {originalLatitude},{originalLongitude}");

            var pth = Path.Combine(Directory.GetCurrentDirectory(), "SnipeMS.json");

            try
            {
                if (OutOffBallBlock > DateTime.Now || (
                        File.Exists(pth) && autoSnipePokemons.Count == 0 && manualSnipePokemons.Count == 0 &&
                        pokedexSnipePokemons.Count == 0))
                {
                    return;
                }

                if (autoSnipePokemons.Count > 0 && !(await CheckPokeballsToSnipe(
                                                         session.LogicSettings.MinPokeballsToSnipe + 1, session, cancellationToken).ConfigureAwait(false)))
                {
                    session.EventDispatcher.Send(new WarnEvent()
                    {
                        Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled,
                                                                     session.LogicSettings.SnipePauseOnOutOfBallTime)
                    });

                    OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime);
                    return;
                }
                List <MSniperInfo2> mSniperLocation2 = new List <MSniperInfo2>();
                if (File.Exists(pth))
                {
                    var sr  = new StreamReader(pth, Encoding.UTF8);
                    var jsn = sr.ReadToEnd();
                    sr.Close();

                    mSniperLocation2 = JsonConvert.DeserializeObject <List <MSniperInfo2> >(jsn);
                    File.Delete(pth);
                    if (mSniperLocation2 == null)
                    {
                        mSniperLocation2 = new List <MSniperInfo2>();
                    }
                }
                using (await locker.LockAsync().ConfigureAwait(false))
                {
                    if (pokedexSnipePokemons.Count > 0)
                    {
                        mSniperLocation2.Add(pokedexSnipePokemons.OrderByDescending(x => x.PokemonId).FirstOrDefault());
                        pokedexSnipePokemons.Clear();
                    }
                    if (manualSnipePokemons.Count > 0)
                    {
                        mSniperLocation2.AddRange(manualSnipePokemons);
                        manualSnipePokemons.Clear();
                    }
                    else
                    {
                        autoSnipePokemons.RemoveAll(x => x.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now);
                        // || ( x.ExpiredTime >0 && x.ExpiredTime < DateTime.Now.ToUnixTime()));
                        autoSnipePokemons.OrderBy(x => x.Priority)
                        .ThenByDescending(x => PokemonGradeHelper.GetPokemonGrade((PokemonId)x.PokemonId))
                        .ThenByDescending(x => x.Iv)
                        .ThenByDescending(x => x.PokemonId)
                        .ThenByDescending(x => x.AddedTime);

                        var batch = autoSnipePokemons.Take(session.LogicSettings.AutoSnipeBatchSize);
                        if (batch != null && batch.Count() > 0)
                        {
                            mSniperLocation2.AddRange(batch);
                            autoSnipePokemons.RemoveAll(x => batch.Contains(x));
                        }
                    }
                }
                foreach (var location in mSniperLocation2)
                {
                    if (session.Stats.CatchThresholdExceeds(session) || isBlocking)
                    {
                        break;
                    }
                    using (await locker.LockAsync().ConfigureAwait(false))
                    {
                        if (location.EncounterId > 0 && expiredCache.Get(location.EncounterId.ToString()) != null)
                        {
                            continue;
                        }

                        if (pokedexSnipePokemons.Count > 0 || manualSnipePokemons.Count > 0)
                        {
                            break;
                            //should return item back to snipe list
                        }
                    }
                    session.EventDispatcher.Send(new SnipePokemonStarted(location));

                    if (location.EncounterId > 0 && session.Cache[CatchPokemonTask.GetEncounterCacheKey(location.EncounterId)] != null)
                    {
                        continue;
                    }

                    if (!(await CheckPokeballsToSnipe(session.LogicSettings.MinPokeballsWhileSnipe + 1, session, cancellationToken).ConfigureAwait(false)))
                    {
                        session.EventDispatcher.Send(new WarnEvent()
                        {
                            Message = session.Translation.GetTranslation(TranslationString.AutoSnipeDisabled)
                        });

                        OutOffBallBlock = DateTime.Now.AddMinutes(session.LogicSettings.SnipePauseOnOutOfBallTime);
                        break;
                    }

                    if (location.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now)
                    {
                        continue;
                    }

                    //If bot already catch the same pokemon, and very close this location.
                    if (session.Cache.Get(CatchPokemonTask.GetUsernameGeoLocationCacheKey(session.Settings.Username, (PokemonId)location.PokemonId, location.Latitude, location.Longitude)) != null)
                    {
                        continue;
                    }

                    session.Cache.Add(CatchPokemonTask.GetEncounterCacheKey(location.EncounterId), true, DateTime.Now.AddMinutes(15));

                    cancellationToken.ThrowIfCancellationRequested();
                    TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
                    session.EventDispatcher.Send(new SnipeScanEvent
                    {
                        Bounds    = new Location(location.Latitude, location.Longitude),
                        PokemonId = (PokemonId)location.PokemonId,
                        Source    = "InternalSnipe",
                        Iv        = location.Iv
                    });

                    session.Stats.IsSnipping = true;
                    var result = await CatchWithSnipe(session, location, cancellationToken).ConfigureAwait(false);

                    if (result)
                    {
                        snipeFailedCount = 0;
                    }
                    else
                    {
                        snipeFailedCount++;
                        if (snipeFailedCount >= 3)
                        {
                            break;                        //maybe softban, stop snipe wait until verify it not been
                        }
                    }
                    //await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
                    session.Stats.LastSnipeTime = DateTime.Now;
                    session.Stats.SnipeCount++;
                    waitNextPokestop = true;
                }
            }
            catch (ActiveSwitchByPokemonException ex) { throw ex; }
            catch (ActiveSwitchAccountManualException ex)
            {
                throw ex;
            }
            catch (ActiveSwitchByRuleException ex)
            {
                throw ex;
            }
            catch (CaptchaException cex)
            {
                throw cex;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && ex.InnerException is CaptchaException)
                {
                    throw ex.InnerException;
                }

                File.Delete(pth);
                var ee = new ErrorEvent {
                    Message = ex.Message
                };
                if (ex.InnerException != null)
                {
                    ee.Message = ex.InnerException.Message;
                }
                session.EventDispatcher.Send(ee);
            }
            finally
            {
                inProgress = false;
                session.Stats.IsSnipping = false;
                //Logger.Write($"DEBUG : Back to home location: {originalLatitude},{originalLongitude}");

                await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(originalLatitude, originalLongitude), 0).ConfigureAwait(false);
            }
        }
Exemple #5
0
        public static async Task <bool> AddSnipeItem(ISession session, MSniperInfo2 item, bool byPassValidation = false)
        {
            if (isBlocking)
            {
                return(false);
            }
            //this pokemon has been recorded as expires
            if (item.EncounterId > 0 && expiredCache.Get(item.EncounterId.ToString()) != null)
            {
                return(false);
            }

            //fake & annoy data
            if (Math.Abs(item.Latitude) > 90 || Math.Abs(item.Longitude) > 180 || item.Iv > 100)
            {
                return(false);
            }

            using (await locker.LockAsync().ConfigureAwait(false))
            {
                Func <MSniperInfo2, bool> checkExisting = (MSniperInfo2 x) =>
                {
                    return((x.EncounterId > 0 && x.EncounterId == item.EncounterId) ||
                           (x.EncounterId == 0 && Math.Round(x.Latitude, 6) == Math.Round(item.Latitude, 6) &&
                            Math.Round(x.Longitude, 6) == Math.Round(item.Longitude, 6) &&
                            x.PokemonId == item.PokemonId));
                };

                //remove existing item that
                autoSnipePokemons.RemoveAll(x => checkExisting(x));
                pokedexSnipePokemons.RemoveAll(x => checkExisting(x));
                manualSnipePokemons.RemoveAll(x => checkExisting(x));
            }

            if (!byPassValidation &&
                session.LogicSettings.AutoSnipeMaxDistance > 0 &&
                LocationUtils.CalculateDistanceInMeters(session.Settings.DefaultLatitude, session.Settings.DefaultLongitude, item.Latitude, item.Longitude) > session.LogicSettings.AutoSnipeMaxDistance * 1000)
            {
                return(false);
            }

            using (await locker.LockAsync().ConfigureAwait(false))
            {
                item.AddedTime = DateTime.Now;
                //just keep pokemon in last 2 min
                autoSnipePokemons.RemoveAll(x => x.AddedTime.AddSeconds(SNIPE_SAFE_TIME) < DateTime.Now);
                pokedexSnipePokemons.RemoveAll(x => x.AddedTime.AddMinutes(SNIPE_SAFE_TIME) < DateTime.Now);
            }
            if (OutOffBallBlock > DateTime.Now ||
                autoSnipePokemons.Exists(x => x.EncounterId == item.EncounterId && item.EncounterId > 0) ||
                (item.EncounterId > 0 && session.Cache[CatchPokemonTask.GetEncounterCacheKey(item.EncounterId)] != null))
            {
                return(false);
            }

            item.Iv = Math.Round(item.Iv, 2);
            if (session.LogicSettings.SnipePokemonNotInPokedex)
            {
                //sometime the API return pokedex not correct, we need cahe this list, need lean everyetime peopellogi
                var pokedex = (await session.Inventory.GetPokeDexItems().ConfigureAwait(false)).Select(x => x.InventoryItemData?.PokedexEntry?.PokemonId).Where(x => x != null).ToList();
                var update  = pokedex.Where(x => !pokedexList.Contains(x.Value)).ToList();

                pokedexList.AddRange(update.Select(x => x.Value));

                //Logger.Debug($"Pokedex Entry : {pokedexList.Count()}");

                if (pokedexList.Count > 0 &&
                    !pokedexList.Exists(x => x == (PokemonId)item.PokemonId) &&
                    !pokedexSnipePokemons.Exists(p => p.PokemonId == item.PokemonId) &&
                    (!session.LogicSettings.AutosnipeVerifiedOnly ||
                     (session.LogicSettings.AutosnipeVerifiedOnly && item.IsVerified())))
                {
                    session.EventDispatcher.Send(new WarnEvent()
                    {
                        Message = session.Translation.GetTranslation(TranslationString.SnipePokemonNotInPokedex,
                                                                     session.Translation.GetPokemonTranslation((PokemonId)item.PokemonId))
                    });
                    item.Priority = 0;
                    pokedexSnipePokemons.Add(item); //Add as hight priority snipe entry
                    return(true);
                }
            }
            var         pokemonId = (PokemonId)item.PokemonId;
            SnipeFilter filter    = session.LogicSettings.PokemonSnipeFilters.GetFilter <SnipeFilter>(pokemonId);

            using (await locker.LockAsync().ConfigureAwait(false))
            {
                if (byPassValidation)
                {
                    item.Priority = -1;
                    manualSnipePokemons.Add(item);

                    Logger.Write($"(MANUAL SNIPER) Pokemon added |  {(PokemonId)item.PokemonId} [{item.Latitude},{item.Longitude}] IV {item.Iv}%");
                    return(true);
                }

                item.Priority = filter.Priority;

                if (filter.VerifiedOnly && item.EncounterId == 0)
                {
                    return(false);
                }

                //check candy
                int candy = await session.Inventory.GetCandyCount(pokemonId).ConfigureAwait(false);

                if (candy < filter.AutoSnipeCandy)
                {
                    autoSnipePokemons.Add(item);
                    return(true);
                }

                if (filter.IsMatch(item.Iv, item.Move1, item.Move2, item.Level, item.EncounterId > 0))
                {
                    autoSnipePokemons.Add(item);
                    return(true);
                }
            }
            return(false);
        }
        public static async Task Execute(ISession session, FortData currentFortData,
                                         CancellationToken cancellationToken)
        {
            TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested();
            cancellationToken.ThrowIfCancellationRequested();
            if (!session.LogicSettings.CatchPokemon ||
                session.CatchBlockTime > DateTime.Now)
            {
                return;
            }

            if (session.KnownLongitudeBeforeSnipe != 0 && session.KnownLatitudeBeforeSnipe != 0 &&
                LocationUtils.CalculateDistanceInMeters(session.KnownLatitudeBeforeSnipe,
                                                        session.KnownLongitudeBeforeSnipe,
                                                        session.Client.CurrentLatitude,
                                                        session.Client.CurrentLongitude) > 1000)
            {
                Logger.Write($"ERROR - Bot is stuck at snipe location({session.Client.CurrentLatitude},{session.Client.CurrentLongitude}). Teleport him back home - if you see this message please PM samuraitruong on Discord");

                session.Client.Player.SetCoordinates(session.KnownLatitudeBeforeSnipe, session.KnownLongitudeBeforeSnipe, session.Client.CurrentAltitude);
                return;
            }


            Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug);

            var fortId = currentFortData.Id;

            var pokemonId = currentFortData.LureInfo.ActivePokemonId;

            if ((session.LogicSettings.UsePokemonToCatchLocallyListOnly &&
                 !session.LogicSettings.PokemonToCatchLocally.Pokemon.Contains(pokemonId)) ||
                (session.LogicSettings.UsePokemonToNotCatchFilter &&
                 session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId)))
            {
                session.EventDispatcher.Send(new NoticeEvent
                {
                    Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId)
                });
            }
            else
            {
                var encounterId = currentFortData.LureInfo.EncounterId;
                if (session.Cache.Get(CatchPokemonTask.GetEncounterCacheKey(currentFortData.LureInfo.EncounterId)) != null)
                {
                    return; //pokemon been ignore before
                }
                var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId).ConfigureAwait(false);

                if (encounter.Result == DiskEncounterResponse.Types.Result.Success &&
                    session.LogicSettings.CatchPokemon)
                {
                    var pokemon = new MapPokemon
                    {
                        EncounterId           = encounterId,
                        ExpirationTimestampMs = currentFortData.LureInfo.LureExpiresTimestampMs,
                        Latitude     = currentFortData.Latitude,
                        Longitude    = currentFortData.Longitude,
                        PokemonId    = currentFortData.LureInfo.ActivePokemonId,
                        SpawnPointId = currentFortData.Id
                    };

                    //add delegate function
                    OnPokemonEncounterEvent(new List <MapPokemon> {
                        pokemon
                    });

                    // Catch the Pokemon
                    await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon,
                                                   currentFortData, sessionAllowTransfer : true).ConfigureAwait(false);
                }
                else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull)
                {
                    if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon)
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring)
                        });
                        if (session.LogicSettings.TransferDuplicatePokemon)
                        {
                            await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                        }
                        if (session.LogicSettings.TransferWeakPokemon)
                        {
                            await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                        }
                        if (EvolvePokemonTask.IsActivated(session))
                        {
                            await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        session.EventDispatcher.Send(new WarnEvent
                        {
                            Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually)
                        });
                    }
                }
                else
                {
                    if (encounter.Result.ToString().Contains("NotAvailable"))
                    {
                        return;
                    }
                    session.EventDispatcher.Send(new WarnEvent
                    {
                        Message =
                            session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon,
                                                               encounter.Result)
                    });
                }
            }
        }