From 4e129c277883d753ecbfdcc4a99a96978fd49575 Mon Sep 17 00:00:00 2001 From: versx Date: Mon, 14 Dec 2020 12:12:49 -0800 Subject: [PATCH] Refactor for loops --- src/Alarms/Alerts/DynamicReplacementEngine.cs | 16 +-- src/Bot.cs | 74 ++++--------- src/Commands/Notifications.cs | 104 ++---------------- src/Extensions/DiscordExtensions.cs | 9 +- src/Net/Webhooks/WebhookController.cs | 48 ++------ src/Program.cs | 8 +- 6 files changed, 51 insertions(+), 208 deletions(-) diff --git a/src/Alarms/Alerts/DynamicReplacementEngine.cs b/src/Alarms/Alerts/DynamicReplacementEngine.cs index d7ff3ff0..ac14d4b9 100644 --- a/src/Alarms/Alerts/DynamicReplacementEngine.cs +++ b/src/Alarms/Alerts/DynamicReplacementEngine.cs @@ -2,7 +2,6 @@ { using System; using System.Collections.Generic; - using System.Linq; using System.Text.RegularExpressions; public static class DynamicReplacementEngine @@ -19,23 +18,16 @@ public static string ReplaceText(string alarmText, IReadOnlyDictionary", value); } - //Replace IF statement blocks i.e. <#is_ditto>**Catch Pokemon:** . If value is true return value inside IF block, otherwise return an empty string. - for (var i = 0; i < keys.Count; i++) + // Replace IF statement blocks i.e. <#is_ditto>**Catch Pokemon:** . If value is true return value inside IF block, otherwise return an empty string. + foreach (var (key, value) in pkmnInfo) { - var key = keys[i]; - var value = pkmnInfo[key]; - if (bool.TryParse(value, out var result)) { placeHolder = ReplaceBlock(placeHolder, key, result); diff --git a/src/Bot.cs b/src/Bot.cs index 30a2b507..a555b4f7 100644 --- a/src/Bot.cs +++ b/src/Bot.cs @@ -92,18 +92,15 @@ public Bot(WhConfig whConfig) } // Create a DiscordClient object per Discord server in config - var keys = _whConfig.Servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, serverConfig) in _whConfig.Servers) { - var guildId = keys[i]; - var server = _whConfig.Servers[guildId]; - server.LoadDmAlerts(); + serverConfig.LoadDmAlerts(); var client = new DiscordClient(new DiscordConfiguration { AutomaticGuildSync = true, AutoReconnect = true, EnableCompression = true, - Token = server.Token, + Token = serverConfig.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true }); @@ -162,10 +159,10 @@ public Bot(WhConfig whConfig) ( new CommandsNextConfiguration { - StringPrefix = server.CommandPrefix?.ToString(), + StringPrefix = serverConfig.CommandPrefix?.ToString(), EnableDms = true, // If command prefix is null, allow for mention prefix - EnableMentionPrefix = string.IsNullOrEmpty(server.CommandPrefix), + EnableMentionPrefix = string.IsNullOrEmpty(serverConfig.CommandPrefix), // Use DSharpPlus's built-in help formatter EnableDefaultHelp = true, CaseSensitive = false, @@ -183,11 +180,11 @@ public Bot(WhConfig whConfig) commands.RegisterCommands(); commands.RegisterCommands(); commands.RegisterCommands(); - if (server.Subscriptions.Enabled) + if (serverConfig.Subscriptions.Enabled) { commands.RegisterCommands(); } - if (server.EnableCities) + if (serverConfig.EnableCities) { commands.RegisterCommands(); } @@ -219,12 +216,8 @@ public async Task Start() _logger.Info("Connecting to Discord..."); // Loop through each Discord server and attempt initial connection - var keys = _servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, client) in _servers) { - var guildId = keys[i]; - var client = _servers[guildId]; - _logger.Info($"Attempting connection to Discord server {guildId}"); await client.ConnectAsync(); await Task.Delay(1000); @@ -262,13 +255,9 @@ public async Task Stop() _logger.Info("Disconnecting from Discord..."); // Loop through each Discord server and terminate the connection - var keys = _servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, client) in _servers) { - var guildId = keys[i]; - var client = _servers[guildId]; - - _logger.Info($"Attempting connection to Discord server {guildId}"); + _logger.Info($"Attempting disconnection from Discord server {guildId}"); await client.DisconnectAsync(); await Task.Delay(1000); } @@ -907,11 +896,9 @@ private async Task CacheGuildEmojisList() { _logger.Trace($"LoadEmojis"); - var keys = _whConfig.Servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, serverConfig) in _whConfig.Servers) { - var guildId = keys[i]; - var emojiGuildId = _whConfig.Servers[guildId].EmojiGuildId; + var emojiGuildId = serverConfig.EmojiGuildId; if (!_servers.ContainsKey(guildId)) continue; @@ -921,9 +908,8 @@ private async Task CacheGuildEmojisList() var emojiGuild = configGuild.Guilds[emojiGuildId]; var emojis = await emojiGuild.GetEmojisAsync(); - for (var j = 0; j < Strings.EmojiList.Length; j++) + foreach (var name in Strings.EmojiList) { - var name = Strings.EmojiList[j]; var emoji = emojis.FirstOrDefault(x => string.Compare(x.Name, name, true) == 0); if (emoji == null) continue; @@ -944,32 +930,28 @@ private async Task OnMidnightTimer() Statistics.WriteOut(); Statistics.Instance.Reset(); - var keys = _whConfig.Servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, serverConfig) in _whConfig.Servers) { - var guildId = keys[i]; - var server = _whConfig.Servers[guildId]; - if (!_servers.ContainsKey(guildId)) { _logger.Warn($"{guildId} guild does not exist it Discord servers."); continue; } var client = _servers[guildId]; - if (server.ShinyStats.Enabled) + if (serverConfig.ShinyStats.Enabled) { _logger.Debug($"Starting Shiny Stat posting..."); - await PostShinyStats(client, guildId, server); + await PostShinyStats(client, guildId, serverConfig); } else { _logger.Debug($"Shiny Stat posting not enabled...skipping"); } - if (server.PruneQuestChannels && server.QuestChannelIds.Count > 0) + if (serverConfig.PruneQuestChannels && serverConfig.QuestChannelIds.Count > 0) { _logger.Debug($"Starting automatic quest messages cleanup..."); - await PruneQuestChannels(client, server); + await PruneQuestChannels(client, serverConfig); } else { @@ -1066,11 +1048,8 @@ private void CleanupDepartedMembers() { _logger.Trace("CleanupDepartedMembers"); - var keys = _servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, client) in _servers) { - var guildId = keys[i]; - var client = _servers[guildId]; var server = _whConfig.Servers[guildId]; if (!server.Subscriptions.Enabled) return; @@ -1121,17 +1100,8 @@ private async void UnhandledExceptionHandler(object sender, UnhandledExceptionEv if (e.IsTerminating) { - var keys = _whConfig.Servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, serverConfig) in _whConfig.Servers) { - var guildId = keys[i]; - if (!_whConfig.Servers.ContainsKey(guildId)) - { - _logger.Error($"Unable to find guild id {guildId} in server config list."); - continue; - } - var server = _whConfig.Servers[guildId]; - if (!_servers.ContainsKey(guildId)) { _logger.Error($"Unable to find guild id {guildId} in Discord server client list."); @@ -1140,10 +1110,10 @@ private async void UnhandledExceptionHandler(object sender, UnhandledExceptionEv var client = _servers[guildId]; if (client != null) { - var owner = await client.GetUserAsync(server.OwnerId); + var owner = await client.GetUserAsync(serverConfig.OwnerId); if (owner == null) { - _logger.Warn($"Unable to get owner from id {server.OwnerId}."); + _logger.Warn($"Unable to get owner from id {serverConfig.OwnerId}."); return; } diff --git a/src/Commands/Notifications.cs b/src/Commands/Notifications.cs index ae484684..3fe4deea 100644 --- a/src/Commands/Notifications.cs +++ b/src/Commands/Notifications.cs @@ -381,12 +381,8 @@ public async Task PokeMeAsync(CommandContext ctx, var areas = SubscriptionAreas.GetAreas(city, server.CityRoles); // Loop through each valid pokemon entry provided - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; - if (!MasterFile.Instance.Pokedex.ContainsKey(pokemonId)) { await ctx.TriggerTypingAsync(); @@ -543,11 +539,8 @@ public async Task PokeMeNotAsync(CommandContext ctx, var areas = SubscriptionAreas.GetAreas(city, _dep.WhConfig.Servers[guildId].CityRoles); var pokemonNames = validation.Valid.Select(x => MasterFile.Instance.Pokedex[x.Key].Name + (string.IsNullOrEmpty(x.Value) ? string.Empty : "-" + x.Value)); var error = false; - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; var subPkmn = subscription.Pokemon.FirstOrDefault(x => x.PokemonId == pokemonId && (string.IsNullOrEmpty(x.Form) || string.Compare(x.Form, form, true) == 0)); if (subPkmn == null) continue; @@ -627,11 +620,8 @@ public async Task RaidMeAsync(CommandContext ctx, } var areas = SubscriptionAreas.GetAreas(city, server.CityRoles); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; var subRaid = subscription.Raids.FirstOrDefault(x => x.PokemonId == pokemonId && string.Compare(x.Form, form, true) == 0); if (subRaid != null) { @@ -1035,11 +1025,8 @@ public async Task InvMeAsync(CommandContext ctx, } var areas = SubscriptionAreas.GetAreas(city, server.CityRoles); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - //var form = validation.Valid[pokemonId]; var subInvasion = subscription.Invasions.FirstOrDefault(x => x.RewardPokemonId == pokemonId); if (subInvasion != null) { @@ -1289,12 +1276,8 @@ public async Task PvpMeAsync(CommandContext ctx, } var areas = SubscriptionAreas.GetAreas(city, server.CityRoles); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; - if (!MasterFile.Instance.Pokedex.ContainsKey(pokemonId)) { await ctx.TriggerTypingAsync(); @@ -1693,11 +1676,8 @@ await ctx.RespondEmbed(Translator.Instance.Translate("SUCCESS_QUEST_SUBSCRIPTION var invasionAreas = await invasionInput.GetAreasResult(server.CityRoles); var validPokemonNames = string.Join(", ", invasionPokemon.Valid.Select(x => MasterFile.Instance.Pokedex[x.Key].Name)); - var keys = invasionPokemon.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in invasionPokemon.Valid) { - var pokemonId = keys[i]; - //var form = validation.Valid[pokemonId]; var subInvasion = subscription.Invasions.FirstOrDefault(x => x.RewardPokemonId == pokemonId); if (subInvasion != null) { @@ -1795,12 +1775,8 @@ private async Task, List>> AddPokemonSubscript { var subscribed = new List(); var alreadySubscribed = new List(); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; - if (!MasterFile.Instance.Pokedex.ContainsKey(pokemonId)) { await ctx.RespondEmbed(Translator.Instance.Translate("NOTIFY_INVALID_POKEMON_ID").FormatText(ctx.User.Username, pokemonId), DiscordColor.Red); @@ -1889,12 +1865,8 @@ private async Task, List>> AddPvPSubscription( { var alreadySubscribed = new List(); var subscribed = new List(); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; - if (!MasterFile.Instance.Pokedex.ContainsKey(pokemonId)) { await ctx.RespondEmbed(Translator.Instance.Translate("NOTIFY_INVALID_POKEMON_ID").FormatText(ctx.User.Username, pokemonId), DiscordColor.Red); @@ -1957,11 +1929,8 @@ private KeyValuePair, List> AddRaidSubscription(CommandCont { var alreadySubscribed = new List(); var subscribed = new List(); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; var subRaid = subscription.Raids.FirstOrDefault(x => x.PokemonId == pokemonId && string.Compare(x.Form, form, true) == 0); if (subRaid != null) { @@ -2237,11 +2206,8 @@ await ctx.RespondEmbed(Translator.Instance.Translate("SUCCESS_INVASION_SUBSCRIPT private async Task RemovePokemonSubscription(CommandContext ctx, SubscriptionObject subscription, PokemonValidation validation, List areas) { var error = false; - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; var subPkmn = subscription.Pokemon.FirstOrDefault(x => x.PokemonId == pokemonId && (string.IsNullOrEmpty(x.Form) || string.Compare(x.Form, form, true) == 0)); if (subPkmn == null) continue; @@ -2286,11 +2252,8 @@ private async Task RemovePvPSubscription(CommandContext ctx, SubscriptionObject { var error = false; var pokemonNames = validation.Valid.Select(x => MasterFile.Instance.Pokedex[x.Key].Name + (string.IsNullOrEmpty(x.Value) ? string.Empty : "-" + x.Value)); - var keys = validation.Valid.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (pokemonId, form) in validation.Valid) { - var pokemonId = keys[i]; - var form = validation.Valid[pokemonId]; var subPvP = subscription.PvP.FirstOrDefault(x => x.PokemonId == pokemonId && (string.IsNullOrEmpty(x.Form) || string.Compare(x.Form, form, true) == 0) && x.League == league); if (subPvP == null) continue; @@ -2983,51 +2946,6 @@ private static ulong ConvertMentionToUserId(string mention) return ulong.TryParse(mention, out ulong result) ? result : 0; } - /* - private PokemonValidation ValidatePokemonList(string pokemonList) - { - if (string.IsNullOrEmpty(pokemonList)) - return null; - - pokemonList = pokemonList.Replace(" ", ""); - - PokemonValidation validation; - if (pokemonList.Contains("-") && int.TryParse(pokemonList.Split('-')[0], out var startRange) && int.TryParse(pokemonList.Split('-')[1], out var endRange)) - { - //If `poke` param is a range - var range = GetListFromRange(startRange, endRange); - validation = range.ValidatePokemon(); - } - else if (Strings.PokemonGenerationRanges.Select(x => "gen" + x.Key).ToList().Contains(pokemonList)) - { - //If `poke` is pokemon generation - if (!int.TryParse(pokemonList.Replace("gen", ""), out var gen) || !Strings.PokemonGenerationRanges.ContainsKey(gen)) - { - var keys = Strings.PokemonGenerationRanges.Keys.ToList(); - var minValue = keys[0]; - var maxValue = keys[keys.Count - 1]; - return null; - } - - var genRange = Strings.PokemonGenerationRanges[gen]; - var range = GetListFromRange(genRange.Start, genRange.End); - validation = range.ValidatePokemon(); - } - else if (string.Compare(pokemonList, Strings.All, true) == 0) - { - var list = GetListFromRange(1, Strings.MaxPokemonIds); - validation = list.ValidatePokemon(); - } - else - { - //If `poke` param is a list - validation = pokemonList.Replace(" ", "").Split(',').ValidatePokemon(); - } - - return validation; - } - */ - private async Task CanExecute(CommandContext ctx) { if (!await ctx.IsDirectMessageSupported(_dep.WhConfig)) diff --git a/src/Extensions/DiscordExtensions.cs b/src/Extensions/DiscordExtensions.cs index 74f90564..6efb114d 100644 --- a/src/Extensions/DiscordExtensions.cs +++ b/src/Extensions/DiscordExtensions.cs @@ -203,14 +203,9 @@ internal static async Task IsDirectMessageSupported(this CommandContext ct public static ulong ContextToGuild(this CommandContext ctx, Dictionary servers) { - var keys = servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, client) in servers) { - var guildId = keys[i]; - if (!servers.ContainsKey(guildId)) - continue; - - if (ctx.Client.CurrentUser.Id != servers[guildId].CurrentUser.Id) + if (ctx.Client.CurrentUser.Id != client.CurrentUser.Id) continue; return guildId; diff --git a/src/Net/Webhooks/WebhookController.cs b/src/Net/Webhooks/WebhookController.cs index d9d29d53..c300b4e1 100644 --- a/src/Net/Webhooks/WebhookController.cs +++ b/src/Net/Webhooks/WebhookController.cs @@ -384,11 +384,9 @@ private void LoadAlarmsOnChange() { _logger.Trace($"WebhookManager::LoadAlarmsOnChange"); - var keys = _servers.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, serverConfig) in _servers) { - var guildId = keys[i]; - var alarmsFile = _servers[guildId].AlarmsFile; + var alarmsFile = serverConfig.AlarmsFile; var path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), alarmsFile)); var fileWatcher = new FileWatcher(path); @@ -447,12 +445,8 @@ private void ProcessPokemon(PokemonData pkmn) else Statistics.Instance.TotalReceivedPokemonWithStats++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnablePokemon) continue; @@ -566,12 +560,8 @@ private void ProcessRaid(RaidData raid) else Statistics.Instance.TotalReceivedRaids++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnableRaids) continue; @@ -692,12 +682,8 @@ private void ProcessQuest(QuestData quest) Statistics.Instance.TotalReceivedQuests++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnableQuests) continue; @@ -763,12 +749,8 @@ private void ProcessPokestop(PokestopData pokestop) Statistics.Instance.TotalReceivedPokestops++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - //Skip if EnablePokestops is disabled in the config. if (!alarms.EnablePokestops) continue; @@ -827,12 +809,8 @@ private void ProcessGym(GymData gym) Statistics.Instance.TotalReceivedGyms++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnableGyms) continue; @@ -871,12 +849,8 @@ private void ProcessGymDetails(GymDetailsData gymDetails) Statistics.Instance.TotalReceivedGyms++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnableGyms) //GymDetails continue; @@ -941,12 +915,8 @@ private void ProcessWeather(WeatherData weather) Statistics.Instance.TotalReceivedWeathers++; - var keys = _alarms.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (guildId, alarms) in _alarms) { - var guildId = keys[i]; - var alarms = _alarms[guildId]; - if (!alarms.EnableWeather) continue; diff --git a/src/Program.cs b/src/Program.cs index fe12bbe1..38cbc414 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -38,19 +38,17 @@ static async Task MainAsync(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 - var keys = arguments.Keys.ToList(); - for (var i = 0; i < keys.Count; i++) + foreach (var (key, value) in arguments) { - var key = keys[i]; switch (key.ToLower()) { case "config": case "c": - configFilePath = arguments.ContainsKey(key) ? arguments[key]?.ToString() : Strings.ConfigFileName; + configFilePath = value?.ToString() ?? Strings.ConfigFileName; break; case "name": case "n": - managerName = arguments.ContainsKey(key) ? arguments[key]?.ToString() : "Default"; + managerName = value?.ToString() ?? "Default"; break; } }