public MessageReaderJob(OGameClient client) { _client = client; client.OnResponseReceived += ClientOnOnResponseReceived; ExecutionInterval = TimeSpan.FromSeconds(10); }
private static FarmCommand Farm(OGameClient client, Config config, IFarmingStrategy strategy, NameValueCollection parameters) { int range; if (!int.TryParse(parameters["range"], out range)) { range = config.Farming.DefaultRange; } int planetId = 0; if (parameters["cp"] != null) { if (!int.TryParse(parameters["cp"], out planetId)) { planetId = 0; } } FarmCommand bot = new FarmCommand() { PlanetId = planetId, Range = range, Strategy = strategy, }; return(bot); }
public static FleetComposition ParseFleetInfoTable(OGameClient client, HtmlNode fleetInfoContainer) { HtmlNode fleetInfoTable = fleetInfoContainer.SelectSingleNode(".//table[@class='fleetinfo']"); Debug.Assert(fleetInfoTable != null); Dictionary <string, ShipType> revMapShips = client.StringProvider.GetReverseMap <ShipType>(); Dictionary <string, ResourceType> revMapResources = client.StringProvider.GetReverseMap <ResourceType>(); FleetComposition res = new FleetComposition(); Resources resources = new Resources(); HtmlNodeCollection rows = fleetInfoTable.SelectNodes(".//tr"); foreach (HtmlNode row in rows) { HtmlNodeCollection tds = row.SelectNodes(".//td"); if (tds?.Count != 2) { continue; } string name = tds[0].InnerText.Trim().TrimEnd(':'); int count = int.Parse(tds[1].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture); ShipType asShip; ResourceType asResource; if (revMapShips.TryGetValue(name, out asShip)) { res.Ships.AddOrUpdate(asShip, () => count, (type, i) => i + count); } else if (revMapResources.TryGetValue(name, out asResource)) { if (asResource == ResourceType.Metal) { resources.Metal += count; } else if (asResource == ResourceType.Crystal) { resources.Crystal += count; } else if (asResource == ResourceType.Deuterium) { resources.Deuterium += count; } } } res.Resources = resources; return(res); }
public SessionKeepAliveJob(OGameClient client, SessionKeepAliveMode mode, int planetId) { _client = client; ExecutionInterval = TimeSpan.FromMinutes(5); using (BotDb db = new BotDb()) { _planets = db.Planets.Where(p => p.PlanetId != null).Select(p => p.PlanetId.Value).ToList(); } Mode = mode; PlanetId = planetId; }
public ApiImporterJob(OGameClient client, DirectoryInfo baseDir) { _client = client; _baseDir = baseDir; if (!_baseDir.Exists) { _baseDir.Create(); _baseDir.Refresh(); } ExecutionInterval = TimeSpan.FromHours(1); }
public ScannerJob(OGameClient client, SystemCoordinate from, SystemCoordinate to) { _client = client; _from = from; _to = to; if (_to < _from) { _from = to; _to = from; } ExecutionInterval = TimeSpan.FromMinutes(15); }
public ReadAllMessagesCommand(OGameClient client) : base(client) { }
public static void Main(string[] args) { // F**k that, it's impossible to make Mono accept certificates from OGame, at least I'm too stupid to do it apparently. if (IsRunningOnMono()) { System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); }; } if (!File.Exists("config.json")) { Console.WriteLine("Please copy config.template.json to config.json and fill it out"); return; } IExitSignal onExitSignal = null; if (IsRunningOnMono()) { onExitSignal = new UnixExitSignal(); } else { onExitSignal = new WindowsExitSignal(); } Config config = JsonConvert.DeserializeObject <Config>(File.ReadAllText("config.json")); Logger.Instance.MinimumLogLevel = config.LogLevel; Logger.Instance.IncludeTimestamp = config.LogIncludeTimestamp; Logger.Instance.Log(LogLevel.Info, $"Loaded settings, user: {config.Username}, server: {config.Server}"); // Setup OGameStringProvider stringProvider = OGameStringProvider.Load(@"Resources/strings-en.json"); CultureInfo clientServerCulture = CultureInfo.GetCultureInfo("da-DK"); var commander = new CommandBase.Commander(); // Processing OGameClient client = new OGameClient(config.Server, stringProvider, config.Username, config.Password, commander); client.Settings.ServerUtcOffset = TimeSpan.FromHours(1); client.Settings.Galaxies = 8; client.Settings.Systems = 499; client.ServerCulture = clientServerCulture; Logger.Instance.Log(LogLevel.Debug, "Prepared OGameClient"); // Savers client.RegisterSaver(new GalaxyPageSaver()); client.RegisterSaver(new EspionageReportSaver()); client.RegisterSaver(new GalaxyPageDebrisSaver()); client.RegisterSaver(new MessageSaver()); client.RegisterSaver(new PlayerPlanetSaver()); client.RegisterSaver(new GalaxyActivitySaver()); client.RegisterSaver(new HostileAttackEmailSender(config.HostileWarning.From, config.HostileWarning.To, config.HostileWarning.Server, config.HostileWarning.Login, config.HostileWarning.Password)); // Injects client.RegisterInject(new CommandsInject()); client.RegisterInject(new CargosForTransportInject()); client.RegisterInject(new PlanetExclusiveInject(client)); client.RegisterInject(new CommonInject()); client.RegisterInject(new BuildQueueInject()); client.RegisterInject(new CustomPlanetOrderInject(config.CustomOrder)); client.RegisterInject(new EventListTotalsInject()); // UA stuff client.RegisterDefaultHeader("Accept-Language", "en-GB,en;q=0.8,da;q=0.6"); client.RegisterDefaultHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); client.RegisterDefaultHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); Logger.Instance.Log(LogLevel.Debug, "Prepared user agent"); // Show details foreach (IInterventionHandler item in client.GetIntervention()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Intervention Handler: {item.GetType().FullName}"); } foreach (BaseParser item in client.GetParsers()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Parser: {item.GetType().FullName}"); } foreach (SaverBase item in client.GetSavers()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Saver: {item.GetType().FullName}"); } // Start proxy OgameClientProxy proxy = new OgameClientProxy(config.ListenAddress, config.ListenPort, client); proxy.SubstituteRoot = new Uri($"https://{config.Server}"); proxy.Start(); Logger.Instance.Log(LogLevel.Success, $"Prepared reverse proxy, visit: {proxy.ListenPrefix}"); // Kick-off client.IssueRequest(client.RequestBuilder.GetPage(Objects.Types.PageType.Overview)); // Example job ApiImporterJob job1 = new ApiImporterJob(client, new DirectoryInfo("temp")); job1.Start(); AuctionMonitor monitor = new AuctionMonitor(client); client.RegisterInject(new AuctionStatusInject(monitor)); monitor.Start(); SessionKeepAliveJob job3 = new SessionKeepAliveJob(client, config.SessionKeepaliveMode); if (config.SessionKeepaliveMode == SessionKeepAliveMode.Single) { job3.PlanetId = config.SessionKeepalivePlanet; } job3.Start(); commander.Start(); Action <int> recallAction = (fleet) => { RecallFleetCommand recall = new RecallFleetCommand() { FleetId = fleet }; recall.Run(); }; if (config.FleetToRecall > 0) { recallAction(config.FleetToRecall); Thread.Sleep(5000); return; } if (config.SystemsToScan?.Count > 0) { SystemScanner sysScanner = new SystemScanner(config.SystemsToScan.Select(z => SystemCoordinate.Parse(z))); sysScanner.Start(); } SetupProxyCommands(client, config, proxy); onExitSignal.Exit += (sender, eventArgs) => { client.SaveCookies(); }; Console.TreatControlCAsInput = true; Console.ReadKey(true); client.SaveCookies(); }
public PlanetExclusiveInject(OGameClient client) { _client = client; }
public SessionKeepAliveJob(OGameClient client, SessionKeepAliveMode mode) : this(client, mode, 0) { }
public OGameAutoLoginner(OGameClient client) { _client = client; }
public AuctionMonitor(OGameClient client) { _client = client; _client.OnResponseReceived += OnResponseReceived; ExecutionInterval = TimeSpan.FromMinutes(2); }
protected CommandBase(OGameClient client) { Client = client; ParsedObjects = new List <DataObject>(); }
public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container) { HtmlDocument doc = container.ResponseHtml.Value; HtmlNode message = doc.DocumentNode.SelectSingleNode("//div[@class='detail_msg']"); if (message == null) { yield break; } OGameClient oClient = (OGameClient)client; // Message info int messageId = message.GetAttributeValue("data-msg-id", 0); MessageTabType tabType = MessageTabType.FleetsEspionage; string dateText = message.SelectSingleNode(".//span[contains(@class, 'msg_date')]").InnerText; DateTime date = DateTime.ParseExact(dateText, "dd.MM.yyyy HH:mm:ss", oClient.ServerCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); EspionageReport result = new EspionageReport { MessageId = messageId, TabType = tabType, Sent = new DateTimeOffset(date).Add(-oClient.Settings.ServerUtcOffset).ToOffset(oClient.Settings.ServerUtcOffset) }; // Establish location HtmlNode locationLink = message.SelectSingleNode(".//a[contains(@href, 'page=galaxy')]"); string locationType = locationLink.SelectSingleNode("./figure").GetCssClasses(s => s == "moon" || s == "planet").First(); CoordinateType coordinateType = locationType == "moon" ? CoordinateType.Moon : CoordinateType.Planet; result.Coordinate = Coordinate.Parse(locationLink.InnerText, coordinateType); // Parts HtmlNodeCollection partsNodesList = message.SelectNodes(".//ul[@data-type and not(./li[@class='detail_list_fail'])]"); Dictionary <string, HtmlNode> partsNodes = partsNodesList.ToDictionary(s => s.GetAttributeValue("data-type", "")); // Parts - Resources HtmlNode details; if (partsNodes.TryGetValue("resources", out details)) { HtmlNodeCollection values = details.SelectNodes(".//span[@class='res_value']"); Debug.Assert(values.Count == 4); var oneThousandAdd = oClient.ServerCulture.NumberFormat.NumberGroupSeparator + "000"; string[] vals = values.Select(s => s.InnerText .Replace("M", oneThousandAdd) .Replace("Bn", oneThousandAdd + oneThousandAdd)).ToArray(); Resources resources = new Resources { Metal = int.Parse(vals[0], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Crystal = int.Parse(vals[1], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Deuterium = int.Parse(vals[2], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture), Energy = int.Parse(vals[3], NumberStyles.AllowThousands | NumberStyles.Integer, oClient.ServerCulture) }; result.Resources = resources; result.Details |= ReportDetails.Resources; } // Parts - Ships if (partsNodes.TryGetValue("ships", out details)) { result.DetectedShips = ParseList <ShipType>(oClient, details); result.Details |= ReportDetails.Ships; } // Parts - Defense if (partsNodes.TryGetValue("defense", out details)) { result.DetectedDefence = ParseList <DefenceType>(oClient, details); result.Details |= ReportDetails.Defense; } // Parts - Buildings if (partsNodes.TryGetValue("buildings", out details)) { result.DetectedBuildings = ParseList <BuildingType>(oClient, details); result.Details |= ReportDetails.Buildings; } // Parts - Research if (partsNodes.TryGetValue("research", out details)) { result.DetectedResearch = ParseList <ResearchType>(oClient, details); result.Details |= ReportDetails.Research; } // Return yield return(result); }
public OwnPlanetCommandBase(OGameClient client) : base(client) { }
public OGameRequestBuilder(OGameClient client) { _client = client; }
private static void SetupProxyCommands(OGameClient client, Config config, OgameClientProxy proxy) { proxy.AddCommand("bid", (parameters) => { ResourceType resourceType = ResourceType.Deuterium; string resource = parameters["resource"]; if (resource != null) { if (resource.Equals("m", StringComparison.InvariantCultureIgnoreCase) || resource.Equals("metal", StringComparison.InvariantCultureIgnoreCase)) { resourceType = ResourceType.Metal; } else if (resource.Equals("c", StringComparison.InvariantCultureIgnoreCase) || resource.Equals("crystal", StringComparison.InvariantCultureIgnoreCase)) { resourceType = ResourceType.Crystal; } else if (resource.Equals("d", StringComparison.InvariantCultureIgnoreCase) || resource.Equals("deuterium", StringComparison.InvariantCultureIgnoreCase)) { resourceType = ResourceType.Deuterium; } } BidAuctionCommand bid = new BidAuctionCommand() { PlanetId = int.Parse(parameters["cp"]), BidResource = resourceType }; bid.Run(); }); proxy.AddCommand("transport", (parameters) => { TransportAllCommand transportAll = new TransportAllCommand() { PlanetId = int.Parse(parameters["from"]), Destination = DbHelper.GetPlanetCoordinateByCp(int.Parse(parameters["to"])) }; transportAll.Run(); }); proxy.AddCommand("readmessages", (parameters) => { (new ReadAllMessagesCommand()).Run(); }); proxy.AddCommand("scanaround", (parameters) => { int range = 60; if (parameters["range"] != null) { range = int.Parse(parameters["range"]); } new ScanAroundOwnCommand() { Range = range }.Run(); }); proxy.AddCommand("hunt", (parameters) => { IFarmingStrategy strategy = new FleetFinderStrategy() { MaxRanking = config.Farming.HuntMaximumRanking > 0 ? config.Farming.HuntMaximumRanking : 400, MinRanking = config.Farming.HuntMinimumRanking > 0 ? config.Farming.HuntMinimumRanking : 600, MoonsOnly = config.Farming.HuntMoonsOnly, ProbeCount = config.Farming.HuntProbeCount > 0 ? config.Farming.HuntProbeCount : 4 }; Farm(client, config, strategy, parameters).Run(); }); proxy.AddCommand("build", (parameters) => { BuildCommand cmd = new BuildCommand() { PlanetId = int.Parse(parameters["cp"]), BuildingToBuild = (BuildingType)int.Parse(parameters["id"]) }; cmd.Run(); }); proxy.AddCommand("fs", (parameters) => { FleetSaveCommand cmd = new FleetSaveCommand() { PlanetId = int.Parse(parameters["cp"]), ReturnTime = DateTimeOffset.Now.AddMinutes(int.Parse(parameters["in"])) }; cmd.Run(); }); proxy.AddCommand("farm", (parameters) => { IFarmingStrategy strategy = new InactiveFarmingStrategy() { MinimumCargosToSend = 2, SlotsLeaveRemaining = parameters["slots"] == null ? 1 : int.Parse(parameters["slots"]), MinimumTotalStorageLevel = 5, ResourcePriority = new Resources(1, 2, 1), MinimumRanking = config.Farming.InactiveMinimumRanking }; Farm(client, config, strategy, parameters).Run(); }); proxy.AddCommand("schedule", (parameters) => { long unixTime = 0; var runAt = parameters["at"]; var runIn = parameters["in"]; if (runAt != null) { unixTime = long.Parse(runAt); } else if (runIn != null) { int secs = 0; if (runIn.Contains('h') || runIn.Contains('m')) { // this should be a function, or maybe there's a way to use TimeSpan.ParseExact to parse this correctly int hours = 0, minutes = 0; int hIx = runIn.IndexOf('h'); int mIx = runIn.IndexOf('m'); if (hIx != -1) { hours = int.Parse(runIn.Substring(0, hIx)); } if (mIx != -1) { hIx++; minutes = int.Parse(runIn.Substring(hIx, mIx - hIx)); } secs = hours * 3600 + minutes * 60; } else { secs = int.Parse(runIn); } unixTime = DateTimeOffset.Now.AddSeconds(secs).ToUnixTimeSeconds(); } string cmd = parameters["cmd"]; parameters.Remove("cmd"); parameters.Remove("at"); parameters.Remove("in"); var command = new RunProxyCommand() { Command = cmd, Parameters = parameters }; client.Commander.Run(command, DateTimeOffset.FromUnixTimeSeconds(unixTime)); }); proxy.AddCommand("fake", (parameters) => { FakePlanetExclusive op = new FakePlanetExclusive() { PlanetId = int.Parse(parameters["cp"]) }; op.Run(); }); proxy.AddCommand("fullscan", (parameters) => new ScanCommand() { From = new SystemCoordinate(1, 1), To = new SystemCoordinate(6, 499), }.Run()); proxy.AddCommand("expedition", (parameters) => { int cp = int.Parse(parameters["cp"]); Coordinate dest; using (BotDb db = new BotDb()) { var here = db.Planets.FirstOrDefault(p => p.PlanetId == cp); dest = Coordinate.Create(here.Coordinate, 16, CoordinateType.Unknown); } SendFleetCommand cmd = new SendFleetCommand() { PlanetId = cp, Destination = dest, Mission = MissionType.Expedition }; cmd.Fleet = new FleetComposition(); cmd.Fleet.Ships[ShipType.Bomber] = 1; cmd.Fleet.Ships[ShipType.LightFighter] = 5; cmd.Fleet.Ships[ShipType.LargeCargo] = 192; cmd.Fleet.Ships[ShipType.EspionageProbe] = 1; cmd.Run(); }); proxy.AddCommand("jump", (parameters) => { int cp = int.Parse(parameters["from"]); int dest = int.Parse(parameters["to"]);; GateJumpCommand cmd = new GateJumpCommand() { PlanetId = cp, Destination = dest, Fleet = null }; cmd.Run(); }); }
public PlanetExclusiveValidator(OGameClient client) { _client = client; }
public FarmingBot(OGameClient client, SystemCoordinate startSystem, SystemCoordinate endSystem) { _client = client; _startSystem = startSystem; _endSystem = endSystem; }
public static void Main(string[] args) { if (!File.Exists("config.json")) { Console.WriteLine("Please copy config.template.json to config.json and fill it out"); return; } Config config = JsonConvert.DeserializeObject <Config>(File.ReadAllText("config.json")); Logger.Instance.Log(LogLevel.Info, $"Loaded settings, user: {config.Username}, server: {config.Server}"); // Setup OGameStringProvider stringProvider = OGameStringProvider.Load(@"Resources\strings-en.json"); CultureInfo clientServerCulture = CultureInfo.GetCultureInfo("da-DK"); // Processing OGameClient client = new OGameClient(config.Server, stringProvider, config.Username, config.Password); client.Settings.ServerUtcOffset = TimeSpan.FromHours(1); client.Settings.Galaxies = 8; client.Settings.Systems = 499; client.ServerCulture = clientServerCulture; Logger.Instance.Log(LogLevel.Debug, "Prepared OGameClient"); // Savers client.RegisterSaver(new GalaxyPageSaver()); client.RegisterSaver(new EspionageReportSaver()); client.RegisterSaver(new GalaxyPageDebrisSaver()); client.RegisterSaver(new MessageSaver()); // UA stuff client.RegisterDefaultHeader("Accept-Language", "en-GB,en;q=0.8,da;q=0.6"); client.RegisterDefaultHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); client.RegisterDefaultHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"); Logger.Instance.Log(LogLevel.Debug, "Prepared user agent"); // Show details foreach (IInterventionHandler item in client.GetIntervention()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Intervention Handler: {item.GetType().FullName}"); } foreach (BaseParser item in client.GetParsers()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Parser: {item.GetType().FullName}"); } foreach (SaverBase item in client.GetSavers()) { Logger.Instance.Log(LogLevel.Info, $"Loaded Saver: {item.GetType().FullName}"); } // Start proxy OgameClientProxy proxy = new OgameClientProxy("127.0.0.1", 9400, client); proxy.SubstituteRoot = new Uri($"https://{config.Server}"); proxy.Start(); Logger.Instance.Log(LogLevel.Warning, $"Prepared reverse proxy, visit: {proxy.ListenPrefix}"); // Kick-off client.PerformLogin(); // Example job ApiImporterJob job1 = new ApiImporterJob(client, new DirectoryInfo("temp")); job1.Start(); MessageReaderJob job2 = new MessageReaderJob(client); job2.Start(); SessionKeepAliveJob job3 = new SessionKeepAliveJob(client); job3.Start(); // Farming bot FarmingBot bot = new FarmingBot(client, SystemCoordinate.Create(6, 60), SystemCoordinate.Create(6, 100)); bot.Start(); // Work Console.ReadLine(); }
public SessionKeepAliveJob(OGameClient client) { _client = client; ExecutionInterval = TimeSpan.FromMinutes(10); }