Exemple #1
0
        private static bool IsNotMetWithCatchCriteria(ISession session, PokemonData encounteredPokemon,
                                                      double pokemonIv, double lv, int?cp)
        {
            if (session.LogicSettings.UsePokemonToNotCatchFilter &&
                session.LogicSettings.PokemonsNotToCatch.Contains(encounteredPokemon.PokemonId))
            {
                return(true);
            }
            if (session.LogicSettings.UseTransferFilterToCatch &&
                session.LogicSettings.PokemonsTransferFilter.ContainsKey(encounteredPokemon.PokemonId))
            {
                var filter = session.LogicSettings.PokemonsTransferFilter[encounteredPokemon.PokemonId];
                if (filter != null && filter.CatchOnlyPokemonMeetTransferCriteria)
                {
                    var move1 = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString();
                    var move2 = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString();

                    if (filter.MovesOperator == "or" &&
                        (filter.Moves.Count > 0 &&
                         filter.Moves.Any(x => x[0] == encounteredPokemon.Move1 && x[1] == encounteredPokemon.Move2)))
                    {
                        return(true); //he has the moves we don't meed.
                    }

                    if (filter.KeepMinOperator == "and" &&
                        ((cp.HasValue && cp.Value < filter.KeepMinCp) ||
                         pokemonIv < filter.KeepMinIvPercentage ||
                         (filter.UseKeepMinLvl && lv < filter.KeepMinLvl)) &&
                        (
                            filter.Moves.Count == 0 ||
                            filter.Moves.Any(x => x[0] == encounteredPokemon.Move1 && x[1] == encounteredPokemon.Move2)
                        ))
                    {
                        return(true); //not catch pokemon
                    }

                    if (filter.KeepMinOperator == "or" && ((!cp.HasValue || cp < filter.KeepMinCp) &&
                                                           pokemonIv < filter.KeepMinIvPercentage &&
                                                           (!filter.UseKeepMinLvl || lv < filter.KeepMinLvl)) &&
                        (
                            filter.Moves.Count == 0 ||
                            filter.Moves.Any(x => x[0] == encounteredPokemon.Move1 && x[1] == encounteredPokemon.Move2)
                        ))
                    {
                        return(true); //not catch pokemon
                    }
                }
            }
            return(false);
        }
        public static async Task Execute(ISession session)
        {
            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var highestsPokemonCpForUpgrade = await session.Inventory.GetHighestsCp(50);

            var highestsPokemonIvForUpgrade = await session.Inventory.GetHighestsPerfect(50);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();
            var pokemonPairedWithStatsCpForUpgrade =
                highestsPokemonCpForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();
            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();
            var pokemonPairedWithStatsIvForUpgrade =
                highestsPokemonIvForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            await Task.Delay(500);

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            foreach (var pokemon in pokemonPairedWithStatsIvForUpgrade)
            {
                var dgdfs = pokemon.ToString();

                var tokens   = dgdfs.Split(new[] { "id" }, StringSplitOptions.None);
                var splitone = tokens[1].Split('"');
                var iv       = session.Inventory.GetPerfect(pokemon.Item1);
                if (iv >= session.LogicSettings.UpgradePokemonIvMinimum)
                {
                    PokemonId.Add(ulong.Parse(splitone[2]));
                }
            }
            foreach (var t in pokemonPairedWithStatsCpForUpgrade)
            {
                var dgdfs            = t.ToString();
                var tokens           = dgdfs.Split(new[] { "id" }, StringSplitOptions.None);
                var splitone         = tokens[1].Split('"');
                var tokensSplit      = tokens[1].Split(new[] { "cp" }, StringSplitOptions.None);
                var tokenSplitAgain  = tokensSplit[1].Split(' ');
                var tokenSplitAgain2 = tokenSplitAgain[1].Split(',');
                if (float.Parse(tokenSplitAgain2[0]) >= session.LogicSettings.UpgradePokemonCpMinimum)
                {
                    PokemonIdcp.Add(ulong.Parse(splitone[2]));
                }
            }
            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                Dumper.ClearDumpFile(session, dumpFileName);
                foreach (var pokemon in allPokemonInBag)
                {
                    Dumper.Dump(session,
                                $"NAME: {pokemon.PokemonId.ToString().PadRight(16, ' ')}Lvl: {PokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}",
                                dumpFileName);
                }
            }
            await Task.Delay(500);
        }
        public static async Task Execute(ISession session)
        {
            var myPokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var myPokeSettings = await session.Inventory.GetPokemonSettings();

            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                try
                {
                    Dumper.ClearDumpFile(session, dumpFileName);
                    Dumper.Dump(session,
                                "pokemonid,pokemonlevel,cp,perfection,stamina,staminamax,move1,move2,candy,ownername,origin,heightm,weightkg,individualattack,individualdefense,individualstamina,cpmultiplier,battlesattacked,battlesdefended,creationtimems,numupgrades,additionalcpmultiplier,favorite,nickname",
                                dumpFileName);
                    foreach (var pokemon in allPokemonInBag)
                    {
                        Dumper.Dump(session,
                                    $"{session.Translation.GetPokemonTranslation(pokemon.PokemonId)},{PokemonInfo.GetLevel(pokemon)},{pokemon.Cp},{PokemonInfo.CalculatePokemonPerfection(pokemon)},{pokemon.Stamina},{pokemon.StaminaMax},{pokemon.Move1},{pokemon.Move2},{PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings)},{pokemon.OwnerName},{pokemon.Origin},{pokemon.HeightM},{pokemon.WeightKg},{pokemon.IndividualAttack},{pokemon.IndividualDefense},{pokemon.IndividualStamina},{pokemon.CpMultiplier},{pokemon.BattlesAttacked},{pokemon.BattlesDefended},{pokemon.CreationTimeMs},{pokemon.NumUpgrades},{pokemon.AdditionalCpMultiplier},{pokemon.Favorite},{pokemon.Nickname}",
                                    dumpFileName);
                    }
                }
                catch (IOException)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = $"Could not write {dumpFileName} dump file."
                    });
                }
            }
        }
        public static async Task Execute(ISession session, CancellationToken cancellationToken, dynamic encounter, MapPokemon pokemon,
                                         FortData currentFortData = null, ulong encounterId = 0, bool sessionAllowTransfer = true)
        {
            AmountOfBerries = 0;

            cancellationToken.ThrowIfCancellationRequested();

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

            if (CatchThresholdExceeds(session))
            {
                return;
            }

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

            // Check for pokeballs before proceeding
            var pokeball = await GetBestBall(session, encounter, probability);

            if (pokeball == ItemId.ItemUnknown)
            {
                return;
            }

            //Calculate CP and IV
            var pokemonCp = (encounter is EncounterResponse
                               ? encounter.WildPokemon?.PokemonData?.Cp
                               : encounter.PokemonData?.Cp);
            var pokemonIv = PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);

            // Calculate distance away
            var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude,
                                                                   session.Client.CurrentLongitude,
                                                                   encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Latitude
                    : currentFortData.Latitude,
                                                                   encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.Longitude
                    : currentFortData.Longitude);

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

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

                pokeball = await GetBestBall(session, encounter, probability);

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

                // Determine whether to use berries or not
                if (((session.LogicSettings.UseBerriesOperator.ToLower().Equals("and") &&
                      pokemonIv >= session.LogicSettings.UseBerriesMinIv &&
                      pokemonCp >= session.LogicSettings.UseBerriesMinCp &&
                      probability < session.LogicSettings.UseBerriesBelowCatchProbability) ||
                     (session.LogicSettings.UseBerriesOperator.ToLower().Equals("or") && (
                          pokemonIv >= session.LogicSettings.UseBerriesMinIv ||
                          pokemonCp >= session.LogicSettings.UseBerriesMinCp ||
                          probability < session.LogicSettings.UseBerriesBelowCatchProbability))) &&
                    lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed) // if last throw is a miss, no double berry
                {
                    AmountOfBerries++;
                    if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                    {
                        await UseBerry(session,
                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                       ?pokemon.EncounterId
                                       : encounterId,
                                       encounter is EncounterResponse || encounter is IncenseEncounterResponse
                                       ?pokemon.SpawnPointId
                                       : currentFortData?.Id);
                    }
                }

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

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

                var lat = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                             ? pokemon.Latitude : currentFortData.Latitude;
                var lng = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                            ? pokemon.Longitude : currentFortData.Longitude;
                var evt = new PokemonCaptureEvent()
                {
                    Status    = caughtPokemonResponse.Status,
                    Latitude  = lat,
                    Longitude = lng
                };

                lastThrow = caughtPokemonResponse.Status; // sets lastThrow status

                if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    var totalExp = 0;

                    foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                    {
                        totalExp += xp;
                    }
                    var profile = await session.Client.Player.GetPlayer();

                    evt.Exp      = totalExp;
                    evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount;
                    evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;

                    var pokemonSettings = await session.Inventory.GetPokemonSettings();

                    var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                    var setting =
                        pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId);
                    var family = pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                    if (family != null)
                    {
                        family.Candy_    += caughtPokemonResponse.CaptureAward.Candy.Sum();
                        evt.FamilyCandies = family.Candy_;
                    }
                    else
                    {
                        evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                    }

                    if (session.LogicSettings.UseCatchLimit)
                    {
                        session.Stats.PokemonTimestamps.Add(DateTime.Now.Ticks);
                        UpdateTimeStampsPokemon?.Invoke();
                        Logger.Write($"(CATCH LIMIT) {session.Stats.PokemonTimestamps.Count}/{session.LogicSettings.CatchPokemonLimit}",
                                     LogLevel.Info, ConsoleColor.Yellow);
                    }
                }

                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 = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.EncounterId
                    : encounterId;
                evt.Move1 = PokemonInfo.GetPokemonMove1(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);
                evt.Move2 = PokemonInfo.GetPokemonMove2(encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData
                    : encounter?.PokemonData);
                evt.Expires      = pokemon?.ExpirationTimestampMs ?? 0;
                evt.SpawnPointId = encounter is EncounterResponse || encounter is IncenseEncounterResponse
                    ? pokemon.SpawnPointId
                    : currentFortData?.Id;
                evt.Level =
                    PokemonInfo.GetLevel(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Cp = encounter is EncounterResponse
                    ? encounter.WildPokemon?.PokemonData?.Cp
                    : encounter?.PokemonData?.Cp ?? 0;
                evt.MaxCp =
                    PokemonInfo.CalculateMaxCp(encounter is EncounterResponse
                        ? encounter.WildPokemon?.PokemonData
                        : encounter?.PokemonData);
                evt.Perfection =
                    Math.Round(
                        PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse
                            ? encounter.WildPokemon?.PokemonData
                            : encounter?.PokemonData));
                evt.Probability =
                    Math.Round(probability * 100, 2);
                evt.Distance = distance;
                evt.Pokeball = pokeball;
                evt.Attempt  = attemptCounter;
                await session.Inventory.RefreshCachedInventory();

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

                evt.Rarity = PokemonGradeHelper.GetPokemonGrade(evt.Id).ToString();
                session.EventDispatcher.Send(evt);

                attemptCounter++;

                DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);

                if (session.LogicSettings.TransferDuplicatePokemonOnCapture && session.LogicSettings.TransferDuplicatePokemon &&
                    sessionAllowTransfer && caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                {
                    if (session.LogicSettings.UseNearActionRandom)
                    {
                        await HumanRandomActionTask.TransferRandom(session, cancellationToken);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                }
            } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                     caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);
        }
Exemple #5
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);
        }
Exemple #6
0
        public async Task <bool> OnCommand(ISession session, string cmd, Action <string> Callback)
        {
            string[] messagetext       = cmd.Split(' ');
            string   answerTextmessage = "";

            if (messagetext[0].ToLower() == Command)
            {
                var times  = 10;
                var sortby = "cp";

                if (messagetext.Length >= 2)
                {
                    sortby = messagetext[1];
                }
                if (messagetext.Length == 3)
                {
                    try
                    {
                        times = Convert.ToInt32(messagetext[2]);
                    }
                    catch (FormatException)
                    {
                        answerTextmessage =
                            session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]");
                    }
                }
                else if (messagetext.Length > 3)
                {
                    answerTextmessage =
                        session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]");
                }

                IEnumerable <PokemonData> topPokemons = null;
                if (sortby.Equals("iv"))
                {
                    topPokemons = await session.Inventory.GetHighestsPerfect(times);
                }
                else if (sortby.Equals("cp"))
                {
                    topPokemons = await session.Inventory.GetHighestsCp(times);
                }
                else
                {
                    answerTextmessage =
                        session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]");
                }

                foreach (var pokemon in topPokemons)
                {
                    answerTextmessage += session.Translation.GetTranslation(TranslationString.ShowPokeSkillTemplate,
                                                                            pokemon.Cp, PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"),
                                                                            session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove1(pokemon)),
                                                                            session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove2(pokemon)),
                                                                            session.Translation.GetPokemonTranslation(pokemon.PokemonId));

                    if (answerTextmessage.Length > 3800)
                    {
                        Callback(answerTextmessage);
                        answerTextmessage = "";
                    }
                }

                Callback(answerTextmessage);
                return(true);
            }
            return(false);
        }
        /// <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)
        {
            // If the encounter is null nothing will work below, so exit now
            if (encounter == null)
            {
                return(true);
            }
            // Exit if user defined max limits reached
            if (session.Stats.CatchThresholdExceeds(session))
            {
                if (session.LogicSettings.AllowMultipleBot &&
                    session.LogicSettings.MultipleBotConfig.SwitchOnCatchLimit)
                {
                    throw new ActiveSwitchByRuleException()
                          {
                              MatchedRule  = SwitchRules.CatchLimitReached,
                              ReachedValue = session.LogicSettings.CatchPokemonLimit
                          };
                }

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

                AmountOfBerries = 0;

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

                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();
                    newdata.EncounterId  = _encounterId.ToString();
                    newdata.Iv           = Math.Round(pokemonIv, 2);
                    newdata.Latitude     = latitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.Longitude    = longitude.ToString("G17", CultureInfo.InvariantCulture);
                    newdata.PokemonId    = (int)(encounteredPokemon?.PokemonId ?? 0);
                    newdata.PokemonName  = encounteredPokemon?.PokemonId.ToString();
                    newdata.SpawnPointId = _spawnPointId;
                    newdata.Move1        = PokemonInfo.GetPokemonMove1(encounteredPokemon).ToString();
                    newdata.Move2        = PokemonInfo.GetPokemonMove2(encounteredPokemon).ToString();
                    newdata.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 =
                    $"{session.Settings.PtcUsername}{session.Settings.GoogleUsername}{Math.Round(encounterEV.Latitude, 6)}{encounterEV.PokemonId}{Math.Round(encounterEV.Longitude, 6)}";
                session.Cache.Add(uniqueCacheKey, encounterEV, DateTime.Now.AddMinutes(15));

                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(_encounterId.ToString(), 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.MaxPokeballsPerPokemon > 0 &&
                         attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon))
                    {
                        break;
                    }

                    pokeball = await GetBestBall(session, encounteredPokemon, probability);

                    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 (((session.LogicSettings.UseBerriesOperator.ToLower().Equals("and") &&
                          pokemonIv >= session.LogicSettings.UseBerriesMinIv &&
                          pokemonCp >= session.LogicSettings.UseBerriesMinCp &&
                          probability < session.LogicSettings.UseBerriesBelowCatchProbability) ||
                         (session.LogicSettings.UseBerriesOperator.ToLower().Equals("or") && (
                              pokemonIv >= session.LogicSettings.UseBerriesMinIv ||
                              pokemonCp >= session.LogicSettings.UseBerriesMinCp ||
                              probability < session.LogicSettings.UseBerriesBelowCatchProbability))) &&
                        // if last throw is a miss, no double berry
                        lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed)
                    {
                        AmountOfBerries++;
                        if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon)
                        {
                            await UseBerry(session, _encounterId, _spawnPointId, cancellationToken);
                        }
                    }

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

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


                    await session.Inventory.UpdateInventoryItem(pokeball, -1);

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

                    lastThrow = caughtPokemonResponse.Status; // sets lastThrow status


                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
                    {
                        var totalExp       = 0;
                        var totalStartDust = caughtPokemonResponse.CaptureAward.Stardust.Sum();
                        if (encounteredPokemon != null)
                        {
                            encounteredPokemon.Id = caughtPokemonResponse.CapturedPokemonId;
                            await session.Inventory.AddPokemonToCache(encounteredPokemon);
                        }
                        foreach (var xp in caughtPokemonResponse.CaptureAward.Xp)
                        {
                            totalExp += xp;
                        }
                        var stardust = session.Inventory.UpdateStartDust(totalStartDust);

                        evt.Exp      = totalExp;
                        evt.Stardust = stardust;
                        evt.UniqueId = caughtPokemonResponse.CapturedPokemonId;

                        var pokemonSettings = await session.Inventory.GetPokemonSettings();

                        var pokemonFamilies = await session.Inventory.GetPokemonFamilies();

                        var setting =
                            pokemonSettings.FirstOrDefault(q => pokemon != null && q.PokemonId == pokemon.PokemonId);
                        var family =
                            pokemonFamilies.FirstOrDefault(q => setting != null && q.FamilyId == setting.FamilyId);

                        if (family != null)
                        {
                            await session.Inventory.UpdateCandy(family, caughtPokemonResponse.CaptureAward.Candy.Sum());

                            family.Candy_    += caughtPokemonResponse.CaptureAward.Candy.Sum();
                            evt.FamilyCandies = family.Candy_;
                        }
                        else
                        {
                            evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum();
                        }

                        if (session.LogicSettings.UseCatchLimit)
                        {
                            session.Stats.AddPokemonTimestamp(DateTime.Now.Ticks);
                            Logger.Write(
                                $"(CATCH LIMIT) {session.Stats.GetNumPokemonsInLast24Hours()}/{session.LogicSettings.CatchPokemonLimit}",
                                LogLevel.Info, ConsoleColor.Yellow);
                        }
                    }

                    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);
                    evt.Perfection   = Math.Round(PokemonInfo.CalculatePokemonPerfection(encounteredPokemon));
                    evt.Probability  = Math.Round(probability * 100, 2);
                    evt.Distance     = distance;
                    evt.Pokeball     = pokeball;
                    evt.Attempt      = attemptCounter;

                    //await session.Inventory.RefreshCachedInventory();

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

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

                    session.EventDispatcher.Send(evt);

                    attemptCounter++;

                    DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0);
                } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed ||
                         caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape);

                if (session.LogicSettings.AllowMultipleBot)
                {
                    if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee)
                    {
                        CatchFleeContinuouslyCount++;
                        if (CatchFleeContinuouslyCount > session.LogicSettings.MultipleBotConfig.CatchFleeCount)
                        {
                            CatchFleeContinuouslyCount = 0;

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

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

                if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings))
                {
                    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);
                    }
                    else
                    {
                        await TransferDuplicatePokemonTask.Execute(session, cancellationToken);
                    }
                }
            }
            return(true);
        }
Exemple #8
0
        public override async Task <bool> OnCommand(ISession session, string cmd, Action <string> callback)
        {
            var commandMatch = Match(cmd, CommandParseRegex);

            if (!commandMatch.Success)
            {
                return(false);
            }

            // Parse count
            int count;

            try
            {
                count = string.IsNullOrEmpty(commandMatch.Groups["count"].Value)
                    ? DefaultCount
                    : Convert.ToInt32(commandMatch.Groups["count"].Value);
            }
            catch (FormatException)
            {
                // Exception should not be thrown ...
                return(false);
            }

            // Parse orderBy
            var orderBy = string.IsNullOrEmpty(commandMatch.Groups["orderBy"].Value)
                ? DefaultOrderBy
                : commandMatch.Groups["orderBy"].Value;

            // Get 'count' top Pokemon and 'orderBy' -> will never be null
            var topPokemon = string.Equals("iv", orderBy)
                ? await session.Inventory.GetHighestsPerfect(count)
                : await session.Inventory.GetHighestsCp(count);

            var topPokemonList = topPokemon as IList <PokemonData> ?? topPokemon.ToList();

            var answerTextmessage = GetMsgHead(session, session.Profile.PlayerData.Username, topPokemonList.Count) + "\r\n\r\n";

            answerTextmessage = topPokemonList.Aggregate(answerTextmessage, (current, pokemon)
                                                         => current + session.Translation.GetTranslation(
                                                             TranslationString.ShowPokeSkillTemplate,
                                                             pokemon.Cp,
                                                             PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"),
                                                             session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove1(pokemon)),
                                                             session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove2(pokemon)),
                                                             session.Translation.GetPokemonTranslation(pokemon.PokemonId)
                                                             )
                                                         );

            callback(answerTextmessage);
            return(true);
        }
Exemple #9
0
        public static async Task Execute(ISession session)
        {
            var myPokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var myPokeSettings = await session.Inventory.GetPokemonSettings();

            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                try
                {
                    Dumper.ClearDumpFile(session, dumpFileName);

                    string[] data =
                    {
                        "pokemonid",
                        "pokemonlevel",
                        "cp",
                        "perfection",
                        "stamina",
                        "staminamax",
                        "move1",
                        "move2",
                        "candy",
                        "ownername",
                        "origin",
                        "heightm",
                        "weightkg",
                        "individualattack",
                        "individualdefense",
                        "individualstamina",
                        "cpmultiplier",
                        "battlesattacked",
                        "battlesdefended",
                        "creationtimems",
                        "numupgrades",
                        "additionalcpmultiplier",
                        "favorite",
                        "nickname"
                    };
                    Dumper.Dump(session, data, dumpFileName);

                    // set culture to OS default
                    CultureInfo prevCulture = Thread.CurrentThread.CurrentCulture;
                    CultureInfo culture     = CultureInfo.CurrentUICulture;
                    Thread.CurrentThread.CurrentCulture = culture;

                    foreach (var pokemon in allPokemonInBag)
                    {
                        string[] pokemonData =
                        {
                            session.Translation.GetPokemonTranslation(pokemon.PokemonId),
                            PokemonInfo.GetLevel(pokemon).ToString(),
                            pokemon.Cp.ToString(),
                            PokemonInfo.CalculatePokemonPerfection(pokemon).ToString(),
                            pokemon.Stamina.ToString(),
                            pokemon.StaminaMax.ToString(),
                            pokemon.Move1.ToString(),
                            pokemon.Move2.ToString(),
                            PokemonInfo.GetCandy(pokemon,                                myPokemonFamilies,myPokeSettings).ToString(),
                            pokemon.OwnerName,
                            pokemon.Origin.ToString(),
                            pokemon.HeightM.ToString(),
                            pokemon.WeightKg.ToString(),
                            pokemon.IndividualAttack.ToString(),
                            pokemon.IndividualDefense.ToString(),
                            pokemon.IndividualStamina.ToString(),
                            pokemon.CpMultiplier.ToString(),
                            pokemon.BattlesAttacked.ToString(),
                            pokemon.BattlesDefended.ToString(),
                            pokemon.CreationTimeMs.ToString(),
                            pokemon.NumUpgrades.ToString(),
                            pokemon.AdditionalCpMultiplier.ToString(),
                            pokemon.Favorite.ToString(),
                            pokemon.Nickname
                        };
                        Dumper.Dump(session, pokemonData, dumpFileName);
                    }

                    // restore culture
                    Thread.CurrentThread.CurrentCulture = prevCulture;
                }
                catch (System.IO.IOException)
                {
                    session.EventDispatcher.Send(new ErrorEvent {
                        Message = $"Could not write {dumpFileName} dump file."
                    });
                }
            }
        }
        public static async Task Execute(ISession session)
        {
            var highestsPokemonCp = await
                                    session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart).ConfigureAwait(false);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(
                        pokemon,
                        PokemonInfo.CalculateMaxCp(pokemon.PokemonId),
                        PokemonInfo.CalculatePokemonPerfection(pokemon),
                        PokemonInfo.GetLevel(pokemon),
                        PokemonInfo.GetPokemonMove1(pokemon),
                        PokemonInfo.GetPokemonMove2(pokemon),
                        PokemonInfo.GetCandy(session, pokemon).Result
                        )
                    )
                .ToList();

            var highestsPokemonPerfect = await
                                         session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart).ConfigureAwait(false);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(
                        pokemon,
                        PokemonInfo.CalculateMaxCp(pokemon.PokemonId),
                        PokemonInfo.CalculatePokemonPerfection(pokemon),
                        PokemonInfo.GetLevel(pokemon),
                        PokemonInfo.GetPokemonMove1(pokemon),
                        PokemonInfo.GetPokemonMove2(pokemon),
                        PokemonInfo.GetCandy(session, pokemon).Result
                        )
                    )
                .ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000).ConfigureAwait(false)
                : await session.Inventory.GetHighestsCp(1000).ConfigureAwait(false);

            if (session.LogicSettings.DumpPokemonStats)
            {
                _MultiAccountManager = new MultiAccountManager();
                var    account      = _MultiAccountManager.GetCurrentAccount();
                string dumpFileName = account.Nickname; // "-PokeBagStats";

                //If user dump file exists then cancel file dump
                if (File.Exists(Path.Combine(Path.Combine(session.LogicSettings.ProfilePath, "Dumps"), $"{dumpFileName}-NecroBot2 DumpFile.csv")))
                {
                    return;
                }

                try
                {
                    Dumper.ClearDumpFile(session, dumpFileName);

                    string[] data =
                    {
                        "Pokemon",
                        "Candies",
                        "Slashed",
                        "Nickname",
                        "Level",
                        "CP",
                        "IV",
                        "Power Ups",
                        "Favorite",
                        "Stamina",
                        "Stamina Max",
                        "Move1",
                        "Move2",
                        "Owner Name",
                        "Origin",
                        "Height(M)",
                        "Weight(KG)",
                        "Attack",
                        "Defense",
                        "Stamina",
                        "CP Multi",
                        "Gyms Attacked",
                        "Gyms Defended",
                        "Creationtimems",
                        "Add CP Multi"
                    };
                    Dumper.Dump(session, data, dumpFileName);

                    // set culture to OS default
                    CultureInfo prevCulture = Thread.CurrentThread.CurrentCulture;
                    CultureInfo culture     = CultureInfo.CurrentUICulture;
                    Thread.CurrentThread.CurrentCulture = culture;

                    foreach (var pokemon in allPokemonInBag)
                    {
                        string[] pokemonData =
                        {
                            session.Translation.GetPokemonTranslation(pokemon.PokemonId).Replace(' ', '_'),
                            session.Inventory.GetCandyCount(pokemon.PokemonId).ToString(),            // PokemonInfo.GetCandy(session, pokemon.PokemonId).ToString(),
                            pokemon.IsBad.ToString(),
                            pokemon.Nickname.Replace(' ',                                             '_'),
                            PokemonInfo.GetLevel(pokemon).ToString(),
                            pokemon.Cp.ToString(),
                            PokemonInfo.CalculatePokemonPerfection(pokemon).ToString(),
                            pokemon.NumUpgrades.ToString(),
                            pokemon.Favorite.ToString(),
                            pokemon.Stamina.ToString(),
                            pokemon.StaminaMax.ToString(),
                            pokemon.Move1.ToString(),
                            pokemon.Move2.ToString(),
                            pokemon.OwnerName,
                            pokemon.Origin.ToString(),
                            pokemon.HeightM.ToString(),
                            pokemon.WeightKg.ToString(),
                            pokemon.IndividualAttack.ToString(),
                            pokemon.IndividualDefense.ToString(),
                            pokemon.IndividualStamina.ToString(),
                            pokemon.CpMultiplier.ToString(),
                            pokemon.BattlesAttacked.ToString(),
                            pokemon.BattlesDefended.ToString(),
                            pokemon.CreationTimeMs.ToString(),
                            pokemon.AdditionalCpMultiplier.ToString()
                        };
                        Dumper.Dump(session, pokemonData, dumpFileName);
                    }

                    // restore culture
                    Thread.CurrentThread.CurrentCulture = prevCulture;
                }
                catch (IOException)
                {
                    session.EventDispatcher.Send(
                        new ErrorEvent {
                        Message = $"Could not write {dumpFileName} dump file."
                    }
                        );
                }
            }
        }
Exemple #11
0
        public static async Task Execute(ISession session)
        {
            var myPokemonFamilies = await session.Inventory.GetPokemonFamilies();

            var myPokeSettings = await session.Inventory.GetPokemonSettings();

            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var highestsPokemonCpForUpgrade = await session.Inventory.GetHighestsCp(50);

            var highestsPokemonIvForUpgrade = await session.Inventory.GetHighestsPerfect(50);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();
            var pokemonPairedWithStatsCpForUpgrade =
                highestsPokemonCpForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();
            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings))).ToList();
            var pokemonPairedWithStatsIvForUpgrade =
                highestsPokemonIvForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });

            await Task.Delay(500);

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            foreach (var pokemon in pokemonPairedWithStatsIvForUpgrade)
            {
                var dgdfs = pokemon.ToString();

                var tokens   = dgdfs.Split(new[] { "id" }, StringSplitOptions.None);
                var splitone = tokens[1].Split('"');
                var iv       = session.Inventory.GetPerfect(pokemon.Item1);
                if (iv >= session.LogicSettings.UpgradePokemonIvMinimum)
                {
                    PokemonId.Add(ulong.Parse(splitone[2]));
                }
            }
            foreach (var t in pokemonPairedWithStatsCpForUpgrade)
            {
                var dgdfs            = t.ToString();
                var tokens           = dgdfs.Split(new[] { "id" }, StringSplitOptions.None);
                var splitone         = tokens[1].Split('"');
                var tokensSplit      = tokens[1].Split(new[] { "cp" }, StringSplitOptions.None);
                var tokenSplitAgain  = tokensSplit[1].Split(' ');
                var tokenSplitAgain2 = tokenSplitAgain[1].Split(',');
                if (float.Parse(tokenSplitAgain2[0]) >= session.LogicSettings.UpgradePokemonCpMinimum)
                {
                    PokemonIdcp.Add(ulong.Parse(splitone[2]));
                }
            }
            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                Dumper.ClearDumpFile(session, dumpFileName);
                Dumper.Dump(session, "pokemonid,pokemonlevel,cp,perfection,stamina,staminamax,move1,move2,candy,ownername,origin,heightm,weightkg,individualattack,individualdefense,individualstamina,cpmultiplier,battlesattacked,battlesdefended,creationtimems,numupgrades,additionalcpmultiplier,favorite,nickname", dumpFileName);
                foreach (var pokemon in allPokemonInBag)
                {
                    Dumper.Dump(session,
                                $"{pokemon.PokemonId},{PokemonInfo.GetLevel(pokemon)},{pokemon.Cp},{PokemonInfo.CalculatePokemonPerfection(pokemon)},{pokemon.Stamina},{pokemon.StaminaMax},{pokemon.Move1},{pokemon.Move2},{PokemonInfo.GetCandy(pokemon, myPokemonFamilies, myPokeSettings)},{pokemon.OwnerName},{pokemon.Origin},{pokemon.HeightM},{pokemon.WeightKg},{pokemon.IndividualAttack},{pokemon.IndividualDefense},{pokemon.IndividualStamina},{pokemon.CpMultiplier},{pokemon.BattlesAttacked},{pokemon.BattlesDefended},{pokemon.CreationTimeMs},{pokemon.NumUpgrades},{pokemon.AdditionalCpMultiplier},{pokemon.Favorite},{pokemon.Nickname}",
                                dumpFileName);
                }
            }
            await Task.Delay(500);
        }
Exemple #12
0
        private async void OnTelegramMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage)
            {
                return;
            }

            var answerTextmessage = "";

            if (_session.Profile == null || _session.Inventory == null)
            {
                return;
            }

            var messagetext = message.Text.ToLower().Split(' ');

            if (!_loggedIn && messagetext[0].ToLower().Contains("/login"))
            {
                if (messagetext.Length == 2)
                {
                    if (messagetext[1].ToLower().Contains(_session.LogicSettings.TelegramPassword))
                    {
                        _loggedIn          = true;
                        _lastLoginTime     = DateTime.Now;
                        answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoggedInTelegram);
                        await SendMessage(message.Chat.Id, answerTextmessage);

                        return;
                    }
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoginFailedTelegram);
                    await SendMessage(message.Chat.Id, answerTextmessage);

                    return;
                }
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.NotLoggedInTelegram);
                await SendMessage(message.Chat.Id, answerTextmessage);

                return;
            }
            if (_loggedIn)
            {
                if (_lastLoginTime.AddMinutes(5).Ticks < DateTime.Now.Ticks)
                {
                    _loggedIn          = false;
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.NotLoggedInTelegram);
                    await SendMessage(message.Chat.Id, answerTextmessage);

                    return;
                }
                var remainingMins = _lastLoginTime.AddMinutes(5).Subtract(DateTime.Now).Minutes;
                var remainingSecs = _lastLoginTime.AddMinutes(5).Subtract(DateTime.Now).Seconds;
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.LoginRemainingTime,
                                                                         remainingMins, remainingSecs);
                await SendMessage(message.Chat.Id, answerTextmessage);

                return;
            }

            switch (messagetext[0].ToLower())
            {
            case "/top":
                var times  = 10;
                var sortby = "cp";

                if (messagetext.Length >= 2)
                {
                    sortby = messagetext[1];
                }
                if (messagetext.Length == 3)
                {
                    try
                    {
                        times = Convert.ToInt32(messagetext[2]);
                    }
                    catch (FormatException)
                    {
                        await SendMessage(message.Chat.Id,
                                          _session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]"));

                        break;
                    }
                }
                else if (messagetext.Length > 3)
                {
                    await SendMessage(message.Chat.Id,
                                      _session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]"));

                    break;
                }

                IEnumerable <PokemonData> topPokemons;
                if (sortby.Equals("iv"))
                {
                    topPokemons = await _session.Inventory.GetHighestsPerfect(times);
                }
                else if (sortby.Equals("cp"))
                {
                    topPokemons = await _session.Inventory.GetHighestsCp(times);
                }
                else
                {
                    await SendMessage(message.Chat.Id,
                                      _session.Translation.GetTranslation(TranslationString.UsageHelp, "/top [cp/iv] [amount]"));

                    break;
                }

                foreach (var pokemon in topPokemons)
                {
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.ShowPokeSkillTemplate,
                                                                             pokemon.Cp, PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"),
                                                                             _session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove1(pokemon)),
                                                                             _session.Translation.GetPokemonMovesetTranslation(PokemonInfo.GetPokemonMove2(pokemon)),
                                                                             _session.Translation.GetPokemonTranslation(pokemon.PokemonId));

                    if (answerTextmessage.Length > 3800)
                    {
                        await SendMessage(message.Chat.Id, answerTextmessage);

                        answerTextmessage = "";
                    }
                }
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;

            case "/all":
                var myPokemons = await _session.Inventory.GetPokemons();

                var allMyPokemons = myPokemons.ToList();
                var allPokemons   = await _session.Inventory.GetHighestsCp(allMyPokemons.Count);

                if (messagetext.Length == 1)
                {
                    allPokemons = await _session.Inventory.GetHighestsCp(allMyPokemons.Count);
                }
                else if (messagetext.Length == 2)
                {
                    if (messagetext[1] == "iv")
                    {
                        allPokemons = await _session.Inventory.GetHighestsPerfect(allMyPokemons.Count);
                    }
                    else if (messagetext[1] != "cp")
                    {
                        await SendMessage(message.Chat.Id,
                                          _session.Translation.GetTranslation(TranslationString.UsageHelp, "/all [cp/iv]"));

                        break;
                    }
                }
                else
                {
                    await SendMessage(message.Chat.Id,
                                      _session.Translation.GetTranslation(TranslationString.UsageHelp, "/all [cp/iv]"));

                    break;
                }

                foreach (var pokemon in allPokemons)
                {
                    answerTextmessage += _session.Translation.GetTranslation(TranslationString.ShowPokeTemplate,
                                                                             pokemon.Cp, PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00"),
                                                                             _session.Translation.GetPokemonTranslation(pokemon.PokemonId));

                    if (answerTextmessage.Length > 3800)
                    {
                        await SendMessage(message.Chat.Id, answerTextmessage);

                        answerTextmessage = "";
                    }
                }
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;

            case "/profile":
                var stats = _session.Inventory.GetPlayerStats().Result;
                var stat  = stats.FirstOrDefault();

                var myPokemons2 = await _session.Inventory.GetPokemons();

                if (stat != null)
                {
                    answerTextmessage += _session.Translation.GetTranslation(
                        TranslationString.ProfileStatsTemplateString, stat.Level, _session.Profile.PlayerData.Username,
                        stat.Experience, stat.NextLevelXp, stat.PokemonsCaptured, stat.PokemonDeployed,
                        stat.PokeStopVisits, stat.EggsHatched, stat.Evolutions, stat.UniquePokedexEntries, stat.KmWalked,
                        myPokemons2.ToList().Count, _session.Profile.PlayerData.MaxPokemonStorage);
                }
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;

            case "/pokedex":
                var pokedex     = _session.Inventory.GetPokeDexItems().Result;
                var pokedexSort = pokedex.OrderBy(x => x.InventoryItemData.PokedexEntry.PokemonId);

                answerTextmessage += _session.Translation.GetTranslation(TranslationString.PokedexCatchedTelegram);
                foreach (var pokedexItem in pokedexSort)
                {
                    answerTextmessage +=
                        _session.Translation.GetTranslation(TranslationString.PokedexPokemonCatchedTelegram,
                                                            Convert.ToInt32(pokedexItem.InventoryItemData.PokedexEntry.PokemonId),
                                                            _session.Translation.GetPokemonTranslation(
                                                                pokedexItem.InventoryItemData.PokedexEntry.PokemonId),
                                                            pokedexItem.InventoryItemData.PokedexEntry.TimesCaptured,
                                                            pokedexItem.InventoryItemData.PokedexEntry.TimesEncountered);

                    if (answerTextmessage.Length > 3800)
                    {
                        await SendMessage(message.Chat.Id, answerTextmessage);

                        answerTextmessage = "";
                    }
                }

                var pokemonsToCapture =
                    Enum.GetValues(typeof(PokemonId))
                    .Cast <PokemonId>()
                    .Except(pokedex.Select(x => x.InventoryItemData.PokedexEntry.PokemonId));

                await SendMessage(message.Chat.Id, answerTextmessage);

                answerTextmessage = "";

                answerTextmessage += _session.Translation.GetTranslation(TranslationString.PokedexNeededTelegram);

                foreach (var pokedexItem in pokemonsToCapture)
                {
                    if (Convert.ToInt32(pokedexItem) > 0)
                    {
                        answerTextmessage +=
                            _session.Translation.GetTranslation(TranslationString.PokedexPokemonNeededTelegram,
                                                                Convert.ToInt32(pokedexItem), _session.Translation.GetPokemonTranslation(pokedexItem));

                        if (answerTextmessage.Length > 3800)
                        {
                            await SendMessage(message.Chat.Id, answerTextmessage);

                            answerTextmessage = "";
                        }
                    }
                }
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;

            case "/loc":
                SendLocation(message.Chat.Id, _session.Client.CurrentLatitude, _session.Client.CurrentLongitude);
                break;

            case "/items":
                var inventory = _session.Inventory;
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.CurrentPokeballInv,
                                                                         await inventory.GetItemAmountByType(ItemId.ItemPokeBall),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemGreatBall),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemUltraBall),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemMasterBall));
                answerTextmessage += "\n";
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.CurrentPotionInv,
                                                                         await inventory.GetItemAmountByType(ItemId.ItemPotion),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemSuperPotion),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemHyperPotion),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemMaxPotion));
                answerTextmessage += "\n";
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.CurrentReviveInv,
                                                                         await inventory.GetItemAmountByType(ItemId.ItemRevive),
                                                                         await inventory.GetItemAmountByType(ItemId.ItemMaxRevive));
                answerTextmessage += "\n";
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.CurrentMiscItemInv,
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemRazzBerry) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemBlukBerry) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemNanabBerry) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemWeparBerry) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemPinapBerry),
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemIncenseOrdinary) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemIncenseSpicy) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemIncenseCool) +
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemIncenseFloral),
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemLuckyEgg),
                                                                         await _session.Inventory.GetItemAmountByType(ItemId.ItemTroyDisk));
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;

            case "/status":
                await SendMessage(message.Chat.Id, Console.Title);

                break;

            case "/restart":
                Process.Start(Assembly.GetEntryAssembly().Location);
                await SendMessage(message.Chat.Id, "Restarted Bot. Closing old Instance... BYE!");

                Environment.Exit(-1);
                break;

            case "/exit":
                await SendMessage(message.Chat.Id, "Closing Bot... BYE!");

                Environment.Exit(0);
                break;

            case "/help":
            default:
                answerTextmessage += _session.Translation.GetTranslation(TranslationString.HelpTemplate);
                await SendMessage(message.Chat.Id, answerTextmessage);

                break;
            }
        }
        public static async Task Execute(ISession session)
        {
            var highestsPokemonCp =
                await session.Inventory.GetHighestsCp(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var highestsPokemonCpForUpgrade = await session.Inventory.GetHighestsCp(50);

            var highestsPokemonIvForUpgrade = await session.Inventory.GetHighestsPerfect(50);

            var pokemonPairedWithStatsCp =
                highestsPokemonCp.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),
                                 (PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))) != null ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") : 0)
                                 )).ToList();
            var pokemonPairedWithStatsCpForUpgrade =
                highestsPokemonCpForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),

                                 (PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))) != null ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") : 0)
                                 )).ToList();
            var highestsPokemonPerfect =
                await session.Inventory.GetHighestsPerfect(session.LogicSettings.AmountOfPokemonToDisplayOnStart);

            var pokemonPairedWithStatsIv =
                highestsPokemonPerfect.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),

                                 (PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))) != null ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") : 0)
                                 )).ToList();
            var pokemonPairedWithStatsIvForUpgrade =
                highestsPokemonIvForUpgrade.Select(
                    pokemon =>
                    Tuple.Create(pokemon, PokemonInfo.CalculateMaxCp(pokemon),
                                 PokemonInfo.CalculatePokemonPerfection(pokemon), PokemonInfo.GetLevel(pokemon),
                                 PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon),

                                 (PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))) != null ? PokemonMoveInfo.GetPokemonMoveSet(PokemonMoveInfo.GetMoveSetCombinationIndex(pokemon.PokemonId, PokemonInfo.GetPokemonMove1(pokemon), PokemonInfo.GetPokemonMove2(pokemon))).GetRankVsType("Average") : 0)
                                 )).ToList();

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "CP",
                PokemonList = pokemonPairedWithStatsCp
            });
            if (session.LogicSettings.Teleport)
            {
                await Task.Delay(session.LogicSettings.DelayDisplayPokemon);
            }
            else
            {
                await Task.Delay(500);
            }

            session.EventDispatcher.Send(
                new DisplayHighestsPokemonEvent
            {
                SortedBy    = "IV",
                PokemonList = pokemonPairedWithStatsIv
            });

            var allPokemonInBag = session.LogicSettings.PrioritizeIvOverCp
                ? await session.Inventory.GetHighestsPerfect(1000)
                : await session.Inventory.GetHighestsCp(1000);

            if (session.LogicSettings.DumpPokemonStats)
            {
                const string dumpFileName = "PokeBagStats";
                string       toDumpCSV    = "Name,Level,CP,IV,Move1,Move2\r\n";
                string       toDumpTXT    = "";
                Dumper.ClearDumpFile(session, dumpFileName);
                Dumper.ClearDumpFile(session, dumpFileName, "csv");

                foreach (var pokemon in allPokemonInBag)
                {
                    toDumpTXT += $"NAME: {session.Translation.GetPokemonName(pokemon.PokemonId).PadRight(16, ' ')}Lvl: {PokemonInfo.GetLevel(pokemon).ToString("00")}\t\tCP: {pokemon.Cp.ToString().PadRight(8, ' ')}\t\t IV: {PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%\t\t\tMOVE1: {pokemon.Move1}\t\t\tMOVE2: {pokemon.Move2}\r\n";
                    toDumpCSV += $"{session.Translation.GetPokemonName(pokemon.PokemonId)},{PokemonInfo.GetLevel(pokemon).ToString("00")},{pokemon.Cp},{PokemonInfo.CalculatePokemonPerfection(pokemon).ToString("0.00")}%,{pokemon.Move1},{pokemon.Move2}\r\n";
                }

                Dumper.Dump(session, toDumpTXT, dumpFileName);
                Dumper.Dump(session, toDumpCSV, dumpFileName, "csv");
            }
            if (session.LogicSettings.Teleport)
            {
                await Task.Delay(session.LogicSettings.DelayDisplayPokemon);
            }
            else
            {
                await Task.Delay(500);
            }
        }