public static string GetInvasionIcon(this PokestopData pokestop, WhConfig whConfig, string style) { var iconStyleUrl = whConfig.IconStyles[style]; var url = iconStyleUrl.EndsWith('/') ? iconStyleUrl + "grunt/" : $"{iconStyleUrl}/grunt"; return($"{url}/{Convert.ToInt32(pokestop.GruntType)}.png"); }
public static string GetQuestIcon(this QuestData quest, WhConfig whConfig, string style) { var iconStyleUrl = whConfig.IconStyles[style]; var url = iconStyleUrl.EndsWith('/') ? iconStyleUrl + "rewards" : $"{iconStyleUrl}/rewards"; switch (quest.Rewards?[0].Type) { case QuestRewardType.Candy: return($"{url}/reward_{Convert.ToInt32(ItemId.Rare_Candy)}_{(quest.Rewards?[0].Info.Amount ?? 1)}.png"); case QuestRewardType.Item: return($"{url}/reward_{(int)quest.Rewards?[0].Info.Item}_{(quest.Rewards?[0].Info.Amount ?? 1)}.png"); case QuestRewardType.PokemonEncounter: return((quest.IsDitto ? 132 : quest.Rewards[0].Info.PokemonId).GetPokemonIcon(quest.Rewards?[0].Info.FormId ?? 0, quest.Rewards?[0].Info.CostumeId ?? 0, whConfig, style)); case QuestRewardType.Stardust: if ((quest.Rewards[0]?.Info?.Amount ?? 0) > 0) { return($"{url}/reward_stardust_{quest.Rewards[0].Info.Amount}.png"); } return($"{url}/reward_stardust.png"); case QuestRewardType.AvatarClothing: case QuestRewardType.Experience: case QuestRewardType.Quest: case QuestRewardType.Unset: default: return(null); } }
public DiscordEmbed GeneratePokestopMessage(DiscordClient client, WhConfig whConfig, AlarmObject alarm, string city) { var alertType = HasInvasion ? AlertMessageType.Invasions : HasLure ? AlertMessageType.Lures : AlertMessageType.Pokestops; var alert = alarm?.Alerts[alertType] ?? AlertMessage.Defaults[alertType]; var properties = GetProperties(client, whConfig, city); var eb = new DiscordEmbedBuilder { Title = DynamicReplacementEngine.ReplaceText(alert.Title, properties), Url = DynamicReplacementEngine.ReplaceText(alert.Url, properties), ImageUrl = DynamicReplacementEngine.ReplaceText(alert.ImageUrl, properties), ThumbnailUrl = DynamicReplacementEngine.ReplaceText(alert.IconUrl, properties), Description = DynamicReplacementEngine.ReplaceText(alert.Content, properties), Color = HasInvasion ? DiscordColor.Red : HasLure ? (LureType == PokestopLureType.Normal ? DiscordColor.HotPink : LureType == PokestopLureType.Glacial ? DiscordColor.CornflowerBlue : LureType == PokestopLureType.Mossy ? DiscordColor.SapGreen : LureType == PokestopLureType.Magnetic ? DiscordColor.Gray : DiscordColor.CornflowerBlue) : DiscordColor.CornflowerBlue, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = $"{(client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.Name : Strings.Creator)} | {DateTime.Now}", IconUrl = client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.IconUrl : string.Empty } }; return(eb.Build()); }
public DiscordEmbed GenerateGymMessage(DiscordClient client, WhConfig whConfig, AlarmObject alarm, GymDetailsData oldGym, string city) { var alertType = AlertMessageType.Gyms; var alert = alarm?.Alerts[alertType] ?? AlertMessage.Defaults[alertType]; var properties = GetProperties(client, whConfig, city, oldGym); var eb = new DiscordEmbedBuilder { Title = DynamicReplacementEngine.ReplaceText(alert.Title, properties), Url = DynamicReplacementEngine.ReplaceText(alert.Url, properties), ImageUrl = DynamicReplacementEngine.ReplaceText(alert.ImageUrl, properties), ThumbnailUrl = DynamicReplacementEngine.ReplaceText(alert.IconUrl, properties), Description = DynamicReplacementEngine.ReplaceText(alert.Content, properties), Color = Team == PokemonTeam.Mystic ? DiscordColor.Blue : Team == PokemonTeam.Valor ? DiscordColor.Red : Team == PokemonTeam.Instinct ? DiscordColor.Yellow : DiscordColor.LightGray, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = $"{(client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.Name : Strings.Creator)} | {DateTime.Now}", IconUrl = client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.IconUrl : string.Empty } }; return(eb.Build()); }
public static string GetRaidEggIcon(this RaidData raid, WhConfig whConfig, string style) { var iconStyleUrl = whConfig.IconStyles[style]; var url = iconStyleUrl.EndsWith('/') ? iconStyleUrl + "eggs" : $"{iconStyleUrl}/eggs"; return($"{url}/{raid.Level}.png"); }
/// <summary> /// Gets the geolocation lookup of the current <seealso cref="Location"/> object. /// </summary> /// <param name="config">Config that includes the Google Maps key and OSM Nominatim endpoint</param> /// <returns>Returns a <seealso cref="Location"/> object containing the address</returns> public Location GetAddress(WhConfig config) { var key = (Latitude, Longitude); // Check if cache already contains lat/lon tuple key, if so return it. if (_cache.ContainsKey(key)) { return(_cache[key]); } // Check if we want any reverse geocoding address Location location = null; if (!string.IsNullOrEmpty(config.GoogleMapsKey)) { location = GetGoogleAddress(City, Latitude, Longitude, config.GoogleMapsKey); } if (!string.IsNullOrEmpty(config.NominatimEndpoint)) { location = GetNominatimAddress(City, Latitude, Longitude, config.NominatimEndpoint, config.NominatimSchema); } // Check if lat/lon tuple key has not been cached already, if not add it. if (!_cache.ContainsKey(key)) { _cache.Add(key, location); } return(location); }
public static bool IsModeratorOrHigher(this ulong userId, ulong guildId, WhConfig config) { if (!config.Servers.ContainsKey(guildId)) { return(false); } var server = config.Servers[guildId]; var isAdmin = IsAdmin(userId, server.OwnerId); if (isAdmin) { return(true); } var isModerator = server.Moderators.Contains(userId); if (isModerator) { return(true); } return(false); }
/// <summary> /// Instantiate a new <see cref="WebhookController"/> class. /// </summary> /// <param name="config"><see cref="WhConfig"/> configuration class.</param> public WebhookController(WhConfig config) { _logger.Trace($"WebhookManager::WebhookManager [Config={config}, Port={config.WebhookPort}, Servers={config.Servers.Count:N0}]"); Geofences = new Dictionary <string, GeofenceItem>(); _gyms = new Dictionary <string, GymDetailsData>(); _weather = new Dictionary <long, WeatherType>(); _servers = config.Servers; _alarms = new Dictionary <ulong, AlarmList>(); foreach (var server in _servers) { if (_alarms.ContainsKey(server.Key)) { continue; } var alarms = LoadAlarms(server.Value.AlarmsFile); _alarms.Add(server.Key, alarms); } _config = config; _http = new HttpServer(_config.ListeningHost, _config.WebhookPort, _config.DespawnTimeMinimumMinutes); _http.PokemonReceived += Http_PokemonReceived; _http.RaidReceived += Http_RaidReceived; _http.QuestReceived += Http_QuestReceived; _http.PokestopReceived += Http_PokestopReceived; _http.GymReceived += Http_GymReceived; _http.GymDetailsReceived += Http_GymDetailsReceived; _http.WeatherReceived += Http_WeatherReceived; _http.IsDebug = _config.Debug; new System.Threading.Thread(LoadAlarmsOnChange).Start(); }
public SubscriptionManager(WhConfig whConfig) { _logger.Trace($"SubscriptionManager::SubscriptionManager"); _whConfig = whConfig; if (_whConfig?.Database?.Main == null) { var err = "Main database is not configured in config.json file."; _logger.Error(err); throw new NullReferenceException(err); } if (_whConfig?.Database?.Scanner == null) { var err = "Scanner database is not configured in config.json file."; _logger.Error(err); throw new NullReferenceException(err); } _connFactory = new OrmLiteConnectionFactory(_whConfig.Database.Main.ToString(), MySqlDialect.Provider); //_scanConnFactory = new OrmLiteConnectionFactory(_whConfig.Database.Scanner.ToString(), MySqlDialect.Provider); if (!CreateDefaultTables()) { _logger.Error("FAiled to create default tables"); } // Reload subscriptions every 60 seconds to account for UI changes _reloadTimer = new Timer(_whConfig.ReloadSubscriptionChangesMinutes * 60 * 1000); _reloadTimer.Elapsed += OnReloadTimerElapsed; _reloadTimer.Start(); ReloadSubscriptions(); }
public WebhookManager(WhConfig config, string alarmsFilePath) { Filters = new Filters(); Geofences = new Dictionary <string, GeofenceItem>(); _logger.Trace($"WebhookManager::WebhookManager [Config={config}, Port={config.WebhookPort}, AlarmsFilePath={alarmsFilePath}]"); GeofenceService = new GeofenceService(); _gyms = new Dictionary <string, GymDetailsData>(); _alarmsFilePath = alarmsFilePath; _alarms = LoadAlarms(_alarmsFilePath); _config = config; _http = new HttpServer(_config.WebhookPort); _http.PokemonReceived += Http_PokemonReceived; _http.RaidReceived += Http_RaidReceived; _http.QuestReceived += Http_QuestReceived; _http.PokestopReceived += Http_PokestopReceived; _http.GymReceived += Http_GymReceived; _http.GymDetailsReceived += Http_GymDetailsReceived; _http.WeatherReceived += Http_WeatherReceived; _http.IsDebug = false; _http.Start(); new System.Threading.Thread(LoadAlarmsOnChange).Start(); }
public static string GetWeatherIcon(this WeatherData weather, WhConfig whConfig, string style) { var iconStyleUrl = whConfig.IconStyles[style]; var url = iconStyleUrl.EndsWith('/') ? iconStyleUrl + "weather/" : $"{iconStyleUrl}/weather"; return($"{url}/weather_{Convert.ToInt32(weather.GameplayCondition)}.png"); }
public static string GetLureIcon(this PokestopData pokestop, WhConfig whConfig, string style) { var iconStyleUrl = whConfig.IconStyles[style]; var url = iconStyleUrl.EndsWith('/') ? iconStyleUrl + "rewards" : $"{iconStyleUrl}/rewards"; return($"{url}/reward_{Convert.ToInt32(pokestop.LureType)}_1.png"); }
private void RegisterConfigMonitor() { var path = Path.Combine(Directory.GetCurrentDirectory(), Strings.ConfigFileName); var fileWatcher = new FileWatcher(path); fileWatcher.FileChanged += (sender, e) => _whConfig = WhConfig.Load(e.FilePath); fileWatcher.Start(); }
public static bool IsModerator(this ulong userId, ulong guildId, WhConfig config) { if (!config.Servers.ContainsKey(guildId)) { return(false); } return(config.Servers[guildId].Moderators.Contains(userId)); }
public Dependencies(InteractivityModule interactivity, WebhookController whm, SubscriptionProcessor subProcessor, WhConfig whConfig, StripeService stripe) { Interactivity = interactivity; Whm = whm; SubscriptionProcessor = subProcessor; WhConfig = whConfig; Stripe = stripe; OsmManager = new OsmManager(); }
public Dependencies(InteractivityModule interactivity, WebhookManager whm, SubscriptionProcessor subProcessor, WhConfig whConfig, Translator language, StripeService stripe) { Interactivity = interactivity; Whm = whm; SubscriptionProcessor = subProcessor; WhConfig = whConfig; Language = language; Stripe = stripe; OsmManager = new OsmManager(); }
public SubscriptionManager(WhConfig whConfig) { _logger.Trace($"SubscriptionManager::SubscriptionManager"); _whConfig = whConfig; _connFactory = new OrmLiteConnectionFactory(_whConfig.ConnectionStrings.Main, MySqlDialect.Provider); _scanConnFactory = new OrmLiteConnectionFactory(_whConfig.ConnectionStrings.Scanner, MySqlDialect.Provider); CreateDefaultTables(); ReloadSubscriptions(); }
/// <summary> /// Instantiate a new <see cref="SubscriptionProcessor"/> class. /// </summary> /// <param name="servers">Discord servers dictionary</param> /// <param name="config">Configuration file</param> /// <param name="whm">Webhook controller class</param> public SubscriptionProcessor(Dictionary <ulong, DiscordClient> servers, WhConfig config, WebhookController whm) { _logger.Trace($"SubscriptionProcessor::SubscriptionProcessor"); _servers = servers; _whConfig = config; _whm = whm; _queue = new NotificationQueue(); Manager = new SubscriptionManager(_whConfig); ProcessQueue(); }
private IReadOnlyDictionary <string, string> GetProperties(WhConfig whConfig, string city) { var questMessage = this.GetQuestMessage(); var questConditions = this.GetConditions(); var questReward = this.GetReward(); var questRewardImageUrl = this.GetIconUrl(whConfig); var gmapsLink = string.Format(Strings.GoogleMaps, Latitude, Longitude); var appleMapsLink = string.Format(Strings.AppleMaps, Latitude, Longitude); var wazeMapsLink = string.Format(Strings.WazeMaps, Latitude, Longitude); var staticMapLink = Utils.PrepareStaticMapUrl(whConfig.Urls.StaticMap, this.GetIconUrl(whConfig), Latitude, Longitude); var gmapsLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? gmapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, gmapsLink); var appleMapsLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? appleMapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, appleMapsLink); var wazeMapsLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? wazeMapsLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, wazeMapsLink); //var staticMapLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? staticMapLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, staticMapLink); const string defaultMissingValue = "?"; var dict = new Dictionary <string, string> { //Main properties { "quest_task", questMessage }, { "quest_conditions", questConditions }, { "quest_reward", questReward }, { "quest_reward_img_url", questRewardImageUrl }, { "has_quest_conditions", Convert.ToString(!string.IsNullOrEmpty(questConditions)) }, { "is_ditto", Convert.ToString(IsDitto) }, { "is_shiny", Convert.ToString(IsShiny) }, //Location properties { "geofence", city ?? defaultMissingValue }, { "lat", Latitude.ToString() }, { "lng", Longitude.ToString() }, { "lat_5", Math.Round(Latitude, 5).ToString() }, { "lng_5", Math.Round(Longitude, 5).ToString() }, //Location links { "tilemaps_url", staticMapLink }, { "gmaps_url", gmapsLocationLink }, { "applemaps_url", appleMapsLocationLink }, { "wazemaps_url", wazeMapsLocationLink }, //Pokestop properties { "pokestop_id", PokestopId ?? defaultMissingValue }, { "pokestop_name", PokestopName ?? defaultMissingValue }, { "pokestop_url", PokestopUrl ?? defaultMissingValue }, //Misc properties { "br", "\r\n" } }; return(dict); }
/// <summary> /// Asynchronous main entry point /// </summary> /// <param name="args">Command line arguments</param> /// <returns></returns> static async Task MainAsync(string[] args) { // Parse command line arguments if given var arguments = CommandLine.ParseArgs(new string[] { "--", "-" }, args); var configFilePath = string.Empty; var managerName = string.Empty; // Loop through the parsed command line arguments and set the key values associated with each argument provided foreach (var(key, value) in arguments) { switch (key.ToLower()) { case "config": case "c": configFilePath = value?.ToString() ?? Strings.ConfigFileName; break; case "name": case "n": managerName = value?.ToString() ?? "Default"; break; } } configFilePath = Path.Combine(Environment.CurrentDirectory, string.IsNullOrEmpty(configFilePath) ? Strings.ConfigFileName : configFilePath); ManagerName = managerName; var logger = EventLogger.GetLogger(managerName); logger.Info(Strings.BannerAsciiText); logger.Info($"Version: {Strings.Version}"); logger.Info($".NET Runtime Version: {System.Reflection.Assembly.GetExecutingAssembly().ImageRuntimeVersion}\n"); var whConfig = WhConfig.Load(configFilePath); if (whConfig == null) { logger.Error($"Failed to load config {configFilePath}."); return; } whConfig.FileName = configFilePath; whConfig.LoadDiscordServers(); LogLevel = whConfig.LogLevel; // Start bot var bot = new Bot(new WhConfigHolder(whConfig)); await bot.Start(); // Keep the process alive Process.GetCurrentProcess().WaitForExit(); }
/// <summary> /// Gets the geolocation lookup of the current <seealso cref="Location"/> object. /// </summary> /// <param name="config">Config that includes the Google Maps key and OSM Nominatim endpoint</param> /// <returns>Returns a <seealso cref="Location"/> object containing the address</returns> public Location GetAddress(WhConfig config) { if (!string.IsNullOrEmpty(config.GoogleMapsKey)) { return(GetGoogleAddress(City, Latitude, Longitude, config.GoogleMapsKey)); } if (!string.IsNullOrEmpty(config.NominatimEndpoint)) { return(GetNominatimAddress(City, Latitude, Longitude, config.NominatimEndpoint, config.NominatimSchema)); } return(null); }
public SubscriptionProcessor(DiscordClient client, WhConfig config, WebhookManager whm)//, EmbedBuilder embedBuilder) { _logger.Trace($"SubscriptionProcessor::SubscriptionProcessor"); _client = client; _whConfig = config; _whm = whm; //_embedBuilder = embedBuilder; _queue = new NotificationQueue(); Manager = new SubscriptionManager(_whConfig); ProcessQueue(); }
public static Location GetAddress(string city, double lat, double lng, WhConfig config) { if (!string.IsNullOrEmpty(config.GoogleMapsKey)) { return(GetGoogleAddress(city, lat, lng, config.GoogleMapsKey)); } if (!string.IsNullOrEmpty(config.NominatimEndpoint)) { return(GetNominatimAddress(city, lat, lng, config.NominatimEndpoint)); } return(null); }
public static bool IsModeratorOrHigher(this ulong userId, WhConfig config) { var isAdmin = IsAdmin(userId, config.Discord.OwnerId); if (isAdmin) { return(true); } var isModerator = config.Discord.Moderators.Contains(userId); if (isModerator) { return(true); } return(false); }
private void RegisterConfigMonitor() { var path = Path.Combine(Directory.GetCurrentDirectory(), Strings.ConfigFileName); var fileWatcher = new FileWatcher(path); fileWatcher.Changed += (sender, e) => { try { _whConfig.Instance = WhConfig.Load(e.FullPath); } catch (Exception ex) { _logger.Error("Error while reloading config:"); _logger.Error(ex); } }; fileWatcher.Start(); }
/// <summary> /// Instantiate a new <see cref="WebhookController"/> class. /// </summary> /// <param name="config"><see cref="WhConfig"/> configuration class.</param> public WebhookController(WhConfig config) { _logger.Trace($"WebhookManager::WebhookManager [Config={config}, Port={config.WebhookPort}, Servers={config.Servers.Count:N0}]"); _gyms = new Dictionary <string, GymDetailsData>(); _weather = new Dictionary <long, GameplayWeather.Types.WeatherCondition>(); _servers = config.Servers; _alarms = new Dictionary <ulong, AlarmList>(); lock (_geofencesLock) Geofences = GeofenceService.LoadGeofences(Strings.GeofenceFolder); foreach (var server in _servers) { if (_alarms.ContainsKey(server.Key)) { continue; } var alarms = LoadAlarms(server.Value.AlarmsFile); _alarms.Add(server.Key, alarms); } _config = config; _http = new HttpServer(_config.ListeningHost, _config.WebhookPort, _config.DespawnTimeMinimumMinutes); _http.PokemonReceived += Http_PokemonReceived; _http.RaidReceived += Http_RaidReceived; _http.QuestReceived += Http_QuestReceived; _http.PokestopReceived += Http_PokestopReceived; _http.GymReceived += Http_GymReceived; _http.GymDetailsReceived += Http_GymDetailsReceived; _http.WeatherReceived += Http_WeatherReceived; _http.IsDebug = _config.Debug; new Thread(() => { LoadAlarmsOnChange(); LoadGeofencesOnChange(); }).Start(); }
public DiscordEmbed GenerateRaidMessage(DiscordClient client, WhConfig whConfig, AlarmObject alarm, string city, string raidImageUrl) { var alertType = PokemonId > 0 ? AlertMessageType.Raids : AlertMessageType.Eggs; var alert = alarm?.Alerts[alertType] ?? AlertMessage.Defaults[alertType]; var properties = GetProperties(client, whConfig, city); var eb = new DiscordEmbedBuilder { Title = DynamicReplacementEngine.ReplaceText(alert.Title, properties), Url = DynamicReplacementEngine.ReplaceText(alert.Url, properties), ImageUrl = DynamicReplacementEngine.ReplaceText(alert.ImageUrl, properties), ThumbnailUrl = raidImageUrl,//DynamicReplacementEngine.ReplaceText(alert.IconUrl, properties), Description = DynamicReplacementEngine.ReplaceText(alert.Content, properties), Color = Level.BuildRaidColor(), Footer = new DiscordEmbedBuilder.EmbedFooter { Text = $"{(client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.Name : Strings.Creator)} | {DateTime.Now}", IconUrl = client.Guilds.ContainsKey(whConfig.Discord.GuildId) ? client.Guilds[whConfig.Discord.GuildId]?.IconUrl : string.Empty } }; return(eb.Build()); }
public static string GetIconUrl(this QuestData quest, WhConfig config) { var iconIndex = 0; switch (quest.Rewards?[0].Type) { case QuestRewardType.AvatarClothing: break; case QuestRewardType.Candy: iconIndex = 1301; break; case QuestRewardType.Experience: iconIndex = -2; break; case QuestRewardType.Item: return(string.Format(config.Urls.QuestImage, (int)quest.Rewards?[0].Info.Item)); case QuestRewardType.PokemonEncounter: return((quest.IsDitto ? 132 : quest.Rewards[0].Info.PokemonId).GetPokemonImage(config.Urls.PokemonImage, (PokemonGender)quest.Rewards?[0].Info.GenderId, quest.Rewards?[0].Info.FormId ?? 0, quest.Rewards?[0].Info.CostumeId ?? 0)); case QuestRewardType.Quest: break; case QuestRewardType.Stardust: iconIndex = -1; break; case QuestRewardType.Unset: break; } return(string.Format(config.Urls.QuestImage, iconIndex)); }
private IReadOnlyDictionary <string, string> GetProperties(DiscordGuild guild, WhConfig whConfig, string city, bool useLure, bool useInvasion) { var lureImageUrl = IconFetcher.Instance.GetLureIcon(whConfig.Servers[guild.Id].IconStyle, LureType); var invasionImageUrl = IconFetcher.Instance.GetInvasionIcon(whConfig.Servers[guild.Id].IconStyle, GruntType); var imageUrl = useInvasion ? invasionImageUrl : useLure ? lureImageUrl : Url; var gmapsLink = string.Format(Strings.GoogleMaps, Latitude, Longitude); var appleMapsLink = string.Format(Strings.AppleMaps, Latitude, Longitude); var wazeMapsLink = string.Format(Strings.WazeMaps, Latitude, Longitude); var scannerMapsLink = string.Format(whConfig.Urls.ScannerMap, Latitude, Longitude); var staticMapLink = StaticMap.GetUrl(whConfig.Urls.StaticMap, useInvasion ? whConfig.StaticMaps["invasions"] : useLure ? whConfig.StaticMaps["lures"] : /* TODO: */ "", Latitude, Longitude, imageUrl); var gmapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, gmapsLink); var appleMapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, appleMapsLink); var wazeMapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, wazeMapsLink); var scannerMapsLocationLink = UrlShortener.CreateShortUrl(whConfig.ShortUrlApiUrl, scannerMapsLink); var address = new Location(null, city, Latitude, Longitude).GetAddress(whConfig); //var staticMapLocationLink = string.IsNullOrEmpty(whConfig.ShortUrlApiUrl) ? staticMapLink : NetUtil.CreateShortUrl(whConfig.ShortUrlApiUrl, staticMapLink); var invasion = MasterFile.Instance.GruntTypes.ContainsKey(GruntType) ? MasterFile.Instance.GruntTypes[GruntType] : null; var leaderString = Translator.Instance.Translate("grunt_" + Convert.ToInt32(GruntType)); var pokemonType = MasterFile.Instance.GruntTypes.ContainsKey(GruntType) ? Notifications.GetPokemonTypeFromString(invasion?.Type) : PokemonType.None; var invasionTypeEmoji = pokemonType == PokemonType.None ? leaderString : pokemonType.GetTypeEmojiIcons(); var invasionEncounters = GruntType > 0 ? invasion.GetPossibleInvasionEncounters() : string.Empty; var now = DateTime.UtcNow.ConvertTimeFromCoordinates(Latitude, Longitude); var lureExpireTimeLeft = now.GetTimeRemaining(LureExpireTime).ToReadableStringNoSeconds(); var invasionExpireTimeLeft = now.GetTimeRemaining(InvasionExpireTime).ToReadableStringNoSeconds(); const string defaultMissingValue = "?"; var dict = new Dictionary <string, string> { //Main properties { "has_lure", Convert.ToString(HasLure) }, { "lure_type", LureType.ToString() }, { "lure_expire_time", LureExpireTime.ToLongTimeString() }, { "lure_expire_time_24h", LureExpireTime.ToString("HH:mm:ss") }, { "lure_expire_time_left", lureExpireTimeLeft }, { "has_invasion", Convert.ToString(HasInvasion) }, { "grunt_type", invasion?.Type }, { "grunt_type_emoji", invasionTypeEmoji }, { "grunt_gender", invasion?.Grunt }, { "invasion_expire_time", InvasionExpireTime.ToLongTimeString() }, { "invasion_expire_time_24h", InvasionExpireTime.ToString("HH:mm:ss") }, { "invasion_expire_time_left", invasionExpireTimeLeft }, { "invasion_encounters", $"**Encounter Reward Chance:**\r\n" + invasionEncounters }, //Location properties { "geofence", city ?? defaultMissingValue }, { "lat", Latitude.ToString() }, { "lng", Longitude.ToString() }, { "lat_5", Latitude.ToString("0.00000") }, { "lng_5", Longitude.ToString("0.00000") }, //Location links { "tilemaps_url", staticMapLink }, { "gmaps_url", gmapsLocationLink }, { "applemaps_url", appleMapsLocationLink }, { "wazemaps_url", wazeMapsLocationLink }, { "scanmaps_url", scannerMapsLocationLink }, //Pokestop properties { "pokestop_id", PokestopId ?? defaultMissingValue }, { "pokestop_name", Name ?? defaultMissingValue }, { "pokestop_url", Url ?? defaultMissingValue }, { "lure_img_url", lureImageUrl }, { "invasion_img_url", invasionImageUrl }, { "address", address?.Address }, // Discord Guild properties { "guild_name", guild?.Name }, { "guild_img_url", guild?.IconUrl }, { "date_time", DateTime.Now.ToString() }, //Misc properties { "br", "\r\n" } }; return(dict); }
public DiscordEmbedNotification GeneratePokestopMessage(ulong guildId, DiscordClient client, WhConfig whConfig, AlarmObject alarm, string city, bool useLure, bool useInvasion) { var server = whConfig.Servers[guildId]; var alertType = useInvasion ? AlertMessageType.Invasions : useLure ? AlertMessageType.Lures : AlertMessageType.Pokestops; var alert = alarm?.Alerts[alertType] ?? server.DmAlerts?[alertType] ?? AlertMessage.Defaults[alertType]; var properties = GetProperties(client.Guilds[guildId], whConfig, city, useLure, useInvasion); var eb = new DiscordEmbedBuilder { Title = DynamicReplacementEngine.ReplaceText(alert.Title, properties), Url = DynamicReplacementEngine.ReplaceText(alert.Url, properties), ImageUrl = DynamicReplacementEngine.ReplaceText(alert.ImageUrl, properties), ThumbnailUrl = DynamicReplacementEngine.ReplaceText(alert.IconUrl, properties), Description = DynamicReplacementEngine.ReplaceText(alert.Content, properties), Color = useInvasion ? new DiscordColor(server.DiscordEmbedColors.Pokestops.Invasions) : useLure ? LureType.BuildLureColor(server) : DiscordColor.CornflowerBlue, Footer = new DiscordEmbedBuilder.EmbedFooter { Text = DynamicReplacementEngine.ReplaceText(alert.Footer?.Text, properties), IconUrl = DynamicReplacementEngine.ReplaceText(alert.Footer?.IconUrl, properties) } }; var username = DynamicReplacementEngine.ReplaceText(alert.Username, properties); var iconUrl = DynamicReplacementEngine.ReplaceText(alert.AvatarUrl, properties); var description = DynamicReplacementEngine.ReplaceText(alarm?.Description, properties); return(new DiscordEmbedNotification(username, iconUrl, description, new List <DiscordEmbed> { eb.Build() })); }