Example #1
0
        private static void OnSnipePokemon(ISession session, string message)
        {
            var match = Regex.Match(message, "42\\[\"snipe-pokemon\",(.*)]");

            if (match != null && !string.IsNullOrEmpty(match.Value) && !string.IsNullOrEmpty(match.Groups[1].Value))
            {
                var data = JsonConvert.DeserializeObject <EncounteredEvent>(match.Groups[1].Value);

                //not your snipe item, return need more encrypt here and configuration to allow catch others item
                if (string.IsNullOrEmpty(session.LogicSettings.DataSharingConfig.DataServiceIdentification) ||
                    string.IsNullOrEmpty(data.RecieverId) ||
                    data.RecieverId.ToLower() != session.LogicSettings.DataSharingConfig.DataServiceIdentification.ToLower())
                {
                    return;
                }

                var move1 = PokemonMove.Absorb;
                var move2 = PokemonMove.Absorb;
                Enum.TryParse <PokemonMove>(data.Move1, true, out move1);
                Enum.TryParse <PokemonMove>(data.Move1, true, out move2);
                ulong encounterid = 0;
                ulong.TryParse(data.EncounterId, out encounterid);

                bool caught = CheckIfPokemonBeenCaught(data.Latitude, data.Longitude, data.PokemonId, encounterid,
                                                       session);
                if (caught)
                {
                    Logger.Write("[SNIPE IGNORED] - Your snipe pokemon has already been cautgh by bot",
                                 PoGo.NecroBot.Logic.Logging.LogLevel.Sniper);
                    return;
                }

                MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                {
                    UniqueIdentifier = data.EncounterId,
                    Latitude         = data.Latitude,
                    Longitude        = data.Longitude,
                    EncounterId      = encounterid,
                    SpawnPointId     = data.SpawnPointId,
                    Level            = data.Level,
                    PokemonId        = (short)data.PokemonId,
                    Iv          = data.IV,
                    Move1       = move1,
                    ExpiredTime = data.ExpireTimestamp,
                    Move2       = move2
                }, true);
            }
        }
Example #2
0
        private void btnAddCoord_Click(object sender, RoutedEventArgs e)
        {
            var model   = (SnipeListViewModel)DataContext;
            var current = model.ManualSnipe;

            Task.Run(() =>
            {
                MSniperServiceTask.AddSnipeItem(Session, new MSniperServiceTask.MSniperInfo2()
                {
                    PokemonId = (short)current.PokemonId,
                    Latitude  = current.Latitude,
                    Longitude = current.Longitude
                }, true);
                current.Clear();
                rtbFreeText.Document.Blocks.Clear();
            });
        }
Example #3
0
 private static void onSocketMessageRecieved(ISession session, object sender, WebSocketSharp.MessageEventArgs e)
 {
     try
     {
         var match = Regex.Match(e.Data, "42\\[\"pokemon\",(.*)]");
         if (match != null && !string.IsNullOrEmpty(match.Groups[1].Value))
         {
             var data = JsonConvert.DeserializeObject <EncounteredEvent>(match.Groups[1].Value);
             data.IsRecievedFromSocket = true;
             session.EventDispatcher.Send(data);
             if (session.LogicSettings.AllowAutoSnipe)
             {
                 var move1 = PokemonMove.Absorb;
                 var move2 = PokemonMove.Absorb;
                 Enum.TryParse <PokemonMove>(data.Move1, true, out move1);
                 Enum.TryParse <PokemonMove>(data.Move1, true, out move2);
                 MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                 {
                     Latitude     = data.Latitude,
                     Longitude    = data.Longitude,
                     EncounterId  = Convert.ToUInt64(data.EncounterId),
                     SpawnPointId = data.SpawnPointId,
                     PokemonId    = (short)data.PokemonId,
                     Iv           = data.IV,
                     Move1        = move1,
                     Move2        = move2
                 });
             }
             return;
         }
         match = Regex.Match(e.Data, "42\\[\"fpm\",(.*)]");
         if (match != null && !string.IsNullOrEmpty(match.Groups[1].Value))
         {
             //var data = JsonConvert.DeserializeObject<List<Logic.Tasks.HumanWalkSnipeTask.FastPokemapItem>>(match.Groups[1].Value);
             HumanWalkSnipeTask.AddFastPokemapItem(match.Groups[1].Value);
             return;
         }
     }
     catch (Exception ex)
     {
         #if DEBUG
         Logger.Write("ERROR TO ADD SNIPE< DEBUG ONLY " + ex.Message, LogLevel.Info, ConsoleColor.Yellow);
         #endif
     }
 }
Example #4
0
        private static void OnPokemonData(ISession session, string message)
        {
            var match = Regex.Match(message, "42\\[\"pokemon\",(.*)]");

            if (match != null && !string.IsNullOrEmpty(match.Groups[1].Value))
            {
                var data = JsonConvert.DeserializeObject <EncounteredEvent>(match.Groups[1].Value);
                data.IsRecievedFromSocket = true;
                session.EventDispatcher.Send(data);
                if (session.LogicSettings.AllowAutoSnipe)
                {
                    var move1 = PokemonMove.MoveUnset;
                    var move2 = PokemonMove.MoveUnset;
                    Enum.TryParse <PokemonMove>(data.Move1, true, out move1);
                    Enum.TryParse <PokemonMove>(data.Move2, true, out move2);
                    ulong encounterid = 0;
                    ulong.TryParse(data.EncounterId, out encounterid);
                    bool caught = CheckIfPokemonBeenCaught(data.Latitude, data.Longitude,
                                                           data.PokemonId, encounterid, session);
                    if (!caught)
                    {
                        var added = MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                        {
                            UniqueIdentifier = data.EncounterId,
                            Latitude         = data.Latitude,
                            Longitude        = data.Longitude,
                            EncounterId      = encounterid,
                            SpawnPointId     = data.SpawnPointId,
                            PokemonId        = (short)data.PokemonId,
                            Iv          = data.IV,
                            Move1       = move1,
                            Move2       = move2,
                            ExpiredTime = data.ExpireTimestamp
                        })
                                    .Result;
                        if (added)
                        {
                            session.EventDispatcher.Send(new AutoSnipePokemonAddedEvent(data));
                        }
                    }
                }
            }
        }
Example #5
0
        public async Task <bool> OnCommand(ISession session, string commandText, Action <string> Callback)
        {
            var cmd = commandText.Split(' ');

            if (cmd[0].ToLower() == Command)
            {
                var       pokemonData = cmd[1].Split(',');
                PokemonId pid         = (PokemonId)Enum.Parse(typeof(PokemonId), pokemonData[0].Trim(), true);

                MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                {
                    PokemonId = (short)pid,
                    Latitude  = Convert.ToDouble(pokemonData[1].Trim()),
                    Longitude = Convert.ToDouble(pokemonData[2].Trim())
                }, true);
                //Callback("Snipe pokemon added");
                return(true);
            }
            return(false);
        }
Example #6
0
        // jjskuld - Ignore CS1998 warning for now.
        #pragma warning disable 1998
        public override async Task <bool> OnCommand(ISession session, string commandText, Action <string> callback)
        {
            var cmd = commandText.Split(' ');

            if (cmd[0].ToLower() == Command)
            {
                var       pokemonData = cmd[1].Split(',');
                PokemonId pid         = (PokemonId)Enum.Parse(typeof(PokemonId), pokemonData[0].Trim(), true);

                MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                {
                    PokemonId = (short)pid,
                    Latitude  = Convert.ToDouble(pokemonData[1].Trim()),
                    Longitude = Convert.ToDouble(pokemonData[2].Trim())
                }, true);
                callback(GetMsgHead(session, session.Profile.PlayerData.Username) + "\r\n\r\n");
                return(true);
            }
            return(false);
        }
Example #7
0
        private void SnipeGrid_OnSnipePokemon(SnipePokemonViewModel selected, bool all)
        {
            var data = selected.Ref as EncounteredEvent;

            Task.Run(async() =>
            {
                if (all)
                {
                    Session.EventDispatcher.Send(new AllBotSnipeEvent(data.EncounterId));
                }
                ;

                var move1 = PokemonMove.MoveUnset;
                var move2 = PokemonMove.MoveUnset;
                Enum.TryParse(data.Move1, true, out move1);
                Enum.TryParse(data.Move2, true, out move2);
                ulong encounterid = 0;
                ulong.TryParse(data.EncounterId, out encounterid);
                bool caught = BotDataSocketClient.CheckIfPokemonBeenCaught(data.Latitude, data.Longitude, data.PokemonId, encounterid, Session);
                if (!caught)
                {
                    await MSniperServiceTask.AddSnipeItem(Session, new MSniperServiceTask.MSniperInfo2()
                    {
                        Latitude     = data.Latitude,
                        Longitude    = data.Longitude,
                        EncounterId  = encounterid,
                        SpawnPointId = data.SpawnPointId,
                        PokemonId    = (short)data.PokemonId,
                        Iv           = data.IV,
                        Move1        = move1,
                        Move2        = move2,
                        ExpiredTime  = data.ExpireTimestamp
                    }, true);
                }
            });
        }
Example #8
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            if (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write("Migrating existing json confix to excel config, please check the config.xlsm in your config folder");

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot && _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START.");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername}");
                    index++;
                }
                ;

                char select = ' ';
                do
                {
                    select = Console.ReadKey(true).KeyChar;
                    Console.WriteLine(select);
                    select = Char.ToUpper(select);
                }while (!availableOption.Contains(select));

                var bot = _session.Accounts[select - 65];

                _session.ResetSessionToWithNextBot(bot);
            }
            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe && _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session, _session.CancellationTokenSource.Token);// that need to keep data  live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            QuitEvent.WaitOne();
        }
Example #9
0
        //TODO : Need add BotManager to manage all feature related to multibot,
        public bool ReInitSessionWithNextBot(AuthConfig bot = null, double lat = 0, double lng = 0, double att = 0)
        {
            this.CatchBlockTime = DateTime.Now; //remove any block
            MSniperServiceTask.BlockSnipe();
            var currentAccount = this.accounts.FirstOrDefault(
                x => (x.AuthType == AuthType.Ptc && x.PtcUsername == this.Settings.PtcUsername) ||
                (x.AuthType == AuthType.Google && x.GoogleUsername == this.Settings.GoogleUsername));

            if (LoggedTime != DateTime.MinValue)
            {
                currentAccount.RuntimeTotal += (DateTime.Now - LoggedTime).TotalMinutes;
            }

            this.accounts = this.accounts.OrderByDescending(p => p.RuntimeTotal).ToList();
            var first = this.accounts.First();

            if (first.RuntimeTotal >= 100000)
            {
                first.RuntimeTotal = this.accounts.Min(p => p.RuntimeTotal);
            }
            this.Forts.Clear();
            this.VisibleForts.Clear();
            var nextBot = bot != null
                ? bot
                : this.accounts.LastOrDefault(p => p != currentAccount && p.ReleaseBlockTime < DateTime.Now);

            if (nextBot != null)
            {
                Logger.Write($"Switching to {nextBot.GoogleUsername}{nextBot.PtcUsername}...");
                string body = "";

                File.Delete("runtime.log");
                List <string> logs = new List <string>();

                foreach (var item in this.Accounts)
                {
                    int day  = (int)item.RuntimeTotal / 1440;
                    int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                    int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);

                    body = body + $"{item.GoogleUsername}{item.PtcUsername}     {day:00}:{hour:00}:{min:00}:00\r\n";
                    logs.Add($"{item.GoogleUsername}{item.PtcUsername};{item.RuntimeTotal}");
                }
                File.AppendAllLines("runtime.log", logs);

                #pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
                SendNotification(this, $"Account changed to {nextBot.GoogleUsername}{nextBot.PtcUsername}", body);
                #pragma warning restore 4014

                this.Settings.AuthType         = nextBot.AuthType;
                this.Settings.GooglePassword   = nextBot.GooglePassword;
                this.Settings.GoogleUsername   = nextBot.GoogleUsername;
                this.Settings.PtcPassword      = nextBot.PtcPassword;
                this.Settings.PtcUsername      = nextBot.PtcUsername;
                this.Settings.DefaultAltitude  = att == 0 ? this.Client.CurrentAltitude : att;
                this.Settings.DefaultLatitude  = lat == 0 ? this.Client.CurrentLatitude : lat;
                this.Settings.DefaultLongitude = lng == 0 ? this.Client.CurrentLongitude : lng;
                this.Stats = new SessionStats(this);
                this.Reset(this.Settings, this.LogicSettings);
                //CancellationTokenSource.Cancel();
                this.CancellationTokenSource = new CancellationTokenSource();

                this.EventDispatcher.Send(new BotSwitchedEvent()
                {
                });

                if (this.LogicSettings.MultipleBotConfig.DisplayList)
                {
                    foreach (var item in this.accounts)
                    {
                        Logger.Write($"{item.PtcUsername}{item.GoogleUsername} \tRuntime : {item.RuntimeTotal:0.00} min ");
                    }
                }
            }
            else
            {
                var nextRelease = this.accounts.Min(x => (x.ReleaseBlockTime - DateTime.Now).TotalMinutes);

                #pragma warning disable 4014 // added to get rid of compiler warning. Remove this if async code is used below.
                SendNotification(this, "All accounts are being blocked", $"None of yours account available to switch, bot will sleep for {nextRelease} mins until next acount available to run", true);
                #pragma warning restore 4014

                Task.Delay((int)nextRelease * 60 * 1000).Wait();
            }
            return(nextBot != null);
        }
Example #10
0
        //TODO : Need add BotManager to manage all feature related to multibot,
        public bool ReInitSessionWithNextBot(Account bot = null, double lat = 0, double lng = 0, double att = 0)
        {
            CatchBlockTime = DateTime.Now; //remove any block
            MSniperServiceTask.BlockSnipe();
            VisibleForts.Clear();
            Forts.Clear();

            var manager = TinyIoCContainer.Current.Resolve <MultiAccountManager>();
            var session = TinyIoCContainer.Current.Resolve <ISession>();
            var nextBot = manager.GetSwitchableAccount(bot);
            var Account = !string.IsNullOrEmpty(nextBot.Nickname) ? nextBot.Nickname : nextBot.Username;
            var TotXP   = 0;

            for (int i = 0; i < nextBot.Level + 1; i++)
            {
                TotXP = TotXP + Statistics.GetXpDiff(i);
            }

            long?XP = nextBot.CurrentXp;

            if (XP == null)
            {
                XP = 0;
            }
            long?SD = nextBot.Stardust;

            if (SD == null)
            {
                SD = 0;
            }
            long?Lvl = nextBot.Level;

            if (Lvl == null)
            {
                Lvl = 0;
            }
            var NLevelXP = nextBot.NextLevelXp;

            if (nextBot.NextLevelXp == null)
            {
                NLevelXP = 0;
            }

            Logger.Write($"Account changed to {Account}", LogLevel.BotStats);

            if (session.LogicSettings.NotificationConfig.EnablePushBulletNotification)
            {
                PushNotificationClient.SendNotification(session, $"Account changed to", $"{Account}\n" +
                                                        $"Lvl: {Lvl}\n" +
                                                        $"XP : {XP:#,##0}({(double)XP / ((double)NLevelXP) * 100:#0.00}%)\n" +
                                                        $"SD : {SD:#,##0}", true).ConfigureAwait(false);
            }

            if (nextBot != null)
            {
                manager.SwitchAccounts(nextBot);
            }

            Settings.DefaultAltitude  = att == 0 ? Client.CurrentAltitude : att;
            Settings.DefaultLatitude  = lat == 0 ? Client.CurrentLatitude : lat;
            Settings.DefaultLongitude = lng == 0 ? Client.CurrentLongitude : lng;
            Stats = new SessionStats(this);
            Reset(Settings, LogicSettings);
            //CancellationTokenSource.Cancel();
            CancellationTokenSource = new CancellationTokenSource();

            EventDispatcher.Send(new BotSwitchedEvent(nextBot)
            {
            });

            if (LogicSettings.MultipleBotConfig.DisplayList)
            {
                manager.DumpAccountList();
            }
            return(true);
        }
Example #11
0
        //static int count = 0;
        private static void OnPokemonData(ISession session, string message)
        {
#pragma warning disable IDE0018 // Inline variable declaration - Build.Bat Error Happens if We Do
            ulong encounterid;
            var   match = Regex.Match(message, "42\\[\"pokemon\",(.*)]");
            if (match != null && !string.IsNullOrEmpty(match.Groups[1].Value))
            {
                var data = JsonConvert.DeserializeObject <EncounteredEvent>(match.Groups[1].Value);
                data.IsRecievedFromSocket = true;
                if (Math.Abs(data.Latitude) > 90 || Math.Abs(data.Longitude) > 180)
                {
                    return;
                }
                ;

                var distance    = LocationUtils.CalculateDistanceInMeters(new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude), new GeoCoordinate(data.Latitude, data.Longitude));
                var maxDistance = session.LogicSettings.EnableHumanWalkingSnipe ? (session.LogicSettings.HumanWalkingSnipeMaxDistance > 0 ? session.LogicSettings.HumanWalkingSnipeMaxDistance : 1500) : 10000;
                if (distance > maxDistance)
                {
                    return;
                }

                ulong.TryParse(data.EncounterId, out encounterid);
                if (encounterid > 0 && cache.Get(encounterid.ToString()) == null)
                {
                    cache.Add(encounterid.ToString(), DateTime.Now, DateTime.Now.AddMinutes(15));
                }

                session.EventDispatcher.Send(data);
                if (session.LogicSettings.DataSharingConfig.AutoSnipe)
                {
                    var move1 = PokemonMove.MoveUnset;
                    var move2 = PokemonMove.MoveUnset;
                    Enum.TryParse(data.Move1, true, out move1);
                    Enum.TryParse(data.Move2, true, out move2);

                    bool caught = CheckIfPokemonBeenCaught(data.Latitude, data.Longitude,
                                                           data.PokemonId, encounterid, session);
                    if (!caught)
                    {
                        var added = MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                        {
                            UniqueIdentifier = data.EncounterId,
                            Latitude         = data.Latitude,
                            Longitude        = data.Longitude,
                            EncounterId      = encounterid,
                            SpawnPointId     = data.SpawnPointId,
                            PokemonId        = (short)data.PokemonId,
                            Level            = data.Level,
                            Iv          = data.IV,
                            Move1       = move1,
                            Move2       = move2,
                            ExpiredTime = data.ExpireTimestamp
                        }).Result;
                        if (added)
                        {
                            session.EventDispatcher.Send(new AutoSnipePokemonAddedEvent(data));
                        }
                    }
                }
            }
#pragma warning restore IDE0018 // Inline variable declaration - Build.Bat Error Happens if We Do
        }
Example #12
0
        public static async Task HandleEvent(AnalyticsEvent e, ISession session)
        {
#pragma warning disable IDE0018 // Inline variable declaration - Build.Bat Error Happens if We Do
            Pokemon data = e.Data as Pokemon;
            ulong   encounterId;
            var     distance    = LocationUtils.CalculateDistanceInMeters(new GeoCoordinate(session.Client.CurrentLatitude, session.Client.CurrentLongitude), new GeoCoordinate(data.Latitude, data.Longitude));
            var     maxDistance = session.LogicSettings.EnableHumanWalkingSnipe ? (session.LogicSettings.HumanWalkingSnipeMaxDistance > 0 ? session.LogicSettings.HumanWalkingSnipeMaxDistance : 1500) : 10000;
            if (distance > maxDistance)
            {
                return;
            }

            switch (e.EventType)
            {
            case 1:
                if (ulong.TryParse(data.EncounterId, out encounterId))
                {
                    var encounteredEvent = new EncounteredEvent
                    {
                        PokemonId            = (PokemonId)data.PokemonId,
                        Latitude             = data.Latitude,
                        Longitude            = data.Longitude,
                        IV                   = data.Iv,
                        Level                = data.Level,
                        Expires              = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(data.ExpiredTime),
                        ExpireTimestamp      = data.ExpiredTime,
                        SpawnPointId         = data.SpawnPointId,
                        EncounterId          = data.EncounterId,
                        Move1                = data.Move1,
                        Move2                = data.Move2,
                        IsRecievedFromSocket = true
                    };

                    session.EventDispatcher.Send(encounteredEvent);
                    if (session.LogicSettings.DataSharingConfig.AutoSnipe)
                    {
                        var move1 = PokemonMove.MoveUnset;
                        var move2 = PokemonMove.MoveUnset;
                        Enum.TryParse(encounteredEvent.Move1, true, out move1);
                        Enum.TryParse(encounteredEvent.Move2, true, out move2);

                        var added = await MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                        {
                            UniqueIdentifier = data.EncounterId,
                            Latitude         = data.Latitude,
                            Longitude        = data.Longitude,
                            EncounterId      = encounterId,
                            SpawnPointId     = data.SpawnPointId,
                            PokemonId        = (short)data.PokemonId,
                            Level            = data.Level,
                            Iv          = data.Iv,
                            Move1       = move1,
                            Move2       = move2,
                            ExpiredTime = data.ExpiredTime
                        }).ConfigureAwait(false);

                        if (added)
                        {
                            session.EventDispatcher.Send(new AutoSnipePokemonAddedEvent(encounteredEvent));
                        }
                    }
                }
                break;

            case 2:
                MSniperServiceTask.RemoveExpiredSnipeData(session, data.EncounterId);
                break;
            }
#pragma warning restore IDE0018 // Inline variable declaration - Build.Bat Error Happens if We Do
        }
Example #13
0
        public static async Task HandleEvent(AnalyticsEvent e, ISession session)
        {
            Pokemon data = e.Data as Pokemon;

            switch (e.EventType)
            {
            case 1:
                if (ulong.TryParse(data.EncounterId, out ulong encounterId))
                {
                    var encounteredEvent = new EncounteredEvent
                    {
                        PokemonId            = (PokemonId)data.PokemonId,
                        Latitude             = data.Latitude,
                        Longitude            = data.Longitude,
                        IV                   = data.Iv,
                        Level                = data.Level,
                        Expires              = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(data.ExpiredTime),
                        ExpireTimestamp      = data.ExpiredTime,
                        SpawnPointId         = data.SpawnPointId,
                        EncounterId          = data.EncounterId,
                        Move1                = data.Move1,
                        Move2                = data.Move2,
                        IsRecievedFromSocket = true
                    };

                    session.EventDispatcher.Send(encounteredEvent);
                    if (session.LogicSettings.DataSharingConfig.AutoSnipe)
                    {
                        var move1 = PokemonMove.MoveUnset;
                        var move2 = PokemonMove.MoveUnset;
                        Enum.TryParse(encounteredEvent.Move1, true, out move1);
                        Enum.TryParse(encounteredEvent.Move2, true, out move2);

                        var added = await MSniperServiceTask.AddSnipeItem(session, new MSniperServiceTask.MSniperInfo2()
                        {
                            UniqueIdentifier = data.EncounterId,
                            Latitude         = data.Latitude,
                            Longitude        = data.Longitude,
                            EncounterId      = encounterId,
                            SpawnPointId     = data.SpawnPointId,
                            PokemonId        = (short)data.PokemonId,
                            Level            = data.Level,
                            Iv          = data.Iv,
                            Move1       = move1,
                            Move2       = move2,
                            ExpiredTime = data.ExpiredTime
                        }).ConfigureAwait(false);

                        if (added)
                        {
                            session.EventDispatcher.Send(new AutoSnipePokemonAddedEvent(encounteredEvent));
                        }
                    }
                }
                break;

            case 2:
                MSniperServiceTask.RemoveExpiredSnipeData(session, data.EncounterId);
                break;
            }
        }
Example #14
0
        public static void RunBotWithParameters(Action <ISession, StatisticsAggregator> onBotStarted, string[] args)
        {
            Application.EnableVisualStyles();
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    //_ignoreKillSwitch = false;
                    break;

                case "false":
                    //_ignoreKillSwitch = true;
                    break;
                }
            }

            bool excelConfigAllow = false;

            if (commandLine["provider"] != null && commandLine["provider"] == "excel")
            {
                excelConfigAllow = true;
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");
            var excelConfigFile   = Path.Combine(profileConfigPath, "config.xlsm");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                settings = GlobalSettings.Load(_subPath, _enableJsonValidation);
                if (excelConfigAllow)
                {
                    if (!File.Exists(excelConfigFile))
                    {
                        Logger.Write(
                            "Migrating existing json confix to excel config, please check the config.xlsm in your config folder"
                            );

                        ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                    }
                    else
                    {
                        settings = ExcelConfigHelper.ReadExcel(settings, excelConfigFile);
                    }

                    Logger.Write("Bot will run with your excel config, loading excel config");
                }
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }
            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            //Only check killswitch if use legacyAPI
            //if (settings.Auth.APIConfig.UseLegacyAPI  && (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch()))
            //    return;

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    )
                                .OrderBy(pt => pt.Distance)
                                .FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            //validation auth.config
            if (boolNeedsSetup)
            {
                AuthAPIForm form = new AuthAPIForm(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    settings.Auth.APIConfig = form.Config;
                }
            }
            else
            {
                var apiCfg = settings.Auth.APIConfig;

                if (apiCfg.UsePogoDevAPI)
                {
                    if (string.IsNullOrEmpty(apiCfg.AuthAPIKey))
                    {
                        Logger.Write(
                            "You select pogodev API but not provide API Key, please press any key to exit and correct you auth.json, \r\n The Pogodev API key call be purchased at - https://talk.pogodev.org/d/51-api-hashing-service-by-pokefarmer",
                            LogLevel.Error
                            );

                        Console.ReadKey();
                        Environment.Exit(0);
                    }
                    //TODO - test api call to valida auth key
                }
                else if (apiCfg.UseLegacyAPI)
                {
                    Logger.Write(
                        "You bot will start after 15 second, You are running bot with  Legacy API (0.45) it will increase your risk to be banned and trigger captcha. Config captcha in config.json to auto resolve them",
                        LogLevel.Warning
                        );

#if RELEASE
                    Thread.Sleep(15000);
#endif
                }
                else
                {
                    Logger.Write(
                        "At least 1 authentication method is selected, please correct your auth.json, ",
                        LogLevel.Error
                        );
                    Console.ReadKey();
                    Environment.Exit(0);
                }
            }

            _session = new Session(
                new ClientSettings(settings, elevationService), logicSettings, elevationService,
                translation
                );
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                StarterConfigForm configForm = new StarterConfigForm(_session, settings, elevationService, configFile);
                if (configForm.ShowDialog() == DialogResult.OK)
                {
                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }

                //if (GlobalSettings.PromptForSetup(_session.Translation))
                //{
                //    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                //    var fileName = Assembly.GetExecutingAssembly().Location;
                //    Process.Start(fileName);
                //    Environment.Exit(0);
                //}
                else
                {
                    GlobalSettings.Load(_subPath, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }

                if (excelConfigAllow)
                {
                    ExcelConfigHelper.MigrateFromObject(settings, excelConfigFile);
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = _session.RuntimeStatistics;

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);
            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);
            if (onBotStarted != null)
            {
                onBotStarted(_session, aggregator);
            }

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();
            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            if (_session.LogicSettings.AllowMultipleBot &&
                _session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
            {
                byte index = 0;
                Console.WriteLine();
                Console.WriteLine();
                Logger.Write("PLEASE SELECT AN ACCOUNT TO START. AUTO START AFTER 30 SEC");
                List <Char> availableOption = new List <char>();
                foreach (var item in _session.Accounts)
                {
                    var ch = (char)(index + 65);
                    availableOption.Add(ch);
                    int day  = (int)item.RuntimeTotal / 1440;
                    int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                    int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);

                    var runtime = $"{day:00}:{hour:00}:{min:00}:00";

                    Logger.Write($"{ch}. {item.GoogleUsername}{item.PtcUsername} \t\t{runtime}");
                    index++;
                }

                char     select       = ' ';
                DateTime timeoutvalue = DateTime.Now.AddSeconds(30);

                while (DateTime.Now < timeoutvalue && !availableOption.Contains(select))
                {
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo cki = Console.ReadKey();
                        select = cki.KeyChar;
                        select = Char.ToUpper(select);
                        if (!availableOption.Contains(select))
                        {
                            Console.Out.WriteLine("Please select an account from list");
                        }
                    }
                    else
                    {
                        Thread.Sleep(100);
                    }
                }

                if (availableOption.Contains(select))
                {
                    var bot = _session.Accounts[select - 65];
                    _session.ReInitSessionWithNextBot(bot);
                }
                else
                {
                    var bot = _session.Accounts.OrderBy(p => p.RuntimeTotal).First();
                    _session.ReInitSessionWithNextBot(bot);
                }
            }

            machine.AsyncStart(new VersionCheckState(), _session, _subPath, excelConfigAllow);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.EnableHumanWalkingSnipe &&
                _session.LogicSettings.HumanWalkingSnipeUseFastPokemap)
            {
                HumanWalkSnipeTask.StartFastPokemapAsync(_session,
                                                         _session.CancellationTokenSource.Token); // that need to keep data live
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
                _session.EventDispatcher.EventReceived += evt => MSniperServiceTask.AddToList(evt);
            }
            var trackFile = Path.GetTempPath() + "\\necrobot2.io";

            if (!File.Exists(trackFile) || File.GetLastWriteTime(trackFile) < DateTime.Now.AddDays(-1))
            {
                Thread.Sleep(10000);
                Thread mThread = new Thread(delegate()
                {
                    var infoForm = new InfoForm();
                    infoForm.ShowDialog();
                });
                File.WriteAllText(trackFile, DateTime.Now.Ticks.ToString());
                mThread.SetApartmentState(ApartmentState.STA);

                mThread.Start();
            }


            QuitEvent.WaitOne();
        }
Example #15
0
        //TODO : Need add BotManager to manage all feature related to multibot,
        public bool ReInitSessionWithNextBot(AuthConfig bot = null, double lat = 0, double lng = 0, double att = 0)
        {
            this.CatchBlockTime = DateTime.Now; //remove any block
            MSniperServiceTask.BlockSnipe();
            var currentAccount = this.accounts.FirstOrDefault(x => (x.AuthType == PokemonGo.RocketAPI.Enums.AuthType.Ptc && x.PtcUsername == this.Settings.PtcUsername) ||
                                                              (x.AuthType == PokemonGo.RocketAPI.Enums.AuthType.Google && x.GoogleUsername == this.Settings.GoogleUsername));

            if (LoggedTime != DateTime.MinValue)
            {
                currentAccount.RuntimeTotal += (DateTime.Now - LoggedTime).TotalMinutes;
            }

            this.accounts = this.accounts.OrderByDescending(p => p.RuntimeTotal).ToList();
            var first = this.accounts.First();

            if (first.RuntimeTotal >= 100000)
            {
                first.RuntimeTotal = this.accounts.Min(p => p.RuntimeTotal);
            }

            var nextBot = bot != null ? bot : this.accounts.LastOrDefault(p => p != currentAccount && p.ReleaseBlockTime < DateTime.Now);

            if (nextBot != null)
            {
                Logger.Write($"Switching to {nextBot.GoogleUsername}{nextBot.PtcUsername}...");
                string body = "";

                File.Delete("runtime.log");
                List <string> logs = new List <string>();

                foreach (var item in this.Accounts)
                {
                    int day  = (int)item.RuntimeTotal / 1440;
                    int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60;
                    int min  = (int)(item.RuntimeTotal - (day * 1400) - hour * 60);

                    body = body + $"{item.GoogleUsername}{item.PtcUsername}     {day:00}:{hour:00}:{min:00}:00\r\n";
                    logs.Add($"{item.GoogleUsername}{item.PtcUsername};{item.RuntimeTotal}");
                }
                File.AppendAllLines("runtime.log", logs);
                PushNotificationClient.SendNotification(this, $"Account changed to {nextBot.GoogleUsername}{nextBot.PtcUsername}", body);

                this.Settings.AuthType         = nextBot.AuthType;
                this.Settings.GooglePassword   = nextBot.GooglePassword;
                this.Settings.GoogleUsername   = nextBot.GoogleUsername;
                this.Settings.PtcPassword      = nextBot.PtcPassword;
                this.Settings.PtcUsername      = nextBot.PtcUsername;
                this.Settings.DefaultAltitude  = att == 0 ? this.Client.CurrentAltitude : att;
                this.Settings.DefaultLatitude  = lat == 0 ? this.Client.CurrentLatitude : lat;
                this.Settings.DefaultLongitude = lng == 0 ? this.Client.CurrentLongitude : lng;
                this.Stats = new SessionStats(this);
                this.Reset(this.Settings, this.LogicSettings);
                //CancellationTokenSource.Cancel();
                this.CancellationTokenSource = new CancellationTokenSource();

                this.EventDispatcher.Send(new BotSwitchedEvent()
                {
                });

                if (this.LogicSettings.MultipleBotConfig.DisplayList)
                {
                    foreach (var item in this.accounts)
                    {
                        Logger.Write($"{item.PtcUsername}{item.GoogleUsername} \tRuntime : {item.RuntimeTotal:0.00} min ");
                    }
                }
            }
            return(nextBot != null);
        }
Example #16
0
        private static void Main(string[] args)
        {
            var strCulture = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

            var culture = CultureInfo.CreateSpecificCulture("en");

            CultureInfo.DefaultThreadCurrentCulture = culture;
            Thread.CurrentThread.CurrentCulture     = culture;

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;

            Console.Title           = @"NecroBot2";
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };

            // Command line parsing
            var commandLine = new Arguments(args);

            // Look for specific arguments values
            if (commandLine["subpath"] != null && commandLine["subpath"].Length > 0)
            {
                _subPath = commandLine["subpath"];
            }
            if (commandLine["jsonvalid"] != null && commandLine["jsonvalid"].Length > 0)
            {
                switch (commandLine["jsonvalid"])
                {
                case "true":
                    _enableJsonValidation = true;
                    break;

                case "false":
                    _enableJsonValidation = false;
                    break;
                }
            }
            if (commandLine["killswitch"] != null && commandLine["killswitch"].Length > 0)
            {
                switch (commandLine["killswitch"])
                {
                case "true":
                    _ignoreKillSwitch = false;
                    break;

                case "false":
                    _ignoreKillSwitch = true;
                    break;
                }
            }

            Logger.AddLogger(new ConsoleLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new FileLogger(LogLevel.Service), _subPath);
            Logger.AddLogger(new WebSocketLogger(LogLevel.Service), _subPath);

            if (!_ignoreKillSwitch && CheckKillSwitch() || CheckMKillSwitch())
            {
                return;
            }

            var profilePath       = Path.Combine(Directory.GetCurrentDirectory(), _subPath);
            var profileConfigPath = Path.Combine(profilePath, "config");
            var configFile        = Path.Combine(profileConfigPath, "config.json");

            GlobalSettings settings;
            var            boolNeedsSetup = false;

            if (File.Exists(configFile))
            {
                // Load the settings from the config file
                // If the current program is not the latest version, ensure we skip saving the file after loading
                // This is to prevent saving the file with new options at their default values so we can check for differences
                settings = GlobalSettings.Load(_subPath, !VersionCheckState.IsLatest(), _enableJsonValidation);
            }
            else
            {
                settings = new GlobalSettings
                {
                    ProfilePath       = profilePath,
                    ProfileConfigPath = profileConfigPath,
                    GeneralConfigPath = Path.Combine(Directory.GetCurrentDirectory(), "config"),
                    ConsoleConfig     = { TranslationLanguageCode = strCulture }
                };

                boolNeedsSetup = true;
            }

            if (commandLine["latlng"] != null && commandLine["latlng"].Length > 0)
            {
                var crds = commandLine["latlng"].Split(',');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var lastPosFile = Path.Combine(profileConfigPath, "LastPos.ini");

            if (File.Exists(lastPosFile) && settings.LocationConfig.StartFromLastPosition)
            {
                var text = File.ReadAllText(lastPosFile);
                var crds = text.Split(':');
                try
                {
                    var lat = double.Parse(crds[0]);
                    var lng = double.Parse(crds[1]);
                    settings.LocationConfig.DefaultLatitude  = lat;
                    settings.LocationConfig.DefaultLongitude = lng;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            var logicSettings = new LogicSettings(settings);
            var translation   = Translation.Load(logicSettings);

            if (settings.GPXConfig.UseGpxPathing)
            {
                var xmlString = File.ReadAllText(settings.GPXConfig.GpxFile);
                var readgpx   = new GpxReader(xmlString, translation);
                var nearestPt = readgpx.Tracks.SelectMany(
                    (trk, trkindex) =>
                    trk.Segments.SelectMany(
                        (seg, segindex) =>
                        seg.TrackPoints.Select(
                            (pt, ptindex) =>
                            new
                {
                    TrackPoint = pt,
                    TrackIndex = trkindex,
                    SegIndex   = segindex,
                    PtIndex    = ptindex,
                    Latitude   = Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                    Longitude  = Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture),
                    Distance   = LocationUtils.CalculateDistanceInMeters(
                        settings.LocationConfig.DefaultLatitude,
                        settings.LocationConfig.DefaultLongitude,
                        Convert.ToDouble(pt.Lat, CultureInfo.InvariantCulture),
                        Convert.ToDouble(pt.Lon, CultureInfo.InvariantCulture)
                        )
                }
                            )
                        )
                    ).OrderBy(pt => pt.Distance).FirstOrDefault(pt => pt.Distance <= 5000);

                if (nearestPt != null)
                {
                    settings.LocationConfig.DefaultLatitude  = nearestPt.Latitude;
                    settings.LocationConfig.DefaultLongitude = nearestPt.Longitude;
                    settings.LocationConfig.ResumeTrack      = nearestPt.TrackIndex;
                    settings.LocationConfig.ResumeTrackSeg   = nearestPt.SegIndex;
                    settings.LocationConfig.ResumeTrackPt    = nearestPt.PtIndex;
                }
            }
            IElevationService elevationService = new ElevationService(settings);

            _session = new Session(new ClientSettings(settings, elevationService), logicSettings, elevationService, translation);
            Logger.SetLoggerContext(_session);

            if (boolNeedsSetup)
            {
                if (GlobalSettings.PromptForSetup(_session.Translation))
                {
                    _session = GlobalSettings.SetupSettings(_session, settings, elevationService, configFile);

                    var fileName = Assembly.GetExecutingAssembly().Location;
                    Process.Start(fileName);
                    Environment.Exit(0);
                }
                else
                {
                    GlobalSettings.Load(_subPath, false, _enableJsonValidation);

                    Logger.Write("Press a Key to continue...",
                                 LogLevel.Warning);
                    Console.ReadKey();
                    return;
                }
            }

            ProgressBar.Start("NecroBot2 is starting up", 10);

            if (settings.WebsocketsConfig.UseWebsocket)
            {
                var websocket = new WebSocketInterface(settings.WebsocketsConfig.WebSocketPort, _session);
                _session.EventDispatcher.EventReceived += evt => websocket.Listen(evt, _session);
            }

            ProgressBar.Fill(20);

            var machine = new StateMachine();
            var stats   = new Statistics();

            ProgressBar.Fill(30);
            var strVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(4);

            stats.DirtyEvent +=
                () =>
                Console.Title = $"[Necrobot2 v{strVersion}] " +
                                stats.GetTemplatedStats(
                    _session.Translation.GetTranslation(TranslationString.StatsTemplateString),
                    _session.Translation.GetTranslation(TranslationString.StatsXpTemplateString));
            ProgressBar.Fill(40);

            var aggregator = new StatisticsAggregator(stats);

            ProgressBar.Fill(50);
            var listener = new ConsoleEventListener();

            ProgressBar.Fill(60);
            var snipeEventListener = new SniperEventListener();

            _session.EventDispatcher.EventReceived += evt => listener.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => aggregator.Listen(evt, _session);
            _session.EventDispatcher.EventReceived += evt => snipeEventListener.Listen(evt, _session);

            ProgressBar.Fill(70);

            machine.SetFailureState(new LoginState());
            ProgressBar.Fill(80);

            ProgressBar.Fill(90);

            _session.Navigation.WalkStrategy.UpdatePositionEvent +=
                (lat, lng) => _session.EventDispatcher.Send(new UpdatePositionEvent {
                Latitude = lat, Longitude = lng
            });
            _session.Navigation.WalkStrategy.UpdatePositionEvent += SaveLocationToDisk;

            ProgressBar.Fill(100);

            machine.AsyncStart(new VersionCheckState(), _session, _subPath);

            try
            {
                Console.Clear();
            }
            catch (IOException)
            {
            }

            if (settings.TelegramConfig.UseTelegramAPI)
            {
                _session.Telegram = new TelegramService(settings.TelegramConfig.TelegramAPIKey, _session);
            }

            if (_session.LogicSettings.UseSnipeLocationServer ||
                _session.LogicSettings.HumanWalkingSnipeUsePogoLocationFeeder)
            {
                SnipePokemonTask.AsyncStart(_session);
            }

            if (_session.LogicSettings.DataSharingEnable)
            {
                BotDataSocketClient.StartAsync(_session);
                _session.EventDispatcher.EventReceived += evt => BotDataSocketClient.Listen(evt, _session);
            }
            settings.CheckProxy(_session.Translation);

            if (_session.LogicSettings.ActivateMSniper)
            {
                MSniperServiceTask.ConnectToService();
            }
            QuitEvent.WaitOne();
        }