public static async Task FortFarmed(FortSearchResponse resp, FortData fortData) { OnFortFarmed(null, new FortFarmedArgs() { SearchResponse = resp, Fort = fortData }); await FortFarmedReset.WaitAsync(); FortFarmedReset.Reset(); }
public static List<FortData> Optimize(FortData[] pokeStops, LatLong latlng, GMapOverlay routeOverlay) { List<FortData> optimizedRoute = new List<FortData>(pokeStops); // NN FortData NN = FindNN(optimizedRoute, latlng.Latitude, latlng.Longitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(0, NN); for (int i = 1; i < pokeStops.Length; i++) { NN = FindNN(optimizedRoute.Skip(i), NN.Latitude, NN.Longitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(i, NN); Visualize(optimizedRoute, routeOverlay); } // 2-Opt bool isOptimized; do { optimizedRoute = Optimize2Opt(optimizedRoute, out isOptimized); Visualize(optimizedRoute, routeOverlay); } while (isOptimized); return optimizedRoute; }
public static async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon) return; Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; if( ( session.LogicSettings.UsePokemonSniperFilterOnly && !session.LogicSettings.PokemonToSnipe.Pokemon.Contains( pokemonId ) ) || ( session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains( pokemonId ) ) ) { session.EventDispatcher.Send(new NoticeEvent { Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId) }); } else { var encounterId = currentFortData.LureInfo.EncounterId; var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId); if (encounter.Result == DiskEncounterResponse.Types.Result.Success && session.LogicSettings.CatchPokemon) { await CatchPokemonTask.Execute(session, cancellationToken, encounter, null, currentFortData, encounterId); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon) { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); if(session.LogicSettings.TransferDuplicatePokemon) await TransferDuplicatePokemonTask.Execute(session, cancellationToken); if(session.LogicSettings.TransferWeakPokemon) await TransferWeakPokemonTask.Execute(session, cancellationToken); } else session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } else { if (encounter.Result.ToString().Contains("NotAvailable")) return; session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, encounter.Result) }); } } }
private async Task RemoveSoftBan(FortData closestPokestop) { var pokestopBooty = await _fort.SearchFort(closestPokestop.Id, closestPokestop.Latitude, closestPokestop.Longitude); while (pokestopBooty.Result == FortSearchResponse.Types.Result.Success) { pokestopBooty = await _fort.SearchFort(closestPokestop.Id, closestPokestop.Latitude, closestPokestop.Longitude); } }
public static string GetGMapLink(FortData pokestop, string text = "this pokestop") { var sb = new StringBuilder(); sb.Append($"<a href=\"{Constant.GoogleMapUrl}"); sb.Append(pokestop.Latitude); sb.Append(","); sb.Append(pokestop.Longitude); sb.Append($"&z=17\">{text}</a>"); return sb.ToString(); }
public async Task Search(FortData pokestop) { var pokestopBooty = await _fort.SearchFort(pokestop.Id, pokestop.Latitude, pokestop.Longitude); if (pokestopBooty.ExperienceAwarded > 0) { logger.Info( $"Pokestop rewarded us with {pokestopBooty.ExperienceAwarded} exp. {pokestopBooty.GemsAwarded} gems. {StringUtils.GetSummedFriendlyNameOfItemAwardList(pokestopBooty.ItemsAwarded)}."); } else { logger.Info("Possible softban detected, attempting to remove."); await RemoveSoftBan(pokestop); } }
public async Task<Func<bool>> EncounterLurePokemon(FortData pokestop) { Func<bool> returnAction = () => false; if (pokestop?.LureInfo != null && pokestop.LureInfo.ActivePokemonId != PokemonId.Missingno) { var encounterId = pokestop.LureInfo.EncounterId; var encounter = await _encounter.EncounterPokemonLure(encounterId, pokestop.Id); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { returnAction = () => _encounter.CatchPokemon(encounterId, pokestop.Id, encounter, encounter.PokemonData.PokemonId).GetAwaiter().GetResult().Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess; } } return returnAction; }
public static List<FortData> Optimize(FortData[] pokeStops, double cLatitude, double cLongitude, GMapOverlay routeOverlay) { List<FortData> optimizedRoute = new List<FortData>(pokeStops); // NN FortData NN = FindNN(optimizedRoute, cLatitude, cLongitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(0, NN); for (int i=1; i<pokeStops.Length; i++) { NN = FindNN(optimizedRoute.Skip(i), NN.Latitude, NN.Longitude); optimizedRoute.Remove(NN); optimizedRoute.Insert(i, NN); } // 2-Opt return optimizedRoute; }
public static async Task Execute(Context ctx, StateMachine machine, FortData currentFortData) { Logger.Write("Looking for lure pokemon..", LogLevel.Debug); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; if (ctx.LogicSettings.UsePokemonToNotCatchFilter && ctx.LogicSettings.PokemonsNotToCatch.Contains(pokemonId)) { machine.Fire(new NoticeEvent {Message = $"Skipped {pokemonId}"}); } else { var encounterId = currentFortData.LureInfo.EncounterId; var encounter = await ctx.Client.Encounter.EncounterLurePokemon(encounterId, fortId); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { await CatchPokemonTask.Execute(ctx, machine, encounter, null, currentFortData, encounterId); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { if (ctx.LogicClient.Settings.TransferDuplicatePokemon) { machine.Fire(new WarnEvent {Message = "PokemonInventory is Full.Transferring pokemons..."}); await TransferDuplicatePokemonTask.Execute(ctx, machine); } else machine.Fire(new WarnEvent { Message = "PokemonInventory is Full.Please Transfer pokemon manually or set TransferDuplicatePokemon to true in settings..." }); } else { if (encounter.Result.ToString().Contains("NotAvailable")) return; machine.Fire(new WarnEvent {Message = $"Encounter problem: Lure Pokemon {encounter.Result}"}); } } }
public static FortData[] pathByNearestNeighbour(FortData[] pokeStops) { for (var i = 1; i < pokeStops.Length - 1; i++) { var closest = i + 1; var cloestDist = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[closest].Latitude, pokeStops[closest].Longitude); for (var j = closest; j < pokeStops.Length; j++) { var initialDist = cloestDist; var newDist = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[j].Latitude, pokeStops[j].Longitude); if (initialDist > newDist) { cloestDist = newDist; closest = j; } } var tmpPok = pokeStops[closest]; pokeStops[closest] = pokeStops[i + 1]; pokeStops[i + 1] = tmpPok; } return pokeStops; }
/// <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) { TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); // 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 && 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()) { 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 = 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)}{(int)encounterEV.PokemonId}{Math.Round(encounterEV.Longitude, 6)}"; 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(_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 = 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 (lastThrow != CatchPokemonResponse.Types.CatchStatus.CatchMissed) { //AmountOfBerries++; //if (AmountOfBerries <= session.LogicSettings.MaxBerriesToUsePerPokemon) await UseBerry(session, encounterEV.PokemonId, _encounterId, _spawnPointId, pokemonIv, pokemonCp.HasValue?pokemonCp.Value : 10000, //unknow CP pokemon, want to use berry encounterEV.Level, probability, 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); 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) { var totalExp = 0; var totalStarDust = caughtPokemonResponse.CaptureAward.Stardust.Sum(); if (encounteredPokemon != null) { encounteredPokemon.Id = caughtPokemonResponse.CapturedPokemonId; } foreach (var xp in caughtPokemonResponse.CaptureAward.Xp) { totalExp += xp; } var stardust = session.Inventory.UpdateStarDust(totalStarDust); evt.Exp = totalExp; evt.Stardust = stardust; evt.UniqueId = caughtPokemonResponse.CapturedPokemonId; evt.Candy = session.Inventory.GetCandyFamily(pokemon.PokemonId); 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)); evt.Probability = Math.Round(probability * 100, 2); evt.Distance = distance; evt.Pokeball = pokeball; evt.Attempt = attemptCounter; //await session.Inventory.RefreshCachedInventory(); evt.BallAmount = 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 && TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch()) { 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, uniqueCacheKey); } 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); }
public async Task CatchEmAll(FortData pokestop) { await CatchEmAll(); await _pokemon.EncounterLurePokemonAndCatch(pokestop); }
public void PushUpdatePokeGym(FortData pokeGym) { HandleUpdatePokeGym(pokeGym); }
public static async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon) { return; } Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; if ((session.LogicSettings.UsePokemonSniperFilterOnly && !session.LogicSettings.PokemonToSnipe.Pokemon.Contains(pokemonId)) || (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId))) { session.EventDispatcher.Send(new NoticeEvent { Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId) }); } else { var encounterId = currentFortData.LureInfo.EncounterId; var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId); if (encounter.Result == DiskEncounterResponse.Types.Result.Success && session.LogicSettings.CatchPokemon) { await CatchPokemonTask.Execute(session, cancellationToken, encounter, null, currentFortData, encounterId); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon) { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken); } } else { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } } else { if (encounter.Result.ToString().Contains("NotAvailable")) { return; } session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, encounter.Result) }); } } }
private async Task<IEnumerable<Task>> CatchBurstPokemon(double x, double y, FortData oldFort) { var actionList = new List<Task>(); await _navigation.TeleportToLocation(x, y); var pokemon = (await _map.GetNearbyPokemonClosestFirst()).DistinctBy(i => i.SpawnPointId).ToList(); foreach (var mapPokemon in pokemon) { if (_settings.UsePokemonToNotCatchFilter && _settings.PokemonsNotToCatch.Contains(mapPokemon.PokemonId)) { continue; } var encounter = await _encounter.EncounterPokemonAsync(mapPokemon); if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { actionList.Add(new Task(async () => { try { await _encounter.CatchPokemon(encounter, mapPokemon); } catch (Exception) { } })); } } return actionList; }
public static async Task Execute(ISession session, CancellationToken cancellationToken, dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { AmountOfBerries = 0; cancellationToken.ThrowIfCancellationRequested(); // If the encounter is null nothing will work below, so exit now if (encounter == null) { 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 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))) { 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); } } //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); Logger.Write($"(Threw ball) {hitTxt} hit. {spinTxt}-ball...", 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); 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 }; 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; 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.TransferDuplicatePokemonOnCapture && session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken); } } evt.CatchType = encounter is EncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; 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); session.EventDispatcher.Send(evt); attemptCounter++; DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 0); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); }
private void InfoObservable_HandleUpdatePokeGym(FortData pokeGym) { Invoke(new MethodInvoker(() => { var bitmap = Properties.MapData.pokegym; var color = Color.Black; switch (pokeGym.OwnedByTeam) { case POGOProtos.Enums.TeamColor.Blue: bitmap = Properties.MapData.pokegym_blue; color = Color.Blue; break; case POGOProtos.Enums.TeamColor.Red: bitmap = Properties.MapData.pokegym_red; color = Color.Red; break; case POGOProtos.Enums.TeamColor.Yellow: bitmap = Properties.MapData.pokegym_yellow; color = Color.Yellow; break; } var str = ""; var pokeGymMaker = new GMarkerGoogle(new PointLatLng(pokeGym.Latitude, pokeGym.Longitude), bitmap); pokeGymMaker.ToolTipText = string.Format("{0}\n{1}, {2}\n{3}\nID: {4}", LocationUtils.FindAddress(pokeGym.Latitude, pokeGym.Longitude), pokeGym.Latitude, pokeGym.Longitude, str, pokeGym.Id); pokeGymMaker.ToolTip.Font = new System.Drawing.Font("Arial", 12, System.Drawing.GraphicsUnit.Pixel); pokeGymMaker.ToolTipMode = MarkerTooltipMode.OnMouseOver; if (_pokeGymsMarks.ContainsKey(pokeGym.Id)) { var markerToDel = _pokeGymsMarks[pokeGym.Id]; if (_pokeGymsOverlay.Markers.Contains(markerToDel)) { _pokeGymsOverlay.Markers.Remove(markerToDel); } _pokeGymsMarks.Remove(pokeGym.Id); } _pokeGymsMarks.Add(pokeGym.Id, pokeGymMaker); _pokeGymsOverlay.Markers.Add(pokeGymMaker); #region Show Guard if (_pokeGymsMarks.ContainsKey(pokeGym.Id + "-Guard")) { var markerToDel = _pokeGymsMarks[pokeGym.Id + "-Guard"]; if (_pokeGymsOverlay.Markers.Contains(markerToDel)) { _pokeGymsOverlay.Markers.Remove(markerToDel); } _pokeGymsMarks.Remove(pokeGym.Id + "-Guard"); } GMarkerGoogle guardPokemonMarker; Bitmap pokebitMap = PokeImgManager.GetPokemonMediumImage(pokeGym.GuardPokemonId); var offsetY = 0; if (pokebitMap != null) { for (int idx = 0; idx < pokebitMap.Width; idx++) { pokebitMap.SetPixel(idx, 0, color); pokebitMap.SetPixel(idx, pokebitMap.Height - 1, color); } for (int idx = 0; idx < pokebitMap.Height; idx++) { pokebitMap.SetPixel(0, idx, color); pokebitMap.SetPixel(pokebitMap.Width - 1, idx, color); } var ImageSize = new System.Drawing.Size(pokebitMap.Width, pokebitMap.Height); guardPokemonMarker = new GMarkerGoogle(new PointLatLng(pokeGym.Latitude, pokeGym.Longitude), pokebitMap); offsetY = 5 - pokebitMap.Height / 2; guardPokemonMarker.Offset = new Point(-bitmap.Width / 2 - 8, offsetY - bitmap.Height); _pokeGymsMarks.Add(pokeGym.Id + "-Guard", guardPokemonMarker); _pokeGymsOverlay.Markers.Add(guardPokemonMarker); } #endregion Show Guard #region Show fighting if (_pokeGymsMarks.ContainsKey(pokeGym.Id + "-Fighting")) { var markerToDel = _pokeGymsMarks[pokeGym.Id + "-Fighting"]; if (_pokeGymsOverlay.Markers.Contains(markerToDel)) { _pokeGymsOverlay.Markers.Remove(markerToDel); } _pokeGymsMarks.Remove(pokeGym.Id + "-Fighting"); } GMarkerGoogle FightingMarker; if (pokeGym.IsInBattle) { for (int idx = 0; idx < pokebitMap.Width; idx++) { pokebitMap.SetPixel(idx, 0, color); pokebitMap.SetPixel(idx, pokebitMap.Height - 1, color); } for (int idx = 0; idx < pokebitMap.Height; idx++) { pokebitMap.SetPixel(0, idx, color); pokebitMap.SetPixel(pokebitMap.Width - 1, idx, color); } FightingMarker = new GMarkerGoogle(new PointLatLng(pokeGym.Latitude, pokeGym.Longitude), GMarkerGoogleType.red_small); if (pokebitMap != null) { FightingMarker.Offset = new Point(-bitmap.Width / 2, 5 - pokebitMap.Height * 2); } _pokeGymsMarks.Add(pokeGym.Id + "-Fighting", FightingMarker); _pokeGymsOverlay.Markers.Add(FightingMarker); } #endregion Show figting })); }
private int calcFitness(ref FortData[] pokeStops, List<int> _chromosome, double walkingSpeedInKilometersPerHour) { if (_chromosome.Count <= 2) return 0; double time = 0.0; double length = 0.0; for (int i = 0; i < _chromosome.Count - 1; ++i) { double distance = DistanceBetween2Coordinates(pokeStops[_chromosome[i]].Latitude, pokeStops[_chromosome[i]].Longitude, pokeStops[_chromosome[i + 1]].Latitude, pokeStops[_chromosome[i + 1]].Longitude); if (distance <= 40) { time += distance / Logic.SpeedDownTo; } else { time += distance * 3.6 / walkingSpeedInKilometersPerHour; } length += distance; } if (time <= 380 || !(time > 0.0)) return 0; if (_client.getSettingHandle().navigation_option == 1) { return Convert.ToInt32((_chromosome.Count * 10000) / time); } else { return Convert.ToInt32(_chromosome.Count * length / time); } }
public async Task EncounterLurePokemonAndCatch(FortData pokestop) { if (pokestop?.LureInfo != null && pokestop.LureInfo.ActivePokemonId != PokemonId.Missingno) { var encounterId = pokestop.LureInfo.EncounterId; var encounter = await _encounter.EncounterPokemonLure(encounterId, pokestop.Id); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { await _encounter.CatchPokemon(encounterId, pokestop.Id, encounter, encounter.PokemonData.PokemonId); } } }
public static async Task Execute(ISession session, CancellationToken cancellationToken, dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { cancellationToken.ThrowIfCancellationRequested(); // If the encounter is null nothing will work below, so exit now if (encounter == null) 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); // 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))) { await UseBerry(session, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.EncounterId : encounterId, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.SpawnPointId : currentFortData?.Id); } // 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 attemptCounter = 1; do { if ((session.LogicSettings.MaxPokeballsPerPokemon > 0 && attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon)) break; pokeball = await GetBestBall(session, encounter, probability, true); 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; } 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); 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 }; 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; 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.TransferDuplicatePokemonOnCapture && session.LogicSettings.TransferDuplicatePokemon) await TransferDuplicatePokemonTask.Execute(session, cancellationToken); } evt.CatchType = encounter is EncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; 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); session.EventDispatcher.Send(evt); attemptCounter++; DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); }
public static void CheckSetMoveToTargetStatus(ref FortDetailsResponse fortInfo, ref FortData pokeStop) { if (SetMoveToTargetEnabled) { SetMoveToTargetAccept = true; fortInfo.Name = "User Destination."; fortInfo.Latitude = pokeStop.Latitude = SetMoveToTargetLat; fortInfo.Longitude = pokeStop.Longitude = SetMoveToTargetLng; } }
private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false) { // If the cooldown is in the future than don't farm the pokestop. if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime()) { return; } FortSearchResponse fortSearch; var timesZeroXPawarded = 0; var fortTry = 0; //Current check const int retryNumber = 50; //How many times it needs to check to clear softban const int zeroCheck = 5; //How many times it checks fort before it thinks it's softban do { cancellationToken.ThrowIfCancellationRequested(); if (SearchThresholdExceeds(session)) { break; } fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) { timesZeroXPawarded = 0; } if (fortSearch.ExperienceAwarded == 0) { timesZeroXPawarded++; if (timesZeroXPawarded > zeroCheck) { if ((int)fortSearch.CooldownCompleteTimestampMs != 0) { break; // Check if successfully looted, if so program can continue as this was "false alarm". } fortTry += 1; session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry, Max = retryNumber - zeroCheck, Looted = false }); if (doNotRetry) { break; } if (!session.LogicSettings.FastSoftBanBypass) { DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0); } } } else { if (fortTry != 0) { session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry + 1, Max = retryNumber - zeroCheck, Looted = true }); } session.EventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude, Altitude = session.Client.CurrentAltitude, InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull }); if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull) { _storeRi = 1; } if (session.LogicSettings.UsePokeStopLimit) { session.Stats.PokeStopTimestamps.Add(DateTime.Now.Ticks); UpdateTimeStampsPokestop?.Invoke(); Logger.Write($"(POKESTOP LIMIT) {session.Stats.PokeStopTimestamps.Count}/{session.LogicSettings.PokeStopLimit}", LogLevel.Info, ConsoleColor.Yellow); } break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry) { if (++_randomStop >= _randomNumber) { _randomNumber = _rc.Next(4, 11); _randomStop = 0; int randomWaitTime = _rc.Next(30, 120); await Task.Delay(randomWaitTime, cancellationToken); } } }
public static async Task SpinPokestopNearBy(ISession session, CancellationToken cancellationToken, FortData destinationFort = null) { var allForts = session.Forts.Where(p => p.Type == FortType.Checkpoint).ToList(); if (allForts.Count > 1) { var spinablePokestops = allForts.Where( i => ( LocationUtils.CalculateDistanceInMeters( session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40 && i.CooldownCompleteTimestampMs == 0 && (destinationFort == null || destinationFort.Id != i.Id)) ).ToList(); List <FortData> spinedPokeStops = new List <FortData>(); if (spinablePokestops.Count >= 1) { foreach (var pokeStop in spinablePokestops) { var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); await FarmPokestop(session, pokeStop, fortInfo, cancellationToken, true); pokeStop.CooldownCompleteTimestampMs = DateTime.UtcNow.ToUnixTime() + 5 * 60 * 1000; spinedPokeStops.Add(pokeStop); if (spinablePokestops.Count > 1) { await Task.Delay(1000); } } } session.AddForts(spinablePokestops); } }
private static async Task <StartGymBattleResponse> StartBattle(ISession session, IEnumerable <PokemonData> pokemons, FortData currentFortData) { IEnumerable <PokemonData> currentPokemons = pokemons; var gymInfo = await session.Client.Fort.GetGymDetails(currentFortData.Id, currentFortData.Latitude, currentFortData.Longitude); if (gymInfo.Result != GetGymDetailsResponse.Types.Result.Success) { return(null); } var pokemonDatas = currentPokemons as PokemonData[] ?? currentPokemons.ToArray(); var defendingPokemon = gymInfo.GymState.Memberships.First().PokemonData.Id; var attackerPokemons = pokemonDatas.Select(pokemon => pokemon.Id); var attackingPokemonIds = attackerPokemons as ulong[] ?? attackerPokemons.ToArray(); Logger.Write( $"Attacking Gym: {gymInfo.Name}, DefendingPokemons:\n{ string.Join("\n", gymInfo.GymState.Memberships.Select(p => p.PokemonData.PokemonId).ToList()) }, \nAttacking: { gymInfo.GymState.Memberships.First().PokemonData.PokemonId }" ); var result = await session.Client.Fort.StartGymBattle(currentFortData.Id, defendingPokemon, attackingPokemonIds); if (result.Result == StartGymBattleResponse.Types.Result.Success) { switch (result.BattleLog.State) { case BattleState.Active: session.EventDispatcher.Send(new GymBattleStarted { GymName = gymInfo.Name }); return(result); case BattleState.Defeated: Logger.Write($"We were defeated in battle."); return(result); case BattleState.Victory: Logger.Write($"We were victorious"); _pos = 0; return(result); case BattleState.StateUnset: Logger.Write($"Error occoured: {result.BattleLog.State}"); break; case BattleState.TimedOut: Logger.Write($"Error occoured: {result.BattleLog.State}"); break; default: Logger.Write($"Unhandled occoured: {result.BattleLog.State}"); break; } } else if (result.Result == StartGymBattleResponse.Types.Result.ErrorGymBattleLockout) { return(result); } else if (result.Result == StartGymBattleResponse.Types.Result.ErrorAllPokemonFainted) { return(result); } else if (result.Result == StartGymBattleResponse.Types.Result.Unset) { return(result); } return(result); }
public static async Task Execute(ISession session, CancellationToken cancellationToken, FortData originalPokestop, FortDetailsResponse fortInfo) { pokestopCount++; pokestopCount = pokestopCount % 3; if (pokestopCount > 0 && !prioritySnipeFlag) { return; } InitSession(session); if (!_setting.CatchPokemon && !prioritySnipeFlag) { return; } cancellationToken.ThrowIfCancellationRequested(); if (_setting.HumanWalkingSnipeTryCatchEmAll) { var checkBall = await CheckPokeballsToSnipe(_setting.HumanWalkingSnipeCatchEmAllMinBalls, session, cancellationToken); if (!checkBall && !prioritySnipeFlag) { return; } } bool caughtAnyPokemonInThisWalk = false; SnipePokemonInfo pokemon = null; do { prioritySnipeFlag = false; pokemon = await GetNextSnipeablePokemon(session.Client.CurrentLatitude, session.Client.CurrentLongitude, !caughtAnyPokemonInThisWalk); if (pokemon != null) { await MSniperServiceTask.Execute(session, cancellationToken); caughtAnyPokemonInThisWalk = true; CalculateDistanceAndEstTime(pokemon); var remainTimes = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds * 0.95; //just use 90% times var catchPokemonTimeEST = (pokemon.Distance / 100) * 10; //assume that 100m we catch 1 pokemon and it took 10 second for each. string strPokemon = session.Translation.GetPokemonTranslation(pokemon.PokemonId); var spinPokestopEST = (pokemon.Distance / 100) * 5; bool catchPokemon = (pokemon.EstimatedTime + catchPokemonTimeEST) < remainTimes && pokemon.Setting.CatchPokemonWhileWalking; bool spinPokestop = pokemon.Setting.SpinPokestopWhileWalking && (pokemon.EstimatedTime + catchPokemonTimeEST + spinPokestopEST) < remainTimes; pokemon.IsCatching = true; session.EventDispatcher.Send(new HumanWalkSnipeEvent() { PokemonId = pokemon.PokemonId, Latitude = pokemon.Latitude, Longitude = pokemon.Longitude, Distance = pokemon.Distance, Expires = (pokemon.ExpiredTime - DateTime.Now).TotalSeconds, Estimate = (int)pokemon.EstimatedTime, Setting = pokemon.Setting, CatchPokemon = catchPokemon, Pokemons = ApplyFilter(rarePokemons), SpinPokeStop = pokemon.Setting.SpinPokestopWhileWalking, WalkSpeedApplied = pokemon.Setting.AllowSpeedUp ? pokemon.Setting.MaxSpeedUpSpeed : _session.LogicSettings.WalkingSpeedInKilometerPerHour, Type = HumanWalkSnipeEventTypes.StartWalking, Rarity = PokemonGradeHelper.GetPokemonGrade(pokemon.PokemonId).ToString() }); var snipeTarget = new SnipeLocation(pokemon.Latitude, pokemon.Longitude, LocationUtils.getElevation(session.ElevationService, pokemon.Latitude, pokemon.Longitude)); await session.Navigation.Move(snipeTarget, async() => { await MSniperServiceTask.Execute(session, cancellationToken); await ActionsWhenTravelToSnipeTarget(session, cancellationToken, pokemon, catchPokemon, spinPokestop); }, session, cancellationToken, pokemon.Setting.AllowSpeedUp?pokemon.Setting.MaxSpeedUpSpeed : 0); session.EventDispatcher.Send(new HumanWalkSnipeEvent() { Latitude = pokemon.Latitude, Longitude = pokemon.Longitude, PauseDuration = pokemon.Setting.DelayTimeAtDestination / 1000, Type = HumanWalkSnipeEventTypes.DestinationReached, UniqueId = pokemon.UniqueId }); await Task.Delay(pokemon.Setting.DelayTimeAtDestination); await CatchNearbyPokemonsTask.Execute(session, cancellationToken, pokemon.PokemonId, false); await Task.Delay(1000); if (!pokemon.IsVisited) { await CatchLurePokemonsTask.Execute(session, cancellationToken); } pokemon.IsVisited = true; pokemon.IsCatching = false; } }while (pokemon != null && _setting.HumanWalkingSnipeTryCatchEmAll); if (caughtAnyPokemonInThisWalk && (!_setting.HumanWalkingSnipeAlwaysWalkBack || _setting.UseGpxPathing)) { if (session.LogicSettings.UseGpxPathing) { await WalkingBackGPXPath(session, cancellationToken, originalPokestop, fortInfo); } else { await UpdateFarmingPokestop(session, cancellationToken); } } }
private static float GetDistance(FortData a, FortData b) { return GetDistance(a.Latitude, a.Longitude, b.Latitude, b.Longitude); }
private static async Task WalkingBackGPXPath(ISession session, CancellationToken cancellationToken, FortData originalPokestop, FortDetailsResponse fortInfo) { var destination = new FortLocation(originalPokestop.Latitude, originalPokestop.Longitude, LocationUtils.getElevation(session.ElevationService, originalPokestop.Latitude, originalPokestop.Longitude), originalPokestop, fortInfo); await session.Navigation.Move(destination, async() => { await MSniperServiceTask.Execute(session, cancellationToken); await CatchNearbyPokemonsTask.Execute(session, cancellationToken); await UseNearbyPokestopsTask.SpinPokestopNearBy(session, cancellationToken); }, session, cancellationToken); }
public FortData[] pathByNearestNeighbour(FortData[] pokeStops, double walkingSpeedInKilometersPerHour) { ////Start Gen. alg. //if (pokeStops.Length > 15) //{ // //Config // int ITERATIONS = 100000; // int POPSIZE = pokeStops.Length * 60; // double CROSSPROP = 99; // double MUTPROP = 20; // List<List<int>> population = new List<List<int>>(); // Random rnd = new Random(); // //Create Population // for (var i = POPSIZE; i > 0; --i) // { // List<int> tempChromosome = new List<int>(); // int items = rnd.Next(2, pokeStops.Length * 3 / 4); // do // { // int tempIndex = rnd.Next(0, pokeStops.Length - 1); // //Add only if new Index // while (tempChromosome.Exists(x => x == tempIndex)) // { // tempIndex = rnd.Next(0, pokeStops.Length - 1); // } // tempChromosome.Add(tempIndex); // } while (--items > 0); // if (calcFitness(ref pokeStops, tempChromosome, walkingSpeedInKilometersPerHour) > 0.0) // { // tempChromosome.Add(tempChromosome[0]); // population.Add(tempChromosome); // } // } // if (population.Count > 10) // { // for (int i = 0; i < ITERATIONS; ++i) // { // //Selection // var parents = selection(pokeStops, population, walkingSpeedInKilometersPerHour); // List<int> child1 = parents[0], child2 = parents[1]; // //Crossing // if (rnd.Next(0, 100) < CROSSPROP) // { // child1 = calcCrossing(parents[0], parents[1]); // child2 = calcCrossing(parents[1], parents[0]); // } // //Mutation // if (rnd.Next(0, 100) < MUTPROP) // { // mutate(ref child1); // } // if (rnd.Next(0, 100) < MUTPROP) // { // mutate(ref child2); // } // //Replace // List<int> fittnes = new List<int>(); // int sumPop = 0; // for (int c = 0; c < population.Count; ++c) // { // var temp = calcFitness(ref pokeStops, population[c], walkingSpeedInKilometersPerHour); // sumPop += temp; // fittnes.Add(temp); // } // List<int> fittnesSorted = new List<int>(fittnes); // fittnesSorted.Sort(); // if (fittnesSorted[0] <= calcFitness(ref pokeStops, child1, walkingSpeedInKilometersPerHour)) // { // var tempSelcetedChr = fittnes.FindIndex(x => x == fittnesSorted[0]); // population[tempSelcetedChr] = child1; // } // if (fittnesSorted[1] <= calcFitness(ref pokeStops, child2, walkingSpeedInKilometersPerHour)) // { // var tempSelcetedChr = fittnes.FindIndex(x => x == fittnesSorted[1]); // population[tempSelcetedChr] = child2; // } // //get best Generation // List<int> fittnes2 = new List<int>(); // for (int c = 0; c < population.Count; ++c) // { // var temp = calcFitness(ref pokeStops, population[c], walkingSpeedInKilometersPerHour); // fittnes2.Add(temp); // } // List<int> fittnesSorted2 = new List<int>(fittnes2); // fittnesSorted2.Sort(); // var tempSelcetedChr2 = fittnes2.FindIndex(x => x == fittnesSorted2[fittnesSorted2.Count - 1]); // List<FortData> newPokeStops = new List<FortData>(); // foreach (var element in population[tempSelcetedChr2]) // { // newPokeStops.Add(pokeStops[element]); // } // Logger.ColoredConsoleWrite(ConsoleColor.Yellow, $"{Math.Round(newPokeStops.Count * 3600 / calcTime(ref pokeStops, population[tempSelcetedChr2], walkingSpeedInKilometersPerHour))} PokeStops per Hour."); // return newPokeStops.ToArray(); // } // } //} //End gen. alg //Normal calculation for (var i = 1; i < pokeStops.Length - 1; i++) { var closest = i + 1; var cloestDist = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[closest].Latitude, pokeStops[closest].Longitude); for (var j = closest; j < pokeStops.Length; j++) { var initialDist = cloestDist; var newDist = LocationUtils.CalculateDistanceInMeters(pokeStops[i].Latitude, pokeStops[i].Longitude, pokeStops[j].Latitude, pokeStops[j].Longitude); if (initialDist > newDist) { cloestDist = newDist; closest = j; } } var tmpPok = pokeStops[closest]; pokeStops[closest] = pokeStops[i + 1]; pokeStops[i + 1] = tmpPok; } return pokeStops; }
public static async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) { TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon || session.CatchBlockTime > DateTime.Now) { return; } if (session.KnownLongitudeBeforeSnipe != 0 && session.KnownLatitudeBeforeSnipe != 0 && LocationUtils.CalculateDistanceInMeters(session.KnownLatitudeBeforeSnipe, session.KnownLongitudeBeforeSnipe, session.Client.CurrentLatitude, session.Client.CurrentLongitude) > 1000) { Logger.Write($"ERROR - Bot is stuck at snipe location({session.Client.CurrentLatitude},{session.Client.CurrentLongitude}). Teleport him back home - if you see this message please PM samuraitruong on Discord"); session.Client.Player.SetCoordinates(session.KnownLatitudeBeforeSnipe, session.KnownLongitudeBeforeSnipe, session.Client.CurrentAltitude); return; } Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; if ((session.LogicSettings.UsePokemonToCatchLocallyListOnly && !session.LogicSettings.PokemonToCatchLocally.Pokemon.Contains(pokemonId)) || (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId))) { session.EventDispatcher.Send(new NoticeEvent { Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId) }); } else { var encounterId = currentFortData.LureInfo.EncounterId; if (session.Cache.Get(CatchPokemonTask.GetEncounterCacheKey(currentFortData.LureInfo.EncounterId)) != null) { return; //pokemon been ignore before } var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId).ConfigureAwait(false); if (encounter.Result == DiskEncounterResponse.Types.Result.Success && session.LogicSettings.CatchPokemon) { var pokemon = new MapPokemon { EncounterId = encounterId, ExpirationTimestampMs = currentFortData.LureInfo.LureExpiresTimestampMs, Latitude = currentFortData.Latitude, Longitude = currentFortData.Longitude, PokemonId = currentFortData.LureInfo.ActivePokemonId, SpawnPointId = currentFortData.Id }; //add delegate function OnPokemonEncounterEvent(new List <MapPokemon> { pokemon }); // Catch the Pokemon await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData, sessionAllowTransfer : true).ConfigureAwait(false); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon) { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (EvolvePokemonTask.IsActivated(session)) { await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } } else { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } } else { if (encounter.Result.ToString().Contains("NotAvailable")) { return; } session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, encounter.Result) }); } } }
public async Task TeleportToPokestop(FortData closestPokestop) { if (closestPokestop?.Latitude == null) return; //if (closestPokestop.Latitude > 35) // return; await _player.UpdatePlayerLocation(closestPokestop.Latitude, closestPokestop.Longitude, 10); }
private async void RunningThread() { int failedWaitTime = 5000; int currentFails = 0; //Reset account state AccountState = Enums.AccountState.Good; while (IsRunning) { if (CheckTime()) { continue; } WaitPaused(); if ((_proxyIssue || CurrentProxy == null) && UserSettings.AutoRotateProxies) { bool success = await ChangeProxy(); //Fails when it's stopping if (!success) { continue; } //Have to restart to set proxy Restart(); _proxyIssue = false; continue; } StartingUp = true; if (currentFails >= UserSettings.MaxFailBeforeReset) { currentFails = 0; _client.Logout(); } if (_client.CaptchaInt > 0) { AccountState = AccountState.CaptchaReceived; LogCaller(new LoggerEventArgs("Captcha ceceived", LoggerTypes.Warning)); //Remove proxy RemoveProxy(); Stop(); continue; } if (_failedInventoryReponses >= _failedInventoryUntilBan) { AccountState = AccountState.PermAccountBan; LogCaller(new LoggerEventArgs("Potential account ban", LoggerTypes.Warning)); //Remove proxy RemoveProxy(); Stop(); continue; } ++currentFails; MethodResult result = new MethodResult(); try { #region Startup if (!_client.LoggedIn) { //Login result = await Login(); if (!result.Success) { //A failed login should require longer wait await Task.Delay(failedWaitTime * 3); continue; } } //LogCaller(new LoggerEventArgs("Sending echo test ...", LoggerTypes.Debug)); result = await CheckReauthentication(); if (!result.Success) { LogCaller(new LoggerEventArgs("Echo failed. Logging out before retry.", LoggerTypes.Debug)); _client.Logout(); await Task.Delay(failedWaitTime); continue; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.StopOnAPIUpdate) { //Get Game settings LogCaller(new LoggerEventArgs("Grabbing game settings ...", LoggerTypes.Debug)); try { MethodResult <bool> minClientResponse = await GetGameSettings(_client.VersionStr); if (result.Success) { //Version isn't 0.xx.x if (!minClientResponse.Data) { LogCaller(new LoggerEventArgs($"Emulates API {_client.VersionStr} ...", LoggerTypes.FatalError, new Exception($"New API needed {_client.ClientSession.GlobalSettings.MinimumClientVersion}. Stopping ..."))); Stop(); continue; } } } catch (Exception) { AccountState = AccountState.PokemonBanAndPokestopBanTemp; LogCaller(new LoggerEventArgs("Game settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); Stop(); continue; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } //Get pokemon settings if (PokeSettings == null) { LogCaller(new LoggerEventArgs("Grabbing pokemon settings ...", LoggerTypes.Debug)); result = await GetItemTemplates(); if (!result.Success) { AccountState = AccountState.PokemonBanAndPokestopBanTemp; LogCaller(new LoggerEventArgs("Load pokemon settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); Stop(); continue; } } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); //Get profile data LogCaller(new LoggerEventArgs("Grabbing player data ...", LoggerTypes.Debug)); result = await GetPlayer(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); //Update inventory LogCaller(new LoggerEventArgs("Updating inventory items ...", LoggerTypes.Debug)); result = await UpdateInventory(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (!result.Success) { if (result.Message == "Failed to get inventory.") { ++_failedInventoryReponses; } await Task.Delay(failedWaitTime); continue; } if (UserSettings.ClaimLevelUpRewards) { LogCaller(new LoggerEventArgs("Getting level up rewards ...", LoggerTypes.Debug)); result = await ClaimLevelUpRewards(Level); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } _failedInventoryReponses = 0; if (WaitPaused()) { continue; } //End startup phase StartingUp = false; //Prevent changing back to running state if (State != BotState.Stopping) { State = BotState.Running; } else { continue; } //Update location if (_firstRun) { LogCaller(new LoggerEventArgs("Setting default location ...", LoggerTypes.Debug)); result = await UpdateLocation(new GeoCoordinate(UserSettings.DefaultLatitude, UserSettings.DefaultLongitude)); if (!result.Success) { await Task.Delay(failedWaitTime); continue; } } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); #endregion #region PokeStopTask //Get pokestops LogCaller(new LoggerEventArgs("Grabbing pokestops...", LoggerTypes.Debug)); MethodResult <List <FortData> > pokestops = await GetPokeStops(); if (!pokestops.Success) { await Task.Delay(failedWaitTime); continue; } int pokeStopNumber = 1; int totalStops = pokestops.Data.Count; if (totalStops == 0) { _proxyIssue = false; _potentialPokeStopBan = false; LogCaller(new LoggerEventArgs(String.Format("{0}. Failure {1}/{2}", pokestops.Message, currentFails, UserSettings.MaxFailBeforeReset), LoggerTypes.Warning)); if (UserSettings.AutoRotateProxies && currentFails >= UserSettings.MaxFailBeforeReset) { if (pokestops.Message.StartsWith("No pokestop data found.")) { _proxyIssue = true; await ChangeProxy(); } } await Task.Delay(failedWaitTime); continue; } GeoCoordinate defaultLocation = new GeoCoordinate(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude); List <FortData> pokestopsToFarm = pokestops.Data.ToList(); int currentFailedStops = 0; while (pokestopsToFarm.Any()) { if (!IsRunning || currentFailedStops >= UserSettings.MaxFailBeforeReset) { break; } if (CheckTime()) { continue; } WaitPaused(); pokestopsToFarm = pokestopsToFarm.OrderBy(x => CalculateDistanceInMeters(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude, x.Latitude, x.Longitude)).ToList(); FortData pokestop = pokestopsToFarm[0]; pokestopsToFarm.RemoveAt(0); if (!UserSettings.SpinGyms && pokestop.Type == FortType.Gym) { continue; } GeoCoordinate currentLocation = new GeoCoordinate(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude); GeoCoordinate fortLocation = new GeoCoordinate(pokestop.Latitude, pokestop.Longitude); double distance = CalculateDistanceInMeters(currentLocation, fortLocation); string fort = "pokestop"; if (pokestop.Type == FortType.Gym) { MethodResult <GymGetInfoResponse> _result = await GymGetInfo(pokestop); if (_result.Success) { fort = "gym"; } else { continue; } } LogCaller(new LoggerEventArgs(String.Format("Going to {0} {1} of {2}. Distance {3:0.00}m", fort, pokeStopNumber, totalStops, distance), pokestop.Type == FortType.Checkpoint ? LoggerTypes.Info : LoggerTypes.FortGym)); //Go to pokestops MethodResult walkResult = await GoToLocation(new GeoCoordinate(pokestop.Latitude, pokestop.Longitude)); if (!walkResult.Success) { LogCaller(new LoggerEventArgs("Too many failed walking attempts. Restarting to fix ...", LoggerTypes.Warning)); break; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); //Search double filledInventorySpace = FilledInventorySpace(); if (filledInventorySpace < UserSettings.SearchFortBelowPercent) { MethodResult searchResult = await SearchPokestop(pokestop); //OutOfRange will show up as a success if (searchResult.Success) { currentFailedStops = 0; } else { ++currentFailedStops; } } else { LogCaller(new LoggerEventArgs(String.Format("Skipping fort. Currently at {0:0.00}% filled", filledInventorySpace), LoggerTypes.Info)); } //Stop bot instantly if (!IsRunning) { continue; } int remainingBalls = RemainingPokeballs(); if (remainingBalls > 0) { //Catch nearby pokemon MethodResult nearbyPokemonResponse = await CatchNeabyPokemon(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); //Get nearby lured pokemon MethodResult luredPokemonResponse = await CatchLuredPokemon(pokestop); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } //Clean inventory, evolve, transfer, etc on first and every 10 stops if (IsRunning && ((pokeStopNumber > 4 && pokeStopNumber % 10 == 0) || pokeStopNumber == 1)) { MethodResult echoResult = await CheckReauthentication(); //Echo failed, restart if (!echoResult.Success) { break; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); bool secondInventoryUpdate = false; int prevLevel = Level; await UpdateInventory(); if (Level > prevLevel) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); await ClaimLevelUpRewards(Level); } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.RecycleItems) { secondInventoryUpdate = true; await RecycleFilteredItems(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } if (UserSettings.EvolvePokemon) { MethodResult evolveResult = await EvolveFilteredPokemon(); if (evolveResult.Success) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); await UpdateInventory(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (UserSettings.TransferPokemon) { MethodResult transferResult = await TransferFilteredPokemon(); if (transferResult.Success) { secondInventoryUpdate = true; await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (UserSettings.IncubateEggs) { MethodResult incubateResult = await IncubateEggs(); if (incubateResult.Success) { secondInventoryUpdate = true; await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (secondInventoryUpdate) { await UpdateInventory(); } } ++pokeStopNumber; await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.MaxLevel > 0 && Level >= UserSettings.MaxLevel) { LogCaller(new LoggerEventArgs(String.Format("Max level of {0} reached.", UserSettings.MaxLevel), LoggerTypes.Info)); Stop(); } if (_potentialPokeStopBan) { //Break out of pokestop loop to test for ip ban break; } } #endregion } catch (Exception ex) { LogCaller(new LoggerEventArgs("Unknown exception occured. Restarting ...", LoggerTypes.Exception, ex)); //LogCaller(new LoggerEventArgs("Unknown exception occured. Stopping ...", LoggerTypes.Exception, ex)); //Stop(); } currentFails = 0; _firstRun = false; } State = BotState.Stopped; _client.Logout(); LogCaller(new LoggerEventArgs(String.Format("Bot fully stopped at {0}", DateTime.Now), LoggerTypes.Info)); if (_autoRestart) { _wasAutoRestarted = true; Start(); } else if (UserSettings.AutoRemoveOnStop) { RemoveProxy(); } }
private static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken) { FortSearchResponse fortSearch; var timesZeroXPawarded = 0; var fortTry = 0; //Current check const int retryNumber = 50; //How many times it needs to check to clear softban const int zeroCheck = 5; //How many times it checks fort before it thinks it's softban do { cancellationToken.ThrowIfCancellationRequested(); if (SearchThresholdExceeds(session)) { break; } fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) { timesZeroXPawarded = 0; } if (fortSearch.ExperienceAwarded == 0) { timesZeroXPawarded++; if (timesZeroXPawarded > zeroCheck) { if ((int)fortSearch.CooldownCompleteTimestampMs != 0) { break; // Check if successfully looted, if so program can continue as this was "false alarm". } fortTry += 1; session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry, Max = retryNumber - zeroCheck, Looted = false }); if (!session.LogicSettings.FastSoftBanBypass) { DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 0); } } } else { if (fortTry != 0) { session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry + 1, Max = retryNumber - zeroCheck, Looted = true }); } session.EventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded, Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude, Altitude = session.Client.CurrentAltitude, InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull }); if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull) { storeRI = 1; } session.Stats.PokeStopTimestamps.Add(DateTime.Now.Ticks); break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. if (session.LogicSettings.RandomlyPauseAtStops) { if (++RandomStop >= RandomNumber) { RandomNumber = rc.Next(4, 11); RandomStop = 0; int RandomWaitTime = rc.Next(30, 120); Thread.Sleep(RandomWaitTime); } } }
public static async Task Execute(ISession session, CancellationToken cancellationToken, dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { AmountOfBerries = 0; cancellationToken.ThrowIfCancellationRequested(); // If the encounter is null nothing will work below, so exit now if (encounter == null) 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 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))) { 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); } } //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); Logger.Write($"(Threw ball) {hitTxt} hit. {spinTxt}-ball...", 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); 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 }; 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(); } } evt.CatchType = encounter is EncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; 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); session.EventDispatcher.Send(evt); attemptCounter++; if (session.LogicSettings.TransferDuplicatePokemonOnCapture && session.LogicSettings.TransferDuplicatePokemon) await TransferDuplicatePokemonTask.Execute(session, cancellationToken); DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 0); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); }
public void PushPokeStopInfoUpdate(FortData pokeStop, string info) { HandlePokeStopInfoUpdate(pokeStop, info); }
private static async Task WalkingToPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo) { var distance = LocationUtils.CalculateDistanceInMeters(session.Client.CurrentLatitude, session.Client.CurrentLongitude, pokeStop.Latitude, pokeStop.Longitude); // we only move to the PokeStop, and send the associated FortTargetEvent, when not using GPX // also, GPX pathing uses its own EggWalker and calls the CatchPokemon tasks internally. if (!session.LogicSettings.UseGpxPathing) { var eggWalker = new EggWalker(1000, session); cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); // Always set the fort info in base walk strategy. var pokeStopDestination = new FortLocation(pokeStop.Latitude, pokeStop.Longitude, await LocationUtils.GetElevation(session.ElevationService, pokeStop.Latitude, pokeStop.Longitude).ConfigureAwait(false), pokeStop, fortInfo); await session.Navigation.Move(pokeStopDestination, async() => { await OnWalkingToPokeStopOrGym(session, pokeStop, cancellationToken).ConfigureAwait(false); }, session, cancellationToken).ConfigureAwait(false); // we have moved this distance, so apply it immediately to the egg walker. await eggWalker.ApplyDistance(distance, cancellationToken).ConfigureAwait(false); } }
private async void RunningThread() { const int failedWaitTime = 5000; int currentFails = 0; //Reset account state AccountState = Enums.AccountState.Good; while (IsRunning) { if (CheckTime()) { continue; } WaitPaused(); if ((_proxyIssue || CurrentProxy == null) && UserSettings.AutoRotateProxies) { bool success = await ChangeProxy(); //Fails when it's stopping if (!success) { continue; } //Have to restart to set proxy Restart(); _proxyIssue = false; continue; } StartingUp = true; if (currentFails >= UserSettings.MaxFailBeforeReset) { currentFails = 0; _client.Logout(); } if (_failedInventoryReponses >= _failedInventoryUntilBan) { AccountState = AccountState.PermanentBan; LogCaller(new LoggerEventArgs("Potential account ban", LoggerTypes.Warning)); //Remove proxy RemoveProxy(); Stop(); continue; } ++currentFails; var result = new MethodResult(); #region Startup try { if (!_client.LoggedIn) { //Login result = await AcLogin(); if (!result.Success) { //A failed login should require longer wait await Task.Delay(failedWaitTime * 3); continue; } } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); UpdateInventory(); // <- should not be needed result = await CheckReauthentication(); if (!result.Success) { LogCaller(new LoggerEventArgs("Echo failed. Logging out before retry.", LoggerTypes.Debug)); _client.Logout(); await Task.Delay(failedWaitTime); continue; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.StopOnAPIUpdate) { //Get Game settings LogCaller(new LoggerEventArgs("Grabbing game settings ...", LoggerTypes.Debug)); try { var remote = new Version(); if (_client.ClientSession.GlobalSettings != null) { remote = new Version(_client.ClientSession.GlobalSettings?.MinimumClientVersion); } if (_client.VersionStr < remote) { LogCaller(new LoggerEventArgs($"Emulates API {_client.VersionStr} ...", LoggerTypes.FatalError, new Exception($"New API needed {remote}. Stopping ..."))); Stop(); continue; } } catch (Exception ex1) { AccountState = AccountState.SoftBan; LogCaller(new LoggerEventArgs("Exception: " + ex1, LoggerTypes.Debug)); LogCaller(new LoggerEventArgs("Game settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); Stop(); continue; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } //Get pokemon settings if (PokeSettings == null) { LogCaller(new LoggerEventArgs("Grabbing pokemon settings ...", LoggerTypes.Debug)); result = await GetItemTemplates(); if (!result.Success) { AccountState = AccountState.SoftBan; LogCaller(new LoggerEventArgs("Load pokemon settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); Stop(); continue; } } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); //Auto complete tutorials if (UserSettings.CompleteTutorial) { if (!PlayerData.TutorialState.Contains(TutorialState.AvatarSelection)) { result = await MarkStartUpTutorialsComplete(true); if (!result.Success) { LogCaller(new LoggerEventArgs("Failed. Marking startup tutorials completed..", LoggerTypes.Warning)); Stop(); await Task.Delay(failedWaitTime); continue; } LogCaller(new LoggerEventArgs("Marking startup tutorials completed.", LoggerTypes.Success)); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } if (!PlayerData.TutorialState.Contains(TutorialState.PokestopTutorial)) { result = await MarkTutorialsComplete(new [] { TutorialState.PokestopTutorial, TutorialState.PokemonBerry, TutorialState.UseItem }); if (!result.Success) { LogCaller(new LoggerEventArgs("Failed. Marking pokestop, pokemonberry, useitem, pokemoncapture tutorials completed..", LoggerTypes.Warning)); Stop(); await Task.Delay(failedWaitTime); continue; } LogCaller(new LoggerEventArgs("Marking pokestop, pokemonberry, useitem, pokemoncapture tutorials completed.", LoggerTypes.Success)); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } _failedInventoryReponses = 0; if (WaitPaused()) { continue; } //End startup phase StartingUp = false; //Prevent changing back to running state if (State != BotState.Stopping) { State = BotState.Running; } else { continue; } //Update location if (_firstRun) { LogCaller(new LoggerEventArgs("Setting default location ...", LoggerTypes.Debug)); result = await UpdateLocation(new GeoCoordinate(UserSettings.Location.Latitude, UserSettings.Location.Longitude)); if (!result.Success) { await Task.Delay(failedWaitTime); continue; } } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); #endregion #region PokeStopTask //Get pokestops LogCaller(new LoggerEventArgs("getting pokestops...", LoggerTypes.Debug)); MethodResult <List <FortData> > pokestops = GetPokeStops(); if (!pokestops.Success) { await Task.Delay(failedWaitTime); continue; } int pokeStopNumber = 1; int totalStops = pokestops.Data.Count; if (totalStops == 0) { _proxyIssue = false; _potentialPokeStopBan = false; LogCaller(new LoggerEventArgs(String.Format("{0}. Failure {1}/{2}", pokestops.Message, currentFails, UserSettings.MaxFailBeforeReset), LoggerTypes.Warning)); if (UserSettings.AutoRotateProxies && currentFails >= UserSettings.MaxFailBeforeReset) { if (pokestops.Message.StartsWith("No pokestop data found.", StringComparison.Ordinal)) { _proxyIssue = true; await ChangeProxy(); } } await Task.Delay(failedWaitTime); continue; } var defaultLocation = new GeoCoordinate(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude); var pokestopsToFarm = new Queue <FortData>(pokestops.Data); int currentFailedStops = 0; while (pokestopsToFarm.Any()) { // In each iteration of the loop we store the current level int prevLevel = Level; if (!IsRunning || currentFailedStops >= UserSettings.MaxFailBeforeReset) { break; } if (CheckTime()) { continue; } WaitPaused(); FortData pokestop = pokestopsToFarm.Dequeue(); LogCaller(new LoggerEventArgs("fort Dequeued: " + pokestop.Id, LoggerTypes.Debug)); var currentLocation = new GeoCoordinate(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude); var fortLocation = new GeoCoordinate(pokestop.Latitude, pokestop.Longitude); double distance = CalculateDistanceInMeters(currentLocation, fortLocation); string fort = (pokestop.Type == FortType.Gym) ? "gym" : "pokestop"; LogCaller(new LoggerEventArgs(String.Format("Going to {0} {1} of {2}. Distance {3:0.00}m", fort, pokeStopNumber, totalStops, distance), pokestop.Type == FortType.Checkpoint ? LoggerTypes.Info : LoggerTypes.FortGym)); //Go to pokestops MethodResult walkResult = await GoToLocation(new GeoCoordinate(pokestop.Latitude, pokestop.Longitude)); if (!walkResult.Success) { LogCaller(new LoggerEventArgs("Too many failed walking attempts. Restarting to fix ...", LoggerTypes.Warning)); LogCaller(new LoggerEventArgs("Result: " + walkResult.Message, LoggerTypes.Debug)); break; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); UpdateInventory(); if (CatchDisabled) { //Check delay if account not have balls var now = DateTime.Now; LogCaller(new LoggerEventArgs("Now: " + now.ToLongDateString() + " " + now.ToLongTimeString(), LoggerTypes.Debug)); LogCaller(new LoggerEventArgs("TimeAutoCatch: " + TimeAutoCatch.ToLongDateString() + " " + TimeAutoCatch.ToLongTimeString(), LoggerTypes.Debug)); if (now > TimeAutoCatch) { CatchDisabled = false; LogCaller(new LoggerEventArgs("Enable catch after wait time.", LoggerTypes.Info)); } } // NOTE: not an "else" we could enabled catch in this time if (!CatchDisabled) { var remainingBalls = RemainingPokeballs(); LogCaller(new LoggerEventArgs("Remaining Balls: " + remainingBalls, LoggerTypes.Debug)); if (remainingBalls > 0) { //Catch nearby pokemon MethodResult nearbyPokemonResponse = await CatchNeabyPokemon(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } else { LogCaller(new LoggerEventArgs("You don't have any pokeball catching pokemon will be disabled during " + UserSettings.DisableCatchDelay.ToString(CultureInfo.InvariantCulture) + " minutes.", LoggerTypes.Info)); CatchDisabled = true; TimeAutoCatch = DateTime.Now.AddMinutes(UserSettings.DisableCatchDelay); } if (RemainingPokeballs() > 0) { //Catch lured pokemon MethodResult luredPokemonResponse = await CatchLuredPokemon(pokestop); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } else { LogCaller(new LoggerEventArgs("You don't have any pokeball catching pokemon will be disabled during " + UserSettings.DisableCatchDelay.ToString(CultureInfo.InvariantCulture) + " minutes.", LoggerTypes.Info)); CatchDisabled = true; TimeAutoCatch = DateTime.Now.AddMinutes(UserSettings.DisableCatchDelay); } UpdateInventory(); // <- should not be needed } //Stop bot instantly if (!IsRunning) { continue; } //Clean inventory, if (UserSettings.RecycleItems) { await RecycleFilteredItems(); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } //Search double filledInventorySpace = FilledInventoryStorage(); LogCaller(new LoggerEventArgs(String.Format("Filled Inventory Storage: {0:0.00}%", filledInventorySpace), LoggerTypes.Debug)); if ((filledInventorySpace < UserSettings.SearchFortBelowPercent) && (filledInventorySpace <= 100)) { if (pokestop.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()) { if (pokestop.Type == FortType.Gym) { if (!UserSettings.SpinGyms) { continue; } try { MethodResult <GymGetInfoResponse> _result = await GymGetInfo(pokestop); LogCaller(new LoggerEventArgs("Gym Name: " + _result.Data.Name, LoggerTypes.Info)); } catch (Exception) { LogCaller(new LoggerEventArgs("Skypped Gym...", LoggerTypes.Warning)); continue; } } else { var fortDetails = await FortDetails(pokestop); LogCaller(new LoggerEventArgs("Fort Name: " + fortDetails.Data.Name, LoggerTypes.Info)); } MethodResult searchResult = await SearchPokestop(pokestop); //OutOfRange will show up as a success if (searchResult.Success) { currentFailedStops = 0; } else { ++currentFailedStops; } } else { LogCaller(new LoggerEventArgs(String.Format("Skipping fort. In cooldown"), LoggerTypes.Info)); } } else { LogCaller(new LoggerEventArgs(String.Format("Skipping fort. Inventory Currently at {0:0.00}% filled", filledInventorySpace), LoggerTypes.Info)); } //Stop bot instantly if (!IsRunning) { continue; } // evolve, transfer, etc on first and every 10 stops if (IsRunning && ((pokeStopNumber > 4 && pokeStopNumber % 10 == 0) || pokeStopNumber == 1)) { MethodResult echoResult = await CheckReauthentication(); //Echo failed, restart if (!echoResult.Success) { break; } await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.EvolvePokemon) { MethodResult evolveResult = await EvolveFilteredPokemon(); if (evolveResult.Success) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (UserSettings.TransferPokemon) { MethodResult transferResult = await TransferFilteredPokemon(); if (transferResult.Success) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (UserSettings.IncubateEggs) { MethodResult incubateResult = await IncubateEggs(); if (incubateResult.Success) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } if (Level > prevLevel) { await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); await ClaimLevelUpRewards(Level); } } ++pokeStopNumber; await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); if (UserSettings.MaxLevel > 0 && Level >= UserSettings.MaxLevel) { LogCaller(new LoggerEventArgs(String.Format("Max level of {0} reached.", UserSettings.MaxLevel), LoggerTypes.Info)); Stop(); } if (_potentialPokeStopBan) { //Break out of pokestop loop to test for ip ban break; } } } catch (PokeHashException ex) { AccountState = AccountState.HashIssues; LogCaller(new LoggerEventArgs("Hash service exception occured. Restarting ...", LoggerTypes.Exception, ex)); } catch (Exception ex) { LogCaller(new LoggerEventArgs("Unknown exception occured. Restarting ...", LoggerTypes.Exception, ex)); //LogCaller(new LoggerEventArgs("Unknown exception occured. Stopping ...", LoggerTypes.Exception, ex)); //Stop(); } #endregion currentFails = 0; _firstRun = false; } State = BotState.Stopped; _client.Logout(); LogCaller(new LoggerEventArgs(String.Format("Bot fully stopped at {0}", DateTime.Now), LoggerTypes.Info)); if (_autoRestart) { _wasAutoRestarted = true; Start(); } else if (UserSettings.AutoRemoveOnStop) { RemoveProxy(); } }
private static async Task DoActionAtPokeStop(ISession session, CancellationToken cancellationToken, FortData pokeStop, FortDetailsResponse fortInfo, bool doNotTrySpin = false) { if (pokeStop.Type != FortType.Checkpoint) { return; } //Catch Lure Pokemon if (pokeStop.LureInfo != null) { // added for cooldowns await Task.Delay(Math.Min(session.LogicSettings.DelayBetweenPlayerActions, 3000)).ConfigureAwait(false); await CatchLurePokemonsTask.Execute(session, pokeStop, cancellationToken).ConfigureAwait(false); } // Spin as long as we haven't reached the user defined limits if (!_pokestopLimitReached && !_pokestopTimerReached) { await FarmPokestop(session, pokeStop, fortInfo, cancellationToken, doNotTrySpin).ConfigureAwait(false); } else { // We hit the pokestop limit but not the pokemon limit. So we want to set the cooldown on the pokestop so that // we keep moving and don't walk back and forth between 2 pokestops. pokeStop.CooldownCompleteTimestampMs = DateTime.UtcNow.ToUnixTime() + 5 * 60 * 1000; // 5 minutes to cooldown for pokestop. } if (++_stopsHit >= _storeRi) //TODO: OR item/pokemon bag is full //check stopsHit against storeRI random without dividing. { _storeRi = _rc.Next(6, 12); //set new storeRI for new random value _stopsHit = 0; if (session.LogicSettings.UseNearActionRandom) { await HumanRandomActionTask.Execute(session, cancellationToken).ConfigureAwait(false); } else { await RecycleItemsTask.Execute(session, cancellationToken).ConfigureAwait(false); if (session.LogicSettings.UseLuckyEggConstantly) { await UseLuckyEggConstantlyTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.UseIncenseConstantly) { await UseIncenseConstantlyTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.EvolveAllPokemonAboveIv || session.LogicSettings.EvolveAllPokemonWithEnoughCandy || session.LogicSettings.UseLuckyEggsWhileEvolving || session.LogicSettings.KeepPokemonsThatCanEvolve) { await EvolvePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.RenamePokemon) { await RenamePokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } if (session.LogicSettings.AutomaticallyLevelUpPokemon) { await LevelUpPokemonTask.Execute(session, cancellationToken).ConfigureAwait(false); } await GetPokeDexCount.Execute(session, cancellationToken).ConfigureAwait(false); } } }
public CachedGymGetails(ISession session, FortData fort) { LoadData(session, fort); }
private static async Task StartGymAttackLogic(ISession session, FortDetailsResponse fortInfo, GetGymDetailsResponse fortDetails, FortData gym, CancellationToken cancellationToken) { bool fighting = true; var badassPokemon = await session.Inventory.GetHighestCpForGym(6); var pokemonDatas = badassPokemon as PokemonData[] ?? badassPokemon.ToArray(); while (fighting) { // Heal pokemon foreach (var pokemon in pokemonDatas) { if (pokemon.Stamina <= 0) { await RevivePokemon(session, pokemon); } if (pokemon.Stamina < pokemon.StaminaMax) { await HealPokemon(session, pokemon); } } await Task.Delay(4000); int tries = 0; StartGymBattleResponse result; do { tries++; result = await StartBattle(session, pokemonDatas, gym); if (result.Result == StartGymBattleResponse.Types.Result.Unset) { // Try to refresh information about pokemons and gym await session.Inventory.RefreshCachedInventory(); badassPokemon = await session.Inventory.GetHighestCpForGym(6); pokemonDatas = badassPokemon as PokemonData[] ?? badassPokemon.ToArray(); Logger.Write($"Failed to Start Gym Battle at try: {tries}, waiting 20 seconds before make another one.", LogLevel.Gym, ConsoleColor.Red); await Task.Delay(20000); } } while (result.Result == StartGymBattleResponse.Types.Result.Unset && tries <= 10); // If we can't start battle in 10 tries, let's skip the gym if (result.Result == StartGymBattleResponse.Types.Result.Unset) { session.EventDispatcher.Send(new GymErrorUnset { GymName = fortInfo.Name }); break; } if (result.Result != StartGymBattleResponse.Types.Result.Success) { break; } switch (result.BattleLog.State) { case BattleState.Active: Logger.Write($"Time to start Attack Mode", LogLevel.Gym, ConsoleColor.Red); await AttackGym(session, cancellationToken, gym, result); break; case BattleState.Defeated: break; case BattleState.StateUnset: break; case BattleState.TimedOut: break; case BattleState.Victory: fighting = false; break; default: Logger.Write($"Unhandled result starting gym battle:\n{result}"); break; } fortDetails = await session.Client.Fort.GetGymDetails(gym.Id, gym.Latitude, gym.Longitude); if (fortDetails.GymState.FortData.OwnedByTeam == TeamColor.Neutral || fortDetails.GymState.FortData.OwnedByTeam == session.Profile.PlayerData.Team) { break; } } // Finished battling.. OwnedByTeam should be neutral when we reach here if (fortDetails.GymState.FortData.OwnedByTeam == TeamColor.Neutral || fortDetails.GymState.FortData.OwnedByTeam == session.Profile.PlayerData.Team) { await Execute(session, cancellationToken, gym, fortInfo); } else { Logger.Write($"Hmmm, for some reason the gym was not taken over..."); } }
public static async Task SpinPokestopNearBy(ISession session, CancellationToken cancellationToken, FortData destinationFort = null) { var allForts = session.Forts.Where(p => p.Type == FortType.Checkpoint).ToList(); if (allForts.Count > 0) { var spinablePokestops = allForts.Where( i => ( LocationUtils.CalculateDistanceInMeters( session.Client.CurrentLatitude, session.Client.CurrentLongitude, i.Latitude, i.Longitude) < 40 && i.CooldownCompleteTimestampMs == 0 && (destinationFort == null || destinationFort.Id != i.Id)) ).ToList(); if (spinablePokestops.Count > 0) { foreach (var pokeStop in spinablePokestops) { var fortInfo = await session.Client.Fort.GetFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude).ConfigureAwait(false); await FarmPokestop(session, pokeStop, fortInfo, cancellationToken, true).ConfigureAwait(false); } } session.AddForts(spinablePokestops); } }
public FortDataWrapper(FortData fortData) { _fortData = fortData; Geoposition = new Geopoint(new BasicGeoposition { Latitude = _fortData.Latitude, Longitude = _fortData.Longitude }); }
private async Task CatchNearbyPokemon(FortData fortData) { var pokemon = _map.GetNearbyPokemonClosestFirst().GetAwaiter().GetResult().DistinctBy(i => i.SpawnPointId).ToList(); if (pokemon.Any()) { var pokemonList = string.Join(", ", pokemon.Select(x => x.PokemonId).ToArray()); logger.Info($"{pokemon.Count()} Pokemon found: {pokemonList}"); } if (fortData?.LureInfo != null && fortData.LureInfo.ActivePokemonId != PokemonId.Missingno) { var encounterId = fortData.LureInfo.EncounterId; var encounter = await _encounter.EncounterPokemonLure(encounterId, fortData.Id); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { await _encounter.CatchPokemon(encounterId, fortData.Id, encounter, encounter.PokemonData.PokemonId); } } foreach (var mapPokemon in pokemon) { //logger.Info($"Found {pokemon.Count()} pokemon in your area."); if (_settings.UsePokemonToNotCatchFilter && _settings.PokemonsNotToCatch.Contains(mapPokemon.PokemonId)) { continue; } var encounter = await _encounter.EncounterPokemonAsync(mapPokemon); if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { await _encounter.CatchPokemon(encounter, mapPokemon); } else { if (encounter.Status != EncounterResponse.Types.Status.EncounterAlreadyHappened) logger.Warn($"Unable to catch pokemon. Reason: {encounter.Status}"); } } }
// ReSharper disable once UnusedParameter.Local private static async Task AttackGym(ISession session, CancellationToken cancellationToken, FortData currentFortData, StartGymBattleResponse startResponse) { long serverMs = startResponse.BattleLog.BattleStartTimestampMs; var lastActions = startResponse.BattleLog.BattleActions.ToList(); Logger.Write($"Gym battle started; fighting trainer: {startResponse.Defender.TrainerPublicProfile.Name}", LogLevel.Gym, ConsoleColor.Green); Logger.Write($"We are attacking: {startResponse.Defender.ActivePokemon.PokemonData.PokemonId}", LogLevel.Gym, ConsoleColor.White); int loops = 0; List <BattleAction> emptyActions = new List <BattleAction>(); BattleAction emptyAction = new BattleAction(); PokemonData attacker = null; while (true) { var attackActionz = GetActions(serverMs, attacker, _currentAttackerEnergy); var attackResult = await session.Client.Fort.AttackGym ( currentFortData.Id, startResponse.BattleId, (loops > 0 ? attackActionz : emptyActions), (loops > 0 ? lastActions.Last() : emptyAction) ); loops++; if (attackResult.Result == AttackGymResponse.Types.Result.Success) { switch (attackResult.BattleLog.State) { case BattleState.Active: _currentAttackerEnergy = attackResult.ActiveAttacker.CurrentEnergy; attacker = attackResult.ActiveAttacker.PokemonData; Logger.Write( $"Successful attack! - They have {attackResult.ActiveDefender.CurrentHealth} health left, we have {attackResult.ActiveAttacker.CurrentHealth} health, energy: {attackResult.ActiveAttacker.CurrentEnergy}"); break; case BattleState.Defeated: Logger.Write( $"We were defeated... (AttackGym)"); return; case BattleState.TimedOut: Logger.Write( $"Our attack timed out...: {attackResult}"); return; case BattleState.StateUnset: Logger.Write( $"State was unset?: {attackResult}"); return; case BattleState.Victory: Logger.Write( $"We were victorious!: {attackResult}"); return; default: Logger.Write( $"Unhandled attack response: {attackResult}"); continue; } Debug.Write($"{attackResult}"); await Task.Delay(5000); // Sleep until last sent battle action expired //bool sleep = true; //while (attackActionz.LastOrDefault() != null && sleep) //{ // await Task.Delay(1000); // DateTime currentTime = DateTime.Now; // if (currentTime.ToUnixTime() > attackActionz.LastOrDefault().DamageWindowsEndTimestampMss) // { // sleep = false; // break; // } // else // { // Logger.Write($"Sleeping until next attack, {currentTime.ToUnixTime()} < {attackActionz.LastOrDefault().DamageWindowsEndTimestampMss}"); // } //} Logger.Write($"Finished sleeping, starting another attack"); } else { Logger.Write($"Unexpected attack result:\n{attackResult}"); continue; } if (attackResult.BattleLog != null && attackResult.BattleLog.BattleActions.Count > 0) { lastActions.AddRange(attackResult.BattleLog.BattleActions); } serverMs = attackResult.BattleLog.ServerMs; } }
public static async Task <bool> Execute(ISession session, dynamic encounter, PokemonCacheItem pokemon, CancellationToken cancellationToken, FortData currentFortData = null, ulong encounterId = 0) { if (!await CheckBotStateTask.Execute(session, cancellationToken)) { return(false); } if (encounter is EncounterResponse && pokemon == null) { throw new ArgumentException("Parameter pokemon must be set, if encounter is of type EncounterResponse", nameof(pokemon)); } var prevState = session.State; session.State = BotState.Catch; CatchPokemonResponse caughtPokemonResponse; var attemptCounter = 1; do { if (session.LogicSettings.MaxPokeballsPerPokemon > 0 && attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon) { break; } float probability = encounter?.CaptureProbability?.CaptureProbability_[0]; ItemId 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 }); session.State = prevState; return(false); } var useBerryBelowCatchProbability = session.LogicSettings.UseBerryBelowCatchProbability > 1 ? session.LogicSettings.UseBerryBelowCatchProbability / 100 : session.LogicSettings.UseBerryBelowCatchProbability; var isLowProbability = probability < useBerryBelowCatchProbability; var isHighCp = encounter != null && (encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp : encounter.PokemonData?.Cp) > session.LogicSettings.UseBerryMinCp; var isHighPerfection = PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData) >= session.LogicSettings.UseBerryMinIv; if (isLowProbability && ((session.LogicSettings.PrioritizeIvOverCp && isHighPerfection) || isHighCp)) { await UseBerry(session, encounter is EncounterResponse || encounter is IncenseEncounterResponse ?pokemon.EncounterId : encounterId, encounter is EncounterResponse || encounter is IncenseEncounterResponse ?pokemon.SpawnPointId : currentFortData?.Id); await DelayingUtils.Delay(session.LogicSettings.DelayBetweenPlayerActions, 1000); } 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); double normalizedRecticleSize, spinModifier; if (session.LogicSettings.HumanizeThrows) { normalizedRecticleSize = Rng.NextInRange(session.LogicSettings.ThrowAccuracyMin, session.LogicSettings.ThrowAccuracyMax) * 1.85 + 0.1; // 0.1..1.95 spinModifier = Rng.NextDouble() > session.LogicSettings.ThrowSpinFrequency ? 0.0 : 1.0; } else { normalizedRecticleSize = 1.95; spinModifier = 1.00; } Func <ItemId, string> returnRealBallName = a => { switch (a) { case ItemId.ItemPokeBall: return(session.Translation.GetTranslation(TranslationString.Pokeball)); case ItemId.ItemGreatBall: return(session.Translation.GetTranslation(TranslationString.GreatPokeball)); case ItemId.ItemUltraBall: return(session.Translation.GetTranslation(TranslationString.UltraPokeball)); case ItemId.ItemMasterBall: return(session.Translation.GetTranslation(TranslationString.MasterPokeball)); default: return(session.Translation.GetTranslation(TranslationString.CommonWordUnknown)); } }; Func <double, string> getThrowType = a => { if (a < 1.0) { return("Normal "); } if (a < 1.3) { return("Nice! "); } if (a < 1.7) { return("Great! "); } return(a > 1.6 ? "Excellent! " : "unknown "); }; var hit = Rng.NextDouble() > session.LogicSettings.MissChance; Logging.Logger.Write($"Throwing {(Math.Abs(spinModifier - 1) < 0.00001 ?"Spinning " : "" )}{getThrowType(normalizedRecticleSize)}{returnRealBallName(pokeball)} - {(hit ? "WILL HIT" : "WILL MISS")}", Logging.LogLevel.Caught, session: session); 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 : hit); session.EventDispatcher.Send(new ItemLostEvent { Id = pokeball, Count = 1 }); 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 }; if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess) { if (pokemon != null) { pokemon.Caught = true; } evt.Uid = caughtPokemonResponse.CapturedPokemonId; var totalExp = caughtPokemonResponse.CaptureAward.Xp.Sum(); var profile = await session.Client.Player.GetPlayer(); evt.Exp = totalExp; evt.Stardust = profile.PlayerData.Currencies.ToArray()[1].Amount; var pokemonSettings = await session.Inventory.GetPokemonSettings(); var pokemonFamilies = await session.Inventory.GetPokemonFamilies(); var setting = pokemonSettings.FirstOrDefault(q => 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.Family = family.FamilyId; evt.FamilyCandies = family.Candy_; } else { evt.FamilyCandies = caughtPokemonResponse.CaptureAward.Candy.Sum(); } session.MapCache.PokemonCaught(pokemon); } if (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchFlee) { pokemon.Caught = true; } evt.CatchType = encounter is EncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; var pokeData = (encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData) as PokemonData; if (pokeData != null) { evt.Level = PokemonInfo.GetLevel(pokeData); evt.Cp = pokeData.Cp; evt.MaxCp = PokemonInfo.CalculateMaxCp(pokeData); evt.Perfection = Math.Round(pokeData.CalculatePokemonPerfection(), 2); evt.Probability = Math.Round(probability * 100, 2); evt.Move1 = pokeData.Move1; evt.Move2 = pokeData.Move2; } evt.Distance = distance; evt.Pokeball = pokeball; evt.Attempt = attemptCounter; await session.Inventory.RefreshCachedInventory(); evt.BallAmount = await session.Inventory.GetItemAmountByType(pokeball); session.EventDispatcher.Send(evt); attemptCounter++; await Task.Delay(session.LogicSettings.DelayCatchPokemon); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); session.State = prevState; return(true); }
public async Task Move(FortData pokestop, Action action) { if (_logicSettings.Teleport) { //var distance = LocationUtils.CalculateDistanceInMeters(_navigation.CurrentLatitude, _navigation.CurrentLongitude, pokestop.Latitude, pokestop.Longitude); //if (distance > 100) //{ // var r = new Random((int)DateTime.Now.Ticks); // closestPokestop = // pokestopList.ElementAt(r.Next(pokestopList.Count)); //} await TeleportToPokestop(pokestop); } else { await HumanLikeWalking(new GeoCoordinate(pokestop.Latitude, pokestop.Longitude), _logicSettings.WalkingSpeedInKilometerPerHour, action); } }
private async Task<Action> CatchLurePokemon(FortData fortData) { Action returnAction = () => { }; if (fortData?.LureInfo != null && fortData.LureInfo.ActivePokemonId != PokemonId.Missingno) { var encounterId = fortData.LureInfo.EncounterId; var encounter = await _encounter.EncounterPokemonLure(encounterId, fortData.Id); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { returnAction = async () => { await _encounter.CatchPokemon(encounterId, fortData.Id, encounter, encounter.PokemonData.PokemonId); }; } } return returnAction; }
protected bool IsVisited(FortData data) { return(fort.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime()); }
public async Task TeleportToPokestop(FortData closestPokestop) { if (closestPokestop?.Latitude == null) return; await _player.UpdatePlayerLocation(closestPokestop.Latitude, closestPokestop.Longitude, _settings.DefaultAltitude); }
public static async Task Execute(ISession session, FortData currentFortData, CancellationToken cancellationToken) { TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); cancellationToken.ThrowIfCancellationRequested(); if (!session.LogicSettings.CatchPokemon || session.CatchBlockTime > DateTime.Now) { return; } Logger.Write(session.Translation.GetTranslation(TranslationString.LookingForLurePokemon), LogLevel.Debug); var fortId = currentFortData.Id; var pokemonId = currentFortData.LureInfo.ActivePokemonId; if ((session.LogicSettings.UsePokemonSniperFilterOnly && !session.LogicSettings.PokemonToSnipe.Pokemon.Contains(pokemonId)) || (session.LogicSettings.UsePokemonToNotCatchFilter && session.LogicSettings.PokemonsNotToCatch.Contains(pokemonId))) { session.EventDispatcher.Send(new NoticeEvent { Message = session.Translation.GetTranslation(TranslationString.PokemonSkipped, pokemonId) }); } else { var encounterId = currentFortData.LureInfo.EncounterId; if (session.Cache.Get(currentFortData.LureInfo.EncounterId.ToString()) != null) { return; //pokemon been ignore before } var encounter = await session.Client.Encounter.EncounterLurePokemon(encounterId, fortId); if (encounter.Result == DiskEncounterResponse.Types.Result.Success && session.LogicSettings.CatchPokemon) { var pokemon = new MapPokemon { EncounterId = encounterId, ExpirationTimestampMs = currentFortData.LureInfo.LureExpiresTimestampMs, Latitude = currentFortData.Latitude, Longitude = currentFortData.Longitude, PokemonId = currentFortData.LureInfo.ActivePokemonId, SpawnPointId = currentFortData.Id }; // Catch the Pokemon await CatchPokemonTask.Execute(session, cancellationToken, encounter, pokemon, currentFortData, sessionAllowTransfer : true); } else if (encounter.Result == DiskEncounterResponse.Types.Result.PokemonInventoryFull) { if (session.LogicSettings.TransferDuplicatePokemon || session.LogicSettings.TransferWeakPokemon) { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferring) }); if (session.LogicSettings.TransferDuplicatePokemon) { await TransferDuplicatePokemonTask.Execute(session, cancellationToken); } if (session.LogicSettings.TransferWeakPokemon) { await TransferWeakPokemonTask.Execute(session, cancellationToken); } } else { session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.InvFullTransferManually) }); } } else { if (encounter.Result.ToString().Contains("NotAvailable")) { return; } session.EventDispatcher.Send(new WarnEvent { Message = session.Translation.GetTranslation(TranslationString.EncounterProblemLurePokemon, encounter.Result) }); } } }
public async Task TeleportToPokestop(FortData closestPokestop) { await _player.UpdatePlayerLocation(closestPokestop.Latitude, closestPokestop.Longitude, 10); }
private async void RunningThread() { const int failedWaitTime = 5000; int currentFails = 0; //Reset account state AccountState = AccountState.Good; while (IsRunning) { if (CheckTime()) { break; } WaitPaused(); if ((_proxyIssue || CurrentProxy == null) && UserSettings.AutoRotateProxies) { bool success = await ChangeProxy(); //Fails when it's stopping if (!success) { continue; } //Have to restart to set proxy Restart(); _proxyIssue = false; } StartingUp = true; if (currentFails >= UserSettings.MaxFailBeforeReset) { currentFails = 0; break; } if (_failedInventoryReponses >= _failedInventoryUntilBan) { AccountState = AccountState.PermanentBan; LogCaller(new LoggerEventArgs("Potential account ban", LoggerTypes.Warning)); break; } ++currentFails; var result = new MethodResult(); #region Startup try { if (!_client.LoggedIn) { //Login result = await AcLogin(); if (!result.Success) { //A failed login should require longer wait await Task.Delay(failedWaitTime * 3); continue; } } if (_client.ClientSession.AccessToken.IsExpired) { Restart(); } if (UserSettings.StopOnAPIUpdate) { //Get Game settings LogCaller(new LoggerEventArgs("Grabbing game settings ...", LoggerTypes.Debug)); try { var remote = new Version(); if (_client.ClientSession.GlobalSettings != null) { remote = new Version(_client.ClientSession.GlobalSettings?.MinimumClientVersion); } if (_client.VersionStr < remote) { LogCaller(new LoggerEventArgs($"Emulates API {_client.VersionStr} ...", LoggerTypes.FatalError, new Exception($"New API needed {remote}. Stopping ..."))); break; } } catch (Exception ex1) { //if (AccountState != AccountState.CaptchaReceived || AccountState != AccountState.HashIssues) // AccountState = AccountState.TemporalBan; LogCaller(new LoggerEventArgs("Exception: " + ex1, LoggerTypes.Debug)); LogCaller(new LoggerEventArgs("Game settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); break; } } //Get pokemon settings if (PokeSettings == null) { LogCaller(new LoggerEventArgs("Grabbing pokemon settings ...", LoggerTypes.Debug)); result = await GetItemTemplates(); if (!result.Success) { //if (AccountState != AccountState.CaptchaReceived || AccountState != AccountState.HashIssues) // AccountState = AccountState.TemporalBan; LogCaller(new LoggerEventArgs("Load pokemon settings failed", LoggerTypes.FatalError, new Exception("Maybe this account is banned ..."))); break; } } //Auto complete tutorials if (UserSettings.CompleteTutorial) { if (!PlayerData.TutorialState.Contains(TutorialState.AvatarSelection)) { result = await MarkStartUpTutorialsComplete(true); if (!result.Success) { LogCaller(new LoggerEventArgs("Failed. Marking startup tutorials completed..", LoggerTypes.Warning)); break; } LogCaller(new LoggerEventArgs("Marking startup tutorials completed.", LoggerTypes.Success)); await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } } _failedInventoryReponses = 0; WaitPaused(); //End startup phase StartingUp = false; //Prevent changing back to running state if (State != BotState.Stopping) { State = BotState.Running; } //Update location if (_firstRun) { LogCaller(new LoggerEventArgs("Setting default location ...", LoggerTypes.Debug)); result = await UpdateLocation(new GeoCoordinate(UserSettings.Latitude, UserSettings.Longitude)); if (!result.Success) { break; } UpdateInventory(InventoryRefresh.All); } #endregion #region PokeStopTask //Get pokestops //Goto her if count or meters is < of settings reloadAllForts: LogCaller(new LoggerEventArgs("Getting pokestops...", LoggerTypes.Info)); MethodResult <List <FortData> > pokestops = await GetAllFortsAsync(); if (!pokestops.Success) { await Task.Delay(failedWaitTime); continue; } int pokeStopNumber = 1; int totalStops = pokestops.Data.Count; if (totalStops == 0) { _proxyIssue = false; _potentialPokeStopBan = false; LogCaller(new LoggerEventArgs(String.Format("{0}. Failure {1}/{2}", pokestops.Message, currentFails, UserSettings.MaxFailBeforeReset), LoggerTypes.Warning)); if (UserSettings.AutoRotateProxies && currentFails >= UserSettings.MaxFailBeforeReset) { if (pokestops.Message.StartsWith("No pokestop data found.", StringComparison.Ordinal)) { _proxyIssue = true; await ChangeProxy(); } } await Task.Delay(failedWaitTime); continue; } int currentFailedStops = 0; var pokestopsToFarm = new Queue <FortData>(pokestops.Data); while (pokestopsToFarm.Any()) { // In each iteration of the loop we store the current level int prevLevel = Level; if (!IsRunning || currentFailedStops >= UserSettings.MaxFailBeforeReset) { break; } if (CheckTime()) { break; } pokestopsToFarm = new Queue <FortData>(pokestopsToFarm.OrderBy(x => CalculateDistanceInMeters(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude, x.Latitude, x.Longitude))); FortData pokestop = pokestopsToFarm.FirstOrDefault(); if (pokestop == null) { continue; } var player = new GeoCoordinate(_client.ClientSession.Player.Latitude, _client.ClientSession.Player.Longitude); var fortLocation = new GeoCoordinate(pokestop.Latitude, pokestop.Longitude); double distance = CalculateDistanceInMeters(player, fortLocation); if (UserSettings.MaxPokestopMeters > 0) { double rand = UserSettings.MaxPokestopMetersRandom - UserSettings.MaxPokestopMeters; pokestopsToFarm = new Queue <FortData>(pokestopsToFarm.OrderBy(x => distance <= rand)); if (pokestopsToFarm.Count < 1) { rand = UserSettings.MaxPokestopMetersRandom + UserSettings.MaxPokestopMeters; pokestopsToFarm = new Queue <FortData>(pokestopsToFarm.OrderBy(x => distance <= rand)); } if (pokestopsToFarm.Count < 1) { //Pass restart if value is 0 or meter no ok recommended 250-300 await Task.Delay(CalculateDelay(UserSettings.DelayBetweenLocationUpdates, UserSettings.LocationupdateDelayRandom)); goto reloadAllForts; } } if (pokestopsToFarm.Count < 1) { continue; } if (UserSettings.GoOnlyToGyms && pokestop.Type != FortType.Gym) { continue; } pokestop = pokestopsToFarm.Dequeue(); LogCaller(new LoggerEventArgs("Fort DeQueued: " + pokestop.Id, LoggerTypes.Debug)); string fort = "pokestop"; LoggerTypes loggerTypes = LoggerTypes.Info; if (pokestop.Type == FortType.Gym && Level >= 5 && !UserSettings.DefaultTeam.Equals("Neutral") && !String.IsNullOrEmpty(UserSettings.DefaultTeam)) { fort = "Gym"; loggerTypes = LoggerTypes.Gym; } if (!UserSettings.SpinGyms && pokestop.Type == FortType.Gym) { continue; } LogCaller(new LoggerEventArgs(String.Format("Going to {0} {1} of {2}. Distance {3:0.00}m", fort, pokeStopNumber, totalStops, distance), loggerTypes)); //Go to pokestops MethodResult walkResult = await GoToLocation(new GeoCoordinate(pokestop.Latitude, pokestop.Longitude)); if (!walkResult.Success) { LogCaller(new LoggerEventArgs("Too many failed walking attempts. Restarting to fix ...", LoggerTypes.Warning)); LogCaller(new LoggerEventArgs("Result: " + walkResult.Message, LoggerTypes.Debug)); break; } if (CatchDisabled) { //Check delay if account not have balls var now = DateTime.Now; LogCaller(new LoggerEventArgs("Now: " + now.ToLongDateString() + " " + now.ToLongTimeString(), LoggerTypes.Info)); LogCaller(new LoggerEventArgs("TimeAutoCatch: " + TimeAutoCatch.ToLongDateString() + " " + TimeAutoCatch.ToLongTimeString(), LoggerTypes.Info)); if (now > TimeAutoCatch) { CatchDisabled = false; LogCaller(new LoggerEventArgs("Enable catch after wait time.", LoggerTypes.Info)); } } // NOTE: not an "else" we could enabled catch in this time if (!CatchDisabled) { int remainingPokeballs = RemainingPokeballs(); LogCaller(new LoggerEventArgs("Remaining Balls: " + remainingPokeballs, LoggerTypes.Info)); double filledPokemonStorage = FilledPokemonStorage(); if (remainingPokeballs > 0) { if (filledPokemonStorage <= 100) { //Catch nearby pokemon MethodResult nearbyPokemonResponse = await CatchNeabyPokemon(); if (nearbyPokemonResponse.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } //Catch incense pokemon MethodResult incensePokemonResponse = await CatchInsencePokemon(); if (incensePokemonResponse.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } //Catch lured pokemon MethodResult luredPokemonResponse = await CatchLuredPokemon(pokestop); if (luredPokemonResponse.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } //Check sniping NearyPokemon MethodResult Snipe = await SnipeAllNearyPokemon(); if (Snipe.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); //this as walk to pokemon sinpe pos is not good .. continue for new pos.. continue; } } else { LogCaller(new LoggerEventArgs("You inventory pokemon storage is full please transfer some pokemons.", LoggerTypes.Warning)); await TransferFilteredPokemon(); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } else { LogCaller(new LoggerEventArgs("You don't have any pokeball catching pokemon will be disabled during " + UserSettings.DisableCatchDelay.ToString(CultureInfo.InvariantCulture) + " minutes.", LoggerTypes.Info)); CatchDisabled = true; TimeAutoCatch = DateTime.Now.AddMinutes(UserSettings.DisableCatchDelay); } } //Stop bot instantly if (!IsRunning) { break; } //Clean inventory, if (UserSettings.RecycleItems) { await RecycleFilteredItems(); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } //if too balls ignore stops.. if (RemainingPokeballs() >= UserSettings.BallsToIgnoreStops && UserSettings.IgnoreStopsIfTooBalls) { continue; } //Search double filledInventorySpace = FilledInventoryStorage(); LogCaller(new LoggerEventArgs(String.Format("Filled Inventory Storage: {0:0.00}%", filledInventorySpace), LoggerTypes.Debug)); if ((filledInventorySpace < UserSettings.SearchFortBelowPercent) && (filledInventorySpace <= 100)) { if (pokestop.CooldownCompleteTimestampMs < DateTime.UtcNow.ToUnixTime()) { if (pokestop.Type == FortType.Gym && Level >= 5 && (!string.IsNullOrEmpty(UserSettings.DefaultTeam) || UserSettings.DefaultTeam != "Neutral")) { if (!PlayerData.TutorialState.Contains(TutorialState.GymTutorial) && UserSettings.CompleteTutorial) { if (PlayerData.Team == TeamColor.Neutral) { TeamColor team = TeamColor.Neutral; foreach (TeamColor _team in Enum.GetValues(typeof(TeamColor))) { if (UserSettings.DefaultTeam == _team.ToString()) { team = _team; } } if (team != TeamColor.Neutral) { var setplayerteam = await SetPlayerTeam(team); if (setplayerteam.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); result = await MarkTutorialsComplete(new[] { TutorialState.GymTutorial }); if (!result.Success) { LogCaller(new LoggerEventArgs("Failed. Marking Gym tutorials completed..", LoggerTypes.Warning)); continue; } LogCaller(new LoggerEventArgs("Marking Gym tutorials completed.", LoggerTypes.Success)); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } } } if (PlayerData.TutorialState.Contains(TutorialState.GymTutorial) && UserSettings.CompleteTutorial) { //Check for missed tutorials foreach (TutorialState tuto in Enum.GetValues(typeof(TutorialState))) { if (!PlayerData.TutorialState.Contains(tuto)) { DialogResult box = MessageBox.Show($"Tutorial {tuto.ToString()} is not completed on this account {PlayerData.Username}! Complete this?", "Confirmation", MessageBoxButtons.YesNo); if (box == DialogResult.Yes) { result = await MarkTutorialsComplete(new[] { tuto }); if (result.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } } } var gyminfo = await GymGetInfo(pokestop); if (gyminfo.Success) { LogCaller(new LoggerEventArgs("Gym Name: " + gyminfo.Data.Name, LoggerTypes.Info)); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } else { continue; } MethodResult spingym = await SearchPokestop(pokestop); //OutOfRange will show up as a success if (spingym.Success) { currentFailedStops = 0; //Try to deploy, full gym is 6 now if (gyminfo.Data.GymStatusAndDefenders.GymDefender.Count < 6) { //Checks team color if same of player or Neutral if (pokestop.OwnedByTeam == PlayerData.Team || pokestop.OwnedByTeam == TeamColor.Neutral) { //Check if config as deploy actived if (UserSettings.DeployPokemon) { //Try to deploy await GymDeploy(pokestop); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } } //Here try to attack gym not released yet // await Task.Delay(CalculateDelay(UserSettings.GeneralDelay, UserSettings.GeneralDelayRandom)); } else { if (currentFailedStops > 10) { break; } ++currentFailedStops; } } } else { if (!PlayerData.TutorialState.Contains(TutorialState.PokestopTutorial) && UserSettings.CompleteTutorial) { result = await MarkTutorialsComplete(new[] { TutorialState.PokestopTutorial, TutorialState.PokemonBerry, TutorialState.UseItem }); if (!result.Success) { LogCaller(new LoggerEventArgs("Failed. Marking pokestop, pokemonberry, useitem, pokemoncapture tutorials completed..", LoggerTypes.Warning)); break; } LogCaller(new LoggerEventArgs("Marking pokestop, pokemonberry, useitem, pokemoncapture tutorials completed.", LoggerTypes.Success)); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } if (UserSettings.RequestFortDetails) { var fortDetails = await FortDetails(pokestop); if (fortDetails.Success) { LogCaller(new LoggerEventArgs("Fort Name: " + fortDetails.Data.Name, LoggerTypes.Info)); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } else { continue; } } MethodResult searchResult = await SearchPokestop(pokestop); //OutOfRange will show up as a success if (searchResult.Success) { currentFailedStops = 0; await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } else { if (currentFailedStops > 10) { break; } ++currentFailedStops; } } } else { LogCaller(new LoggerEventArgs(String.Format("Skipping fort. In cooldown"), LoggerTypes.Info)); } } else { LogCaller(new LoggerEventArgs(String.Format("Skipping fort. Inventory Currently at {0:0.00}% filled", filledInventorySpace), LoggerTypes.Info)); } //Stop bot instantly if (!IsRunning) { break; } // evolve, transfer, etc on first and every 10 stops if (IsRunning && ((pokeStopNumber > 4 && pokeStopNumber % 10 == 0) || pokeStopNumber == 1)) { // clean account state if (AccountState != AccountState.Flagged || AccountState != AccountState.SoftBan) { AccountState = AccountState.Good; } if (_client.ClientSession.AccessToken.IsExpired) { Restart(); } if (UserSettings.EvolvePokemon) { MethodResult evolveResult = await EvolveFilteredPokemon(); if (evolveResult.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } if (UserSettings.TransferPokemon) { MethodResult transferResult = await TransferFilteredPokemon(); if (transferResult.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } if (UserSettings.UpgradePokemon) { MethodResult upgradeResult = await UpgradeFilteredPokemon(); if (upgradeResult.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } if (UserSettings.IncubateEggs) { MethodResult incubateResult = await IncubateEggs(); if (incubateResult.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } UpdateInventory(InventoryRefresh.All); //all inventory } WaitPaused(); UpdateInventory(InventoryRefresh.Stats); if (Level > prevLevel) { await ClaimLevelUpRewards(Level); await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } ++pokeStopNumber; if (UserSettings.MaxLevel > 0 && Level >= UserSettings.MaxLevel) { LogCaller(new LoggerEventArgs(String.Format("Max level of {0} reached.", UserSettings.MaxLevel), LoggerTypes.Info)); await ExportToPGPool(); Stop(); await ShuffleADSProcess(); } if (_totalZeroExpStops > 25) { LogCaller(new LoggerEventArgs("Potential PokeStop SoftBan.", LoggerTypes.Warning)); AccountState = AccountState.SoftBan; // reset values _totalZeroExpStops = 0; break; } if (_potentialPokeStopBan) { //Break out of pokestop loop to test for ip ban break; } if (Tracker.PokemonCaught >= UserSettings.CatchPokemonDayLimit && Tracker.PokestopsFarmed >= UserSettings.SpinPokestopsDayLimit) { LogCaller(new LoggerEventArgs("Daily limits reached. Stoping ...", LoggerTypes.Warning)); Stop(); } if (UserSettings.UseLuckEggConst && Level >= UserSettings.LevelForConstLukky && IsRunning) { MethodResult luckEggResult = await UseLuckyEgg(); if (luckEggResult.Success) { await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } } } } catch (StackOverflowException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs(ex.Message, LoggerTypes.FatalError)); break; } catch (HashVersionMismatchException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs(ex.Message, LoggerTypes.FatalError)); break; } catch (GoogleLoginException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs(ex.Message, LoggerTypes.FatalError)); break; } catch (PtcLoginException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs(ex.Message, LoggerTypes.FatalError)); break; } catch (TaskCanceledException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs("TaskCanceledException. Restarting ...", LoggerTypes.Warning, ex)); } catch (OperationCanceledException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs("OperationCanceledException. Stopping ...", LoggerTypes.Warning, ex)); break; } catch (APIBadRequestException ex) { LogCaller(new LoggerEventArgs("API Bad Request. Restarting ...", LoggerTypes.Warning, ex)); } catch (InvalidPlatformException ex) { LogCaller(new LoggerEventArgs("Invalid Platform or token session refresh. Restarting ...", LoggerTypes.Warning, ex)); } catch (SessionInvalidatedException ex) { LogCaller(new LoggerEventArgs("Session Invalidated or token session refresh. Restarting ...", LoggerTypes.Warning, ex)); } catch (PokeHashException ex) { AccountState = AccountState.HashIssues; LogCaller(new LoggerEventArgs($"Hash service exception occured. Restarting ...", LoggerTypes.Warning, ex)); } catch (SessionUnknowException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs("Skipping request. Restarting ...", LoggerTypes.Exception, ex)); } catch (ArgumentOutOfRangeException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs("Skipping request. Restarting ...", LoggerTypes.Exception, ex)); } catch (SessionStateException ex) { AccountState = AccountState.Unknown; LogCaller(new LoggerEventArgs("SessionStateException. Restarting ...", LoggerTypes.Exception, ex)); _client.CleanLocalAccesToken(); } catch (Exception ex) { LogCaller(new LoggerEventArgs("Unknown exception occured. Restarting ...", LoggerTypes.Exception, ex)); } #endregion currentFails = 0; _firstRun = false; } Stop(); State = BotState.Stopped; LogCaller(new LoggerEventArgs(String.Format("Bot fully stopped at {0}", DateTime.Now), LoggerTypes.Info)); if (_autoRestart) { _wasAutoRestarted = true; Start(); } }
private bool CheckAndFarmNearbyPokeStop(FortData pokeStop, Client client, FortDetailsResponse fortInfo) { if (Setout.count >= 9) { Setout.Execute(); } if (pokeStop.CooldownCompleteTimestampMs < (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds && BotSettings.FarmPokestops) { var fortSearch = objClient.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude); Logger.Debug("================[VERBOSE LOGGING - Pokestop Search]================"); Logger.Debug($"Result: {fortSearch.Result}"); Logger.Debug($"ChainHackSequenceNumber: {fortSearch.ChainHackSequenceNumber}"); Logger.Debug($"Cooldown Complete (MS): {fortSearch.CooldownCompleteTimestampMs}"); Logger.Debug($"EXP Award: {fortSearch.ExperienceAwarded}"); Logger.Debug($"Gems Award: {fortSearch.GemsAwarded}"); Logger.Debug($"Item Award: {fortSearch.ItemsAwarded}"); Logger.Debug($"Egg Data: {fortSearch.PokemonDataEgg}"); Logger.Debug("=================================================================="); switch (fortSearch.Result.ToString()) { case "NoResultSet": Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: We did not recieve a result from the pokestop."); break; case "Success": // It already showed our pokestop Information break; case "OutOfRange": Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: The pokestop is out of range!"); break; case "InCooldownPeriod": Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Pokestop Warning: The current Pokestop is in the cooldown period."); break; case "InventoryFull": Logger.ColoredConsoleWrite(ConsoleColor.Yellow, "Pokestop Warning: Your Inventory is full. You did not recieve any items."); break; case "ExceededDailyLimit": Logger.ColoredConsoleWrite(ConsoleColor.Red, "Pokestop Error: You are above your daily limit of pokestops! You should stop farming pokestops."); break; } Setout.count++; var strDate = DateTime.Now.ToString("HH:mm:ss"); var pokeStopInfo = $"{fortInfo.Name}{Environment.NewLine}Visited:{strDate}{Environment.NewLine}"; if (fortSearch.ExperienceAwarded > 0) { var egg = "/"; if (fortSearch.PokemonDataEgg != null) { egg = fortSearch.PokemonDataEgg.EggKmWalkedTarget + "km"; } var items = ""; if (fortSearch.ItemsAwarded != null) { items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded); } var logrestock = false; if (fortSearch.ItemsAwarded != null) { foreach (var item in fortSearch.ItemsAwarded) { if (item.ItemId == ItemId.ItemPokeBall || item.ItemId == ItemId.ItemGreatBall || item.ItemId == ItemId.ItemUltraBall) { logrestock = true; } } if (logrestock && pokeballoutofstock) { Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Detected Pokeball Restock - Enabling Catch Pokemon"); CatchingLogic.AllowCatchPokemon = true; pokeballoutofstock = false; } FailedSoftban = 0; BotStats.AddExperience(fortSearch.ExperienceAwarded); Setout.RefreshConsoleTitle(client); Setout.pokeStopFarmedCount++; Setout.SaveSession(); Logger.Info($"Farmed XP: {fortSearch.ExperienceAwarded}, Gems: {fortSearch.GemsAwarded}, Egg: {egg}, Items: {items}"); var strItems = items.Replace(",", Environment.NewLine); pokeStopInfo += $"{fortSearch.ExperienceAwarded} XP{Environment.NewLine}{fortSearch.GemsAwarded}{Environment.NewLine}{egg}{Environment.NewLine}{strItems}"; Logger.Debug("LureInfo: " + pokeStop.LureInfo); if (pokeStop.LureInfo != null) { var pokedata = new MapPokemon(); pokedata.EncounterId = pokeStop.LureInfo.EncounterId; pokedata.PokemonId = pokeStop.LureInfo.ActivePokemonId; pokedata.Latitude = pokeStop.Latitude; pokedata.Longitude = pokeStop.Longitude; pokedata.ExpirationTimestampMs = pokeStop.LureInfo.LureExpiresTimestampMs; pokedata.SpawnPointId = pokeStop.LureInfo.FortId; infoObservable.PushNewPokemonLocation(pokedata); Logger.Debug("Lured Pokemon: " + pokedata); if (!BotSettings.catchPokemonSkipList.Contains(pokedata.PokemonId) && GlobalVars.CatchPokemon) { if (!lureEncounters.Contains(pokedata.EncounterId.ToString())) { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Catching Lured Pokemon"); CatchingLogic.CatchLuredPokemon(pokedata.EncounterId, pokedata.SpawnPointId, pokedata.PokemonId, pokedata.Longitude, pokedata.Latitude); lureEncounters.Add(pokedata.EncounterId.ToString()); } else { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Skipped Lure Pokemon: " + pokedata.PokemonId + " because we have already caught him, or catching pokemon is disabled"); } } } double eggs = 0; if (fortSearch.PokemonDataEgg != null) { eggs = fortSearch.PokemonDataEgg.EggKmWalkedTarget; } Telegram?.sendInformationText(TelegramUtil.TelegramUtilInformationTopics.Pokestop, fortInfo.Name, fortSearch.ExperienceAwarded, eggs, fortSearch.GemsAwarded, StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded)); } } Task.Factory.StartNew(() => infoObservable.PushPokeStopInfoUpdate(pokeStop, pokeStopInfo)); return(true); } if (!BotSettings.FarmPokestops) { Logger.ColoredConsoleWrite(ConsoleColor.Green, "Farm Pokestop option unchecked, skipping and only looking for pokemon"); return(false); } Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokestop not ready to farm again, skipping and only looking for pokemon"); return(false); }
private async Task <MethodResult> SearchPokestop(FortData pokestop) { try { FortSearchResponse fortResponse = null; int maxFortAttempts = 5; for (int i = 0; i < maxFortAttempts; i++) { var response = await _client.ClientSession.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.FortSearch, RequestMessage = new FortSearchMessage { FortId = pokestop.Id, FortLatitude = pokestop.Latitude, FortLongitude = pokestop.Longitude, PlayerLatitude = _client.ClientSession.Player.Latitude, PlayerLongitude = _client.ClientSession.Player.Longitude }.ToByteString() }); try { fortResponse = FortSearchResponse.Parser.ParseFrom(response); } catch (Exception ex) { if (response.IsEmpty) { LogCaller(new LoggerEventArgs("FortSearchResponse parsing failed because response was empty", LoggerTypes.Exception, ex)); } return(new MethodResult()); } if (fortResponse.Result == FortSearchResponse.Types.Result.OutOfRange) { if (_potentialPokeStopBan) { if (AccountState != Enums.AccountState.PokestopBanTemp && AccountState != Enums.AccountState.PokemonBanAndPokestopBanTemp) { LogCaller(new LoggerEventArgs("Pokestop ban detected. Marking state", LoggerTypes.Warning)); } //Already pokemon banned if (AccountState == Enums.AccountState.PokemonBanTemp || AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp) { AccountState = Enums.AccountState.PokemonBanAndPokestopBanTemp; } else { AccountState = Enums.AccountState.PokestopBanTemp; } //Check for auto stop bot if ((UserSettings.StopAtMinAccountState == Enums.AccountState.PokestopBanTemp || UserSettings.StopAtMinAccountState == Enums.AccountState.PokemonBanOrPokestopBanTemp) || (UserSettings.StopAtMinAccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp && AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp)) { LogCaller(new LoggerEventArgs("Auto stopping bot ...", LoggerTypes.Info)); Stop(); } } else //This error should never happen normally, so assume temp ban { _potentialPokeStopBan = true; _proxyIssue = true; //Display error only on first notice LogCaller(new LoggerEventArgs("Pokestop out of range. Potential temp pokestop ban or IP ban", LoggerTypes.Warning)); } //Let it continue down } else if (fortResponse.Result != FortSearchResponse.Types.Result.Success && fortResponse.Result != FortSearchResponse.Types.Result.InventoryFull) { LogCaller(new LoggerEventArgs(String.Format("Failed to search fort. Response: {0}", fortResponse.Result), LoggerTypes.Warning)); return(new MethodResult { Message = "Failed to search fort" }); } string message = String.Format("Searched Fort. Exp: {0}. Items: {1}.", fortResponse.ExperienceAwarded, StringUtil.GetSummedFriendlyNameOfItemAwardList(fortResponse.ItemsAwarded.ToList())); Dictionary <ItemId, ItemData> itemDictionary = new Dictionary <ItemId, ItemData>(); foreach (ItemData item in Items) { itemDictionary.Add(item.ItemId, item); } foreach (ItemAward item in fortResponse.ItemsAwarded) { if (itemDictionary.ContainsKey(item.ItemId)) { itemDictionary[item.ItemId].Count += item.ItemCount; } else { Items.Add(new ItemData { ItemId = item.ItemId, Unseen = true, Count = item.ItemCount }); } } if (fortResponse.Result != FortSearchResponse.Types.Result.OutOfRange) { //Successfully grabbed stop if (AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp || AccountState == Enums.AccountState.PokestopBanTemp) { if (AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp) { AccountState = Enums.AccountState.PokemonBanTemp; } else { AccountState = Enums.AccountState.Good; } LogCaller(new LoggerEventArgs("Pokestop ban was removed", LoggerTypes.Info)); } ExpIncrease(fortResponse.ExperienceAwarded); TotalPokeStopExp += fortResponse.ExperienceAwarded; Tracker.AddValues(0, 1); if (fortResponse.ExperienceAwarded == 0) { //Softban on the fleeing pokemon. Reset. _fleeingPokemonResponses = 0; _potentialPokemonBan = false; ++_totalZeroExpStops; message += String.Format(" No exp gained. Attempt {0} of {1}", i + 1, maxFortAttempts); } LogCaller(new LoggerEventArgs(message, LoggerTypes.Success)); } if (fortResponse.ExperienceAwarded != 0 || fortResponse.Result == FortSearchResponse.Types.Result.OutOfRange) { if (!_potentialPokemonBan && _fleeingPokemonResponses >= _fleeingPokemonUntilBan) { LogCaller(new LoggerEventArgs("Potential pokemon ban detected. Setting flee count to 0 avoid false positives", LoggerTypes.Warning)); _potentialPokemonBan = true; _fleeingPokemonResponses = 0; } else if (_fleeingPokemonResponses >= _fleeingPokemonUntilBan) { //Already pokestop banned if (AccountState == Enums.AccountState.PokestopBanTemp || AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp) { _potentialPokemonBan = false; AccountState = Enums.AccountState.PokemonBanAndPokestopBanTemp; } else { _potentialPokemonBan = false; AccountState = Enums.AccountState.PokemonBanTemp; } if (AccountState != Enums.AccountState.PokemonBanTemp) { //Only occurs when out of range is found if (fortResponse.ExperienceAwarded == 0) { LogCaller(new LoggerEventArgs("Pokemon fleeing and failing to grab stops. Potential pokemon & pokestop ban.", LoggerTypes.Warning)); } else { LogCaller(new LoggerEventArgs("Pokemon fleeing, yet grabbing stops. Potential pokemon ban.", LoggerTypes.Warning)); } } if (UserSettings.StopAtMinAccountState == Enums.AccountState.PokemonBanTemp || UserSettings.StopAtMinAccountState == Enums.AccountState.PokemonBanOrPokestopBanTemp || (UserSettings.StopAtMinAccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp && AccountState == Enums.AccountState.PokemonBanAndPokestopBanTemp)) { LogCaller(new LoggerEventArgs("Auto stopping bot ...", LoggerTypes.Info)); Stop(); } return(new MethodResult { Message = "Bans detected", Success = true }); } break; } await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } if (fortResponse != null && fortResponse.ExperienceAwarded == 0) { ++_totalZeroExpStops; if (_totalZeroExpStops >= 15 || _fleeingPokemonResponses >= _fleeingPokemonUntilBan) { _totalZeroExpStops = 0; LogCaller(new LoggerEventArgs("Potential softban detected. Attempting to bypass ...", LoggerTypes.Warning)); int totalAttempts = 0; int maxAttempts = 40; FortSearchResponse bypassResponse = null; do { ++totalAttempts; if (totalAttempts >= 5 && totalAttempts % 5 == 0) { LogCaller(new LoggerEventArgs(String.Format("Softban bypass attempt {0} of {1}", totalAttempts, maxAttempts), LoggerTypes.Info)); } var response = await _client.ClientSession.RpcClient.SendRemoteProcedureCallAsync(new Request { RequestType = RequestType.FortSearch, RequestMessage = new FortSearchMessage { FortId = pokestop.Id, FortLatitude = pokestop.Latitude, FortLongitude = pokestop.Longitude, PlayerLatitude = _client.ClientSession.Player.Latitude, PlayerLongitude = _client.ClientSession.Player.Longitude }.ToByteString() }); try { bypassResponse = FortSearchResponse.Parser.ParseFrom(response); } catch (Exception ex) { if (response.IsEmpty) { LogCaller(new LoggerEventArgs("FortSearchResponse parsing failed because response was empty", LoggerTypes.Exception, ex)); } return(new MethodResult()); } await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); } while (bypassResponse.ExperienceAwarded == 0 && totalAttempts <= maxAttempts); if (bypassResponse.ExperienceAwarded != 0) { //Fleeing pokemon was a softban, reset count _fleeingPokemonResponses = 0; _potentialPokemonBan = false; string message = String.Format("Searched Fort. Exp: {0}. Items: {1}.", bypassResponse.ExperienceAwarded, StringUtil.GetSummedFriendlyNameOfItemAwardList(bypassResponse.ItemsAwarded.ToList())); ExpIncrease(fortResponse.ExperienceAwarded); Tracker.AddValues(0, 1); //_expGained += fortResponse.ExperienceAwarded; LogCaller(new LoggerEventArgs(message, LoggerTypes.Success)); LogCaller(new LoggerEventArgs("Softban removed", LoggerTypes.Success)); } else { LogCaller(new LoggerEventArgs("Softban still active. Continuing ...", LoggerTypes.Info)); } } } else { _totalZeroExpStops = 0; } await Task.Delay(CalculateDelay(UserSettings.DelayBetweenPlayerActions, UserSettings.PlayerActionDelayRandom)); return(new MethodResult { Success = true, Message = "Success" }); } catch (Exception ex) { LogCaller(new LoggerEventArgs("Failed to search fort", LoggerTypes.Exception, ex)); return(new MethodResult { Message = "Failed to search fort" }); } }
public static async Task Execute(ISession session, dynamic encounter, MapPokemon pokemon, FortData currentFortData = null, ulong encounterId = 0) { CatchPokemonResponse caughtPokemonResponse; var attemptCounter = 1; do { if (session.LogicSettings.MaxPokeballsPerPokemon > 0 && attemptCounter > session.LogicSettings.MaxPokeballsPerPokemon) break; float probability = encounter?.CaptureProbability?.CaptureProbability_[0]; var 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; } var isLowProbability = probability < 0.35; var isHighCp = encounter != null && (encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData?.Cp : encounter.PokemonData?.Cp) > 400; var isHighPerfection = PokemonInfo.CalculatePokemonPerfection(encounter is EncounterResponse ? encounter.WildPokemon?.PokemonData : encounter?.PokemonData) >= session.LogicSettings.KeepMinIvPercentage; if ((isLowProbability && isHighCp) || isHighPerfection) { await UseBerry(session, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.EncounterId : encounterId, encounter is EncounterResponse || encounter is IncenseEncounterResponse ? pokemon.SpawnPointId : currentFortData?.Id); } 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); 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); 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 }; 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; 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(); } } evt.CatchType = encounter is EncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeNormal) : encounter is DiskEncounterResponse ? session.Translation.GetTranslation(TranslationString.CatchTypeLure) : session.Translation.GetTranslation(TranslationString.CatchTypeIncense); evt.Id = encounter is EncounterResponse ? pokemon.PokemonId : encounter?.PokemonData.PokemonId; 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); session.EventDispatcher.Send(evt); attemptCounter++; DelayingUtils.Delay(session.LogicSettings.DelayBetweenPokemonCatch, 2000); } while (caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchMissed || caughtPokemonResponse.Status == CatchPokemonResponse.Types.CatchStatus.CatchEscape); }
public static async Task FarmPokestop(ISession session, FortData pokeStop, FortDetailsResponse fortInfo, CancellationToken cancellationToken, bool doNotRetry = false) { var manager = TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>(); // If the cooldown is in the future than don't farm the pokestop. if (pokeStop.CooldownCompleteTimestampMs > DateTime.UtcNow.ToUnixTime()) { return; } if (session.Stats.SearchThresholdExceeds(session, true)) { if (manager.AllowMultipleBot() && session.LogicSettings.MultipleBotConfig.SwitchOnPokestopLimit) { throw new Exceptions.ActiveSwitchByRuleException(SwitchRules.SpinPokestopReached, session.LogicSettings.PokeStopLimit); } return; } //await session.Client.Map.GetMapObjects().ConfigureAwait(false); FortSearchResponse fortSearch; var timesZeroXPawarded = 0; var fortTry = 0; //Current check int retryNumber = session.LogicSettings.ByPassSpinCount; //How many times it needs to check to clear softban int zeroCheck = Math.Min(5, retryNumber); //How many times it checks fort before it thinks it's softban var distance = LocationUtils.CalculateDistanceInMeters(pokeStop.Latitude, pokeStop.Longitude, session.Client.CurrentLatitude, session.Client.CurrentLongitude); //This should be < ## not > ##. > makes bot jump to pokestop if < then when in range will just spin. if (distance < 50) //if (distance > 30) { await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(pokeStop.Latitude, pokeStop.Longitude), 0).ConfigureAwait(false); await session.Client.Misc.RandomAPICall().ConfigureAwait(false); } do { cancellationToken.ThrowIfCancellationRequested(); TinyIoC.TinyIoCContainer.Current.Resolve <MultiAccountManager>().ThrowIfSwitchAccountRequested(); int retry = 3; double latitude = pokeStop.Latitude; double longitude = pokeStop.Longitude; do { fortSearch = await session.Client.Fort.SearchFort(pokeStop.Id, pokeStop.Latitude, pokeStop.Longitude).ConfigureAwait(false); if (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange) { if (retry > 2) { await Task.Delay(500).ConfigureAwait(false); } else { await session.Client.Map.GetMapObjects(true).ConfigureAwait(false); } Logger.Debug($"Loot pokestop result: {fortSearch.Result}, distance to pokestop:[{pokeStop.Latitude}, {pokeStop.Longitude}] {distance:0.00}m, retry: #{4 - retry}"); latitude += 0.000003; longitude += 0.000005; await LocationUtils.UpdatePlayerLocationWithAltitude(session, new GeoCoordinate(latitude, longitude), 0).ConfigureAwait(false); retry--; } }while (fortSearch.Result == FortSearchResponse.Types.Result.OutOfRange && retry > 0); if (fortSearch.Result == FortSearchResponse.Types.Result.PoiInaccessible) { Logger.Debug($"Loot {fortInfo.Type} result: {fortSearch.Result} trainer level must be >= 5 to access gym disk."); //, LogLevel.Gym, ConsoleColor.White); break; } if (fortSearch.ExperienceAwarded > 0 && timesZeroXPawarded > 0) { timesZeroXPawarded = 0; } if (fortSearch.ExperienceAwarded == 0 && fortSearch.Result != FortSearchResponse.Types.Result.InventoryFull) { timesZeroXPawarded++; if (timesZeroXPawarded > zeroCheck) { if ((int)fortSearch.CooldownCompleteTimestampMs != 0) { break; // Check if successfully looted, if so program can continue as this was "false alarm". } fortTry += 1; session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry, Max = retryNumber - zeroCheck, Looted = false }); if (doNotRetry) { break; } if (!session.LogicSettings.FastSoftBanBypass) { await DelayingUtils.DelayAsync(session.LogicSettings.DelayBetweenPlayerActions, 0, session.CancellationTokenSource.Token).ConfigureAwait(false); } } } else { softbanCount = 0; if (fortTry != 0) { session.EventDispatcher.Send(new FortFailedEvent { Name = fortInfo.Name, Try = fortTry + 1, Max = retryNumber - zeroCheck, Looted = true }); } session.EventDispatcher.Send(new FortUsedEvent { Id = pokeStop.Id, Name = fortInfo.Name, Exp = fortSearch.ExperienceAwarded, Gems = fortSearch.GemsAwarded > 0 ? $"Yes {fortSearch.GemsAwarded}" : "No", Items = StringUtils.GetSummedFriendlyNameOfItemAwardList(fortSearch.ItemsAwarded), Badges = fortSearch.AwardedGymBadge != null ? fortSearch.AwardedGymBadge.GymBadgeType.ToString() : "No", BonusLoot = fortSearch.BonusLoot != null ? StringUtils.GetSummedFriendlyNameOfGetLootList(fortSearch.BonusLoot.LootItem) : "No", RaidTickets = fortSearch.RaidTickets > 0 ? $"{fortSearch.RaidTickets} tickets" : "No", TeamBonusLoot = fortSearch.TeamBonusLoot != null ? StringUtils.GetSummedFriendlyNameOfGetLootList(fortSearch.TeamBonusLoot.LootItem) : "No", PokemonDataEgg = fortSearch.PokemonDataEgg != null ? fortSearch.PokemonDataEgg : null, Latitude = pokeStop.Latitude, Longitude = pokeStop.Longitude, Altitude = session.Client.CurrentAltitude, InventoryFull = fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull, Fort = pokeStop }); if (fortSearch.Result == FortSearchResponse.Types.Result.Success) { mapEmptyCount = 0; foreach (var item in fortSearch.ItemsAwarded) { await session.Inventory.UpdateInventoryItem(item.ItemId).ConfigureAwait(false); } if (fortSearch.PokemonDataEgg != null) { fortSearch.PokemonDataEgg.IsEgg = true; } // Update the cache var fortFromCache = session.Client.Map.LastGetMapObjectResponse.MapCells.SelectMany(x => x.Forts).FirstOrDefault(f => f.Id == pokeStop.Id); long newCooldown = TimeUtil.GetCurrentTimestampInMilliseconds() + (5 * 60 * 1000); /* 5 min */ fortFromCache.CooldownCompleteTimestampMs = newCooldown; pokeStop.CooldownCompleteTimestampMs = newCooldown; if (session.SaveBallForByPassCatchFlee) { var totalBalls = (await session.Inventory.GetItems().ConfigureAwait(false)).Where(x => x.ItemId == ItemId.ItemPokeBall || x.ItemId == ItemId.ItemGreatBall || x.ItemId == ItemId.ItemUltraBall).Sum(x => x.Count); Logger.Write($"Balls required to by-pass catch flee {totalBalls}/{CatchPokemonTask.BALL_REQUIRED_TO_BYPASS_CATCHFLEE}"); } else { MSniperServiceTask.UnblockSnipe(false); } } if (fortSearch.Result == FortSearchResponse.Types.Result.InventoryFull) { await RecycleItemsTask.Execute(session, cancellationToken).ConfigureAwait(false); _storeRi = 1; } if (session.LogicSettings.UsePokeStopLimit) { session.Stats.AddPokestopTimestamp(DateTime.Now.Ticks); session.EventDispatcher.Send(new PokestopLimitUpdate(session.Stats.GetNumPokestopsInLast24Hours(), session.LogicSettings.PokeStopLimit)); } //add pokeStops to Map OnLootPokestopEvent(pokeStop); //end pokeStop to Map break; //Continue with program as loot was succesfull. } } while (fortTry < retryNumber - zeroCheck); //Stop trying if softban is cleaned earlier or if 40 times fort looting failed. if (manager.AllowMultipleBot()) { if (fortTry >= retryNumber - zeroCheck) { softbanCount++; //only check if PokestopSoftbanCount > 0 if (MultipleBotConfig.IsMultiBotActive(session.LogicSettings, manager) && session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount > 0 && session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount <= softbanCount && TinyIoCContainer.Current.Resolve <MultiAccountManager>().AllowSwitch()) { softbanCount = 0; //Activate switcher by pokestop throw new ActiveSwitchByRuleException() { MatchedRule = SwitchRules.PokestopSoftban, ReachedValue = session.LogicSettings.MultipleBotConfig.PokestopSoftbanCount }; } } } else { softbanCount = 0; //reset softban count } if (session.LogicSettings.RandomlyPauseAtStops && !doNotRetry) { if (++_randomStop >= _randomNumber) { _randomNumber = _rc.Next(4, 11); _randomStop = 0; int randomWaitTime = _rc.Next(30, 120); await Task.Delay(randomWaitTime, cancellationToken).ConfigureAwait(false); } } }
private List<List<int>> selection(FortData[] pokeStops, List<List<int>> population, double walkingSpeedInKilometersPerHour) { List<List<int>> listSelection = new List<List<int>>(); int sumPop = 0; List<int> fittnes = new List<int>(); for (int c = 0; c < population.Count; ++c) { var temp = calcFitness(ref pokeStops, population[c], walkingSpeedInKilometersPerHour); sumPop += temp; fittnes.Add(temp); } List<int> fittnesSorted = new List<int>(fittnes); fittnesSorted.Sort(); if (sumPop < 2) return listSelection; Random rnd = new Random(); int selcetedChr = -1; do { var tempIndex = rnd.Next(0, sumPop); int tempSumPop = 0; for (int c = fittnesSorted.Count - 1; c > 0; --c) { tempSumPop += fittnesSorted[c]; if (tempSumPop > tempIndex) { var tempSelcetedChr = fittnes.FindIndex(x => x == fittnesSorted[c]); if (tempSelcetedChr != selcetedChr && !(tempSelcetedChr < 0)) { selcetedChr = tempSelcetedChr; listSelection.Add(population[selcetedChr]); break; } } } } while (listSelection.Count < 2); return listSelection; }
//add delegate event private static void OnLootPokestopEvent(FortData pokestop) { LootPokestopEvent?.Invoke(pokestop); }
private double calcTime(ref FortData[] pokeStops, List<int> _chromosome, double walkingSpeedInKilometersPerHour) { double time = 0.0; for (int i = 0; i < _chromosome.Count - 1; ++i) { double distance = DistanceBetween2Coordinates(pokeStops[_chromosome[i]].Latitude, pokeStops[_chromosome[i]].Longitude, pokeStops[_chromosome[i + 1]].Latitude, pokeStops[_chromosome[i + 1]].Longitude); if (distance <= 40) { time += distance / Logic.SpeedDownTo; } else { time += distance * 3.6 / walkingSpeedInKilometersPerHour; } } return time; }
private async Task CatchNearbyPokemon(FortData fortData, bool isSniping) { var pokemon = _map.GetNearbyPokemonClosestFirst().GetAwaiter().GetResult().DistinctBy(i => i.SpawnPointId).ToList(); if (pokemon.Any()) { var pokemonList = string.Join(", ", pokemon.Select(x => x.PokemonId).ToArray()); logger.Info($"{pokemon.Count()} Pokemon found: {pokemonList}"); } if (fortData?.LureInfo != null && fortData.LureInfo.ActivePokemonId != PokemonId.Missingno) { var encounterId = fortData.LureInfo.EncounterId; var encounter = await _encounter.EncounterPokemonLure(encounterId, fortData.Id); if (encounter.Result == DiskEncounterResponse.Types.Result.Success) { if (isSniping) await _navigation.TeleportToPokestop(fortData); await _encounter.CatchPokemon(encounterId, fortData.Id, encounter, encounter.PokemonData.PokemonId); } } var taskList = new List<Task>(); foreach (var mapPokemon in pokemon) { if (_settings.UsePokemonToNotCatchFilter && _settings.PokemonsNotToCatch.Contains(mapPokemon.PokemonId)) { continue; } var encounter = await _encounter.EncounterPokemonAsync(mapPokemon); if (encounter.Status == EncounterResponse.Types.Status.EncounterSuccess) { taskList.Add(new Task(async () => { await _encounter.CatchPokemon(encounter, mapPokemon); })); } else { if (encounter.Status != EncounterResponse.Types.Status.EncounterAlreadyHappened) logger.Warn($"Unable to catch pokemon. Reason: {encounter.Status}"); } } if (isSniping) await _navigation.TeleportToPokestop(fortData); var arrayTasks = taskList.ToArray(); arrayTasks.ForEach(x => x.Start()); Task.WaitAll(arrayTasks); }