From 0a78981c9154125846536fd9470d9282e6490905 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 3 Apr 2019 10:55:03 -0400 Subject: [PATCH 01/10] Start adding localization --- .../Options/ConfigurationOptions.cs | 1 + PoGo.DiscordBot/Dto/RaidInfoDto.cs | 27 +- PoGo.DiscordBot/Modules/CleanModule.cs | 10 +- PoGo.DiscordBot/Modules/HelpModule.cs | 42 +-- PoGo.DiscordBot/Modules/InfoModule.cs | 3 +- PoGo.DiscordBot/Modules/PlayerModule.cs | 25 +- PoGo.DiscordBot/Modules/RaidModule.cs | 40 +-- PoGo.DiscordBot/Modules/RoleModule.cs | 2 +- PoGo.DiscordBot/PoGo.DiscordBot.csproj | 3 +- PoGo.DiscordBot/Resources/Global.cs.resx | 249 ++++++++++++++++++ PoGo.DiscordBot/Resources/Global.en.resx | 249 ++++++++++++++++++ .../Services/GymLocationService.cs | 2 +- .../Services/LocalizationService.cs | 35 +++ .../Services/RaidChannelService.cs | 8 + PoGo.DiscordBot/Services/UserService.cs | 15 +- 15 files changed, 637 insertions(+), 74 deletions(-) create mode 100644 PoGo.DiscordBot/Resources/Global.cs.resx create mode 100644 PoGo.DiscordBot/Resources/Global.en.resx create mode 100644 PoGo.DiscordBot/Services/LocalizationService.cs diff --git a/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs b/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs index dec4439..2b550b1 100644 --- a/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs +++ b/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs @@ -14,6 +14,7 @@ public class GuildOptions { public string Name { get; set; } public ulong Id { get; set; } + public string Language { get; set; } public bool IgnoreMention { get; set; } public string[] FreeRoles { get; set; } public ChannelOptions[] Channels { get; set; } diff --git a/PoGo.DiscordBot/Dto/RaidInfoDto.cs b/PoGo.DiscordBot/Dto/RaidInfoDto.cs index 3a7691d..25d41d9 100644 --- a/PoGo.DiscordBot/Dto/RaidInfoDto.cs +++ b/PoGo.DiscordBot/Dto/RaidInfoDto.cs @@ -1,8 +1,11 @@ using Discord; +using Microsoft.Extensions.Localization; using PoGo.DiscordBot.Configuration; +using PoGo.DiscordBot.Services; using System; using System.Collections.Generic; using System.Linq; +using System.Resources; namespace PoGo.DiscordBot.Dto { @@ -17,6 +20,10 @@ public class RaidInfoDto public const string TimeFormat = "H:mm"; public const string DateTimeFormat = "d.M.yyyy H:mm"; + public readonly static string DateWord = LocalizationService.Instance.GetStringFromResources("Date"); + + public readonly static string TimeWord = LocalizationService.Instance.GetStringFromResources("Time"); + public IUserMessage Message { get; set; } public DateTime CreatedAt { get; set; } public string BossName { get; set; } @@ -59,23 +66,23 @@ Color GetColor() embedBuilder .WithColor(GetColor()) .AddInlineField("Boss", BossName) - .AddInlineField("Kde", Location) - .AddInlineField(RaidType == RaidType.Normal ? "Čas" : "Datum", DateTimeAsString) + .AddInlineField(LocalizationService.Instance.GetStringFromResources("Where"), Location) + .AddInlineField(RaidType == RaidType.Normal ? TimeWord : DateWord, DateTimeAsString) ; - if (Players.Any()) + if (Players.Count > 0) { string playerFieldValue = Players.Count >= 10 ? PlayersToGroupString(Players.Values) : PlayersToString(Players.Values); - embedBuilder.AddField($"Hráči ({Players.Count})", playerFieldValue); + embedBuilder.AddField(LocalizationService.Instance.GetStringFromResources("Players") + $"({Players.Count})", playerFieldValue); } - if (ExtraPlayers.Any()) + if (ExtraPlayers.Count > 0) { string extraPlayersFieldValue = string.Join(" + ", ExtraPlayers.Select(t => t.Count)); - embedBuilder.AddField($"Další hráči (bez Discordu, 2. mobil atd.) ({ExtraPlayers.Sum(t => t.Count)})", extraPlayersFieldValue); + embedBuilder.AddField(LocalizationService.Instance.GetStringFromResources("OtherPlayers") + $"({ExtraPlayers.Sum(t => t.Count)})", extraPlayersFieldValue); } return embedBuilder.Build(); @@ -87,7 +94,7 @@ Color GetColor() string PlayersToGroupString(IEnumerable allPlayers) { - string TeamToString(PokemonTeam? team) => team != null ? team.ToString() : "Bez teamu"; + string TeamToString(PokemonTeam? team) => team != null ? team.ToString() : LocalizationService.Instance.GetStringFromResources("WithoutTeam"); List formatterGroupedPlayers = new List(); @@ -95,7 +102,7 @@ string PlayersToGroupString(IEnumerable allPlayers) foreach (PokemonTeam? team in teams) { var players = allPlayers.Where(t => t.Team == team).ToList(); - if (players.Any()) + if (players.Count > 0) formatterGroupedPlayers.Add($"{TeamToString(team)} ({players.Count}) - {PlayersToString(players)}"); } @@ -140,7 +147,7 @@ public static RaidInfoDto Parse(IUserMessage message) RaidInfoDto result = null; - if (embed.Fields[2].Name == "Čas") + if (embed.Fields[2].Name.Equals(TimeWord,StringComparison.OrdinalIgnoreCase)) { var time = ParseTime(embed.Fields[2].Value, message.CreatedAt.Date); if (!time.HasValue) @@ -155,7 +162,7 @@ public static RaidInfoDto Parse(IUserMessage message) DateTime = time.Value, }; } - else if (embed.Fields[2].Name == "Datum") + else if (embed.Fields[2].Name.Equals(DateWord,StringComparison.OrdinalIgnoreCase)) { var dateTime = ParseDateTime(embed.Fields[2].Value); if (!dateTime.HasValue) diff --git a/PoGo.DiscordBot/Modules/CleanModule.cs b/PoGo.DiscordBot/Modules/CleanModule.cs index 2a51813..5fa0ee1 100644 --- a/PoGo.DiscordBot/Modules/CleanModule.cs +++ b/PoGo.DiscordBot/Modules/CleanModule.cs @@ -9,7 +9,7 @@ namespace PoGo.DiscordBot.Modules public class CleanModule : ModuleBase { [Command("hardclean", RunMode = RunMode.Async)] - [Summary("Smaže všechny zprávy (omezeno počtem).")] + [Summary("DeleteAllMessagesSummary")] public async Task FullClean([Summary("Počet zpráv.")]int count = 10) { var batchMessages = AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync(count)); @@ -18,15 +18,15 @@ public async Task FullClean([Summary("Počet zpráv.")]int count = 10) } [Command("clean", RunMode = RunMode.Async)] - [Summary("Smaže tvoje zprávy (omezeno počtem).")] + [Summary("DeleteYourMessageSummary")] public async Task DeleteLastMessagesFromCurrentUser([Summary("Počet zpráv.")]int count = 5) { await DeleteMessagesAsync(Context.User.Id, count); } [Command("clean", RunMode = RunMode.Async)] - [Summary("Smaže zprávy označeného uživatele (omezeno počtem).")] - public async Task DeleteLastMessages([Summary("Uživatel.")]IUser user, + [Summary("DeleteLastMessageSummary")] + public async Task DeleteLastMessages([Summary("Uživatel.")]IUser user, [Summary("Počet zpráv.")]int count = 5) { ulong userId = user != null ? user.Id : Context.User.Id; @@ -36,7 +36,7 @@ public async Task DeleteLastMessages([Summary("Uživatel.")]IUser user, async Task DeleteMessagesAsync(ulong userId, int count) { - foreach (var messages in AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync())) + foreach (var messages in Context.Channel.GetMessagesAsync().ToEnumerable()) { var messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); if (messagesToDelete != null) diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index ba344c7..711f474 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -3,9 +3,11 @@ using Discord.Commands; using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; +using PoGo.DiscordBot.Services; using System; using System.Collections.Generic; using System.Linq; +using System.Resources; using System.Text; using System.Threading.Tasks; @@ -25,7 +27,7 @@ public HelpModule(CommandService commandService, IServiceProvider serviceProvide } [Command("help")] - [Summary("Vypíše seznam příkazů.")] + [Summary("ListCommandsSummary")] public async Task Help() { var groupCommands = new Dictionary>(); @@ -64,7 +66,7 @@ string CommandsToString(IEnumerable commands) => foreach (var c in groupCommands.OrderBy(t => t.Key)) { - if (c.Key == string.Empty) continue; + if (c.Key?.Length == 0) continue; // future hint for division // c.Value.Count / MaxCommandsPerPage > 1 ... then divide it into N pages @@ -79,11 +81,12 @@ string CommandsToString(IEnumerable commands) => currentPageCommands.AddRange(c.Value); } - if (currentPageCommands.Any()) + if (currentPageCommands.Count > 0) commandPages.Add(currentPageCommands); var pages = commandPages.Select(CommandsToString).ToList(); if (pages.Count > 1) + { await PagedReplyAsync(new PaginatedMessage { Color = Color.Blue, @@ -93,10 +96,11 @@ await PagedReplyAsync(new PaginatedMessage DisplayInformationIcon = false, Timeout = TimeSpan.FromMinutes(1), }, - Title = "Dostupné příkazy", + Title = LocalizationService.Instance.GetStringFromResources("AvailableCommands"), Pages = pages, }); - else if (pages.Any()) + } + else if (pages.Count > 0) await ReplyAsync($"```{pages.First()}```"); } @@ -114,7 +118,9 @@ public async Task Help([Remainder] string command) if (!result.IsSuccess) { - await ReplyAsync($"Žádný příkaz **{command}** jsem nemohl najít."); + string reply = String.Format(LocalizationService.Instance.GetStringFromResources("CommandNotFound"),command); + + await ReplyAsync(reply); return; } @@ -130,13 +136,13 @@ string ParameterInfoToDetailedString(ParameterInfo info) sb.Append(info.Name); if (!string.IsNullOrEmpty(info.Summary)) - sb.Append($" - {info.Summary}"); + sb.Append($" - {LocalizationService.Instance.GetStringFromResources(info.Summary)}"); if (info.Type.IsEnum) - sb.Append($" Možné jsou jenom tyhle hodnoty ({string.Join(" | ", Enum.GetNames(info.Type))})!"); + sb.Append(LocalizationService.Instance.GetStringFromResources("PossibleValues") + $" ({string.Join(" | ", Enum.GetNames(info.Type))})!"); if (info.IsOptional) - sb.Append($" (Volitelný, výchozí hodnota je {info.DefaultValue})"); + sb.Append(LocalizationService.Instance.GetStringFromResources("Optional") + $" ({info.DefaultValue})"); return sb.ToString(); } @@ -145,11 +151,11 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) { StringBuilder sb = new StringBuilder() .Append(prefix) - .Append(ci.Aliases.First()); + .Append(ci.Aliases[0]); string FormatParameter(ParameterInfo pi) => $"<{pi.Name}>"; - if (ci.Parameters.Any()) + if (ci.Parameters.Count > 0) { var parameters = ci.Parameters.AsEnumerable(); @@ -166,26 +172,26 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) { var cmd = match.Command; StringBuilder sb = new StringBuilder() - .AppendLine($"Popis: {cmd.Summary}") + .Append(LocalizationService.Instance.GetStringFromResources("Description")).Append(':').AppendLine(cmd.Summary) .AppendLine() - .AppendLine($"Základní použití: **{CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Basic)}**"); + .Append(LocalizationService.Instance.GetStringFromResources("BasicUse")).Append(":**").Append(CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Basic)).AppendLine("**"); if (cmd.Parameters.Any(t => t.IsOptional)) - sb.AppendLine($"Plné použití: {CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Full)}"); + sb.AppendLine(LocalizationService.Instance.GetStringFromResources("FullUse") + $": {CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Full)}"); sb.AppendLine(); - if (cmd.Parameters.Any()) + if (cmd.Parameters.Count > 0) { string parameters = string.Join(", ", cmd.Parameters.Select(ParameterInfoToString)); string detailedParameters = string.Join(Environment.NewLine, cmd.Parameters.Select(ParameterInfoToDetailedString)); sb - .AppendLine($"Parametry: {parameters}") - .AppendLine("Popis parametrů:") + .Append(LocalizationService.Instance.GetStringFromResources("Parameters")).Append(": ").AppendLine(parameters) + .AppendLine(LocalizationService.Instance.GetStringFromResources("ParameterDescription")) .AppendLine(detailedParameters); } - builder.AddField($"Příkaz{(cmd.Aliases.Count > 1 ? "y" : "")}: {string.Join(", ", cmd.Aliases)}", sb); + builder.AddField(LocalizationService.Instance.GetStringFromResources("Command") + $"{(cmd.Aliases.Count > 1 ? "y" : "")}: {string.Join(", ", cmd.Aliases)}", sb); } await ReplyAsync(string.Empty, false, builder.Build()); diff --git a/PoGo.DiscordBot/Modules/InfoModule.cs b/PoGo.DiscordBot/Modules/InfoModule.cs index 77e40b5..9739f51 100644 --- a/PoGo.DiscordBot/Modules/InfoModule.cs +++ b/PoGo.DiscordBot/Modules/InfoModule.cs @@ -2,6 +2,7 @@ using Discord.Commands; using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; +using PoGo.DiscordBot.Services; using System; using System.Threading.Tasks; @@ -50,7 +51,7 @@ public async Task Contribute() [Command("donate", RunMode = RunMode.Async)] public async Task Donate() { - await ReplyAsync("V případě, že byste chtěli podpořit vývoj, tak se ozvěte Pako#3904"); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("SupportDevelopment")); } } } diff --git a/PoGo.DiscordBot/Modules/PlayerModule.cs b/PoGo.DiscordBot/Modules/PlayerModule.cs index 375585e..571a355 100644 --- a/PoGo.DiscordBot/Modules/PlayerModule.cs +++ b/PoGo.DiscordBot/Modules/PlayerModule.cs @@ -20,27 +20,26 @@ public PlayerModule(UserService userService, TeamService teamService) } [Command("team")] - [Summary("Zkontroluje zda má uživatel nastavený team. Jestliže ne, tak mu přijde zpráva s informacemi jak ho nastavit.")] + [Summary("CheckTeamSummary")] public async Task CheckTeam( - [Summary("Kontrolovaný uživatel.")]SocketGuildUser user) + [Summary("ControlledUser")]SocketGuildUser user) { await userService.CheckTeam(user); } [Command("team", RunMode = RunMode.Async)] - [Summary("Nastaví team.")] + [Summary("SetTeamSummary")] public async Task SetTeam( - [Summary("Zvolený team (roli).")]PokemonTeam team) + [Summary("SelectedTeam")]PokemonTeam team) { var contextUser = Context.User; - var user = contextUser as SocketGuildUser; - if (user == null) + if (!(contextUser is SocketGuildUser user)) return; var userTeam = userService.GetTeam(user); if (userTeam != null) { - await ReplyAsync("Už jsi v teamu."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("InTeam")); return; } @@ -51,16 +50,16 @@ public async Task SetTeam( [Command("level", RunMode = RunMode.Async)] [Alias("lvl")] [TeamPrecondition] - [Summary("Nastaví level.")] + [Summary("SetLevelSummary")] public async Task SetLevel( - [Summary("Aktuální level (1-40)")]int level) + [Summary("CurrentLevel")]int level) { if (!(Context.User is SocketGuildUser user)) return; if (!(level >= 1 && level <= 40)) { - await ReplyAsync("Asi hraješ jinou hru ... povolený level je 1-40."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("PlayAnotherGame")); return; } @@ -82,10 +81,10 @@ await user.ModifyAsync(t => } [Command("set")] - [Summary("Nastaví team a level.")] + [Summary("SetBasicInfoSummary")] public async Task SetBasicInfo( - [Summary("Zvolený team (roli).")]PokemonTeam team, - [Summary("Aktuální level (1-40).")]int level) + [Summary("SelectedTeam")]PokemonTeam team, + [Summary("CurrentLevel")]int level) { await SetTeam(team); await SetLevel(level); diff --git a/PoGo.DiscordBot/Modules/RaidModule.cs b/PoGo.DiscordBot/Modules/RaidModule.cs index 80cc809..b0a9e4e 100644 --- a/PoGo.DiscordBot/Modules/RaidModule.cs +++ b/PoGo.DiscordBot/Modules/RaidModule.cs @@ -43,23 +43,23 @@ public RaidModule(TeamService teamService, RaidService raidService, ILogger [Command("schedule", RunMode = RunMode.Async)] [Alias("s")] - [Summary("Vytvoří plánovanou raid anketu do speciálního kanálu.")] + [Summary("StartScheduledRaidSummary")] [RaidChannelPrecondition] public async Task StartScheduledRaid( - [Summary("Název bosse.")]string bossName, - [Summary("Místo.")]string location, - [Remainder][Summary("Datum (" + RaidInfoDto.DateTimeFormat + ").")]string dateTime) + [Summary("BossName")]string bossName, + [Summary("Place")]string location, + [Remainder][Summary("Date (" + RaidInfoDto.DateTimeFormat + ").")]string dateTime) { var raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); if (raidChannelBinding == null || !raidChannelBinding.AllowScheduledRaids) { - await ReplyAsync($"Z tohoto kanálu není možné vytvořit plánovanou raid anketu."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotPossible")); return; } var parsedDateTime = RaidInfoDto.ParseDateTime(dateTime); if (!parsedDateTime.HasValue) { - await ReplyAsync($"Datum není ve validním formátu ({RaidInfoDto.DateTimeFormat} 24H)."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("DateNotValid") + $"({RaidInfoDto.DateTimeFormat} 24H)."); return; } if (parsedDateTime < DateTime.Now) { - await ReplyAsync($"Vážně chceš vytvořit plánovaný raid v minulosti?"); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("PastRaid")); return; } @@ -147,7 +147,7 @@ RaidInfoDto GetRaid(int skip) [Command("time", RunMode = RunMode.Async)] [Alias("t")] - [Summary("Přenastaví čas raidu.")] + [Summary("AdjustRaidTimeSummary")] [RaidChannelPrecondition] public async Task AdjustRaidTime( [Summary("Nový čas raidu (" + RaidInfoDto.TimeFormat + ").")]string time, @@ -158,7 +158,7 @@ public async Task AdjustRaidTime( if (raid == null) { - await ReplyAsync("Raid nenalezen."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); return; } @@ -204,7 +204,7 @@ public async Task AdjustRaidBoss( if (raid == null) { - await ReplyAsync("Raid nenalezen."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); return; } @@ -235,7 +235,7 @@ public async Task MentionRaidPlayers( if (raid == null) { - await ReplyAsync("Raid nenalezen."); + await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); return; } @@ -254,7 +254,7 @@ public async Task MentionRaidPlayers( [Command("delete", RunMode = RunMode.Async)] [Alias("d")] - [Summary("Smaže raid.")] + [Summary("DeleteRaidSummary")] [RaidChannelPrecondition] public async Task DeleteRaid( [Summary("Počet anket odspodu.")] int skip = 0) @@ -269,7 +269,7 @@ public async Task DeleteRaid( var questionMessage = await ReplyAsync($"Vážně chceš smazat tenhle raid: '{raid.ToSimpleString()}'? [y]"); var responseMessage = await NextMessageAsync(); - if (responseMessage == null || responseMessage.Content.ToLower() != "y") + if (responseMessage == null || !string.Equals(responseMessage.Content, "y", StringComparison.OrdinalIgnoreCase)) return; foreach (var player in raid.Players.Values) @@ -284,7 +284,7 @@ public async Task DeleteRaid( [Command("info", RunMode = RunMode.Async)] [Alias("i")] - [Summary("Vypíše základní info o bossovi.")] + [Summary("RaidBossInfoSummary")] public async Task RaidBossInfo( [Summary("Název bosse.")] string bossName) { diff --git a/PoGo.DiscordBot/Modules/RoleModule.cs b/PoGo.DiscordBot/Modules/RoleModule.cs index 9529b39..baa9587 100644 --- a/PoGo.DiscordBot/Modules/RoleModule.cs +++ b/PoGo.DiscordBot/Modules/RoleModule.cs @@ -29,7 +29,7 @@ public RoleModule(ILogger logger, IOptions opt [Command("add")] [Alias("a")] - [Summary("Přidá uživateli roli.")] + [Summary("AddRoleSummary")] public async Task AddRole([Summary("Název role")]string roleName) { if (!(Context.User is SocketGuildUser user)) diff --git a/PoGo.DiscordBot/PoGo.DiscordBot.csproj b/PoGo.DiscordBot/PoGo.DiscordBot.csproj index b23998d..8eb85c1 100644 --- a/PoGo.DiscordBot/PoGo.DiscordBot.csproj +++ b/PoGo.DiscordBot/PoGo.DiscordBot.csproj @@ -14,10 +14,11 @@ + - + diff --git a/PoGo.DiscordBot/Resources/Global.cs.resx b/PoGo.DiscordBot/Resources/Global.cs.resx new file mode 100644 index 0000000..7ff3d11 --- /dev/null +++ b/PoGo.DiscordBot/Resources/Global.cs.resx @@ -0,0 +1,249 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Přidá uživateli roli + + + Přenastaví čas raidu + + + Dostupné příkazy + + + Čas není ve validním formátu + + + Základní použití + + + Název bosse + + + Zkontroluje zda má uživatel nastavený team. Jestliže ne, tak mu přijde zpráva s informacemi jak ho nastavit + + + Příkaz + + + Žádný příkaz **{0}** jsem nemohl najít + + + Kontrolovaný uživatel + + + Aktuální level (1-40) + + + datum + + + Datum není ve validním formátu + + + Smaže všechny zprávy (omezeno počtem) + + + Maže zprávy označeného uživatele (omezeno počtem) + + + Smaže raid. + + + Smaže tvoje zprávy (omezeno počtem) + + + Popis + + + Plné použití + + + Vypíše seznam příkazů. + + + Už jsi v teamu + + + Volitelný, výchozí hodnota je + + + Další hráči (bez Discordu, 2. mobil atd + + + Popis parametrů + + + Parametry + + + Vážně chceš vytvořit raid v minulosti? + + + Místo + + + Asi hraje jinou hru ... povolený level je 1-40 + + + Hráči + + + Možné jsou jenom tyhle hodnoty + + + Vypíše základní info o bossovi + + + Raid nenalezen. + + + Z tohoto kanálu není možné vytvořit naplánovanou raid anketu + + + Zvolený team (roli) + + + Nastaví team a level + + + Nastaví level + + + Sets the team + + + Vytvoří raid anketu do speciálního kanálu. + + + Vytvoří plánovanou raid anketu do speciálního kanálu + + + V případě, že byste chtěli podpořit vývoj, tak se ozvěte Pako#3904 + + + Čas + + + Kde + + + Bez teamu + + \ No newline at end of file diff --git a/PoGo.DiscordBot/Resources/Global.en.resx b/PoGo.DiscordBot/Resources/Global.en.resx new file mode 100644 index 0000000..d795f6e --- /dev/null +++ b/PoGo.DiscordBot/Resources/Global.en.resx @@ -0,0 +1,249 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Adds a role to the user + + + It will reset the raid time + + + Available commands + + + Time is not in valid format + + + Basic Use + + + Name of the boss. + + + Checks whether the user has a team set up. If not, he will receive a message with information on how to set it + + + Command + + + No command found {0}, I couldn't find it + + + Controlled user + + + Current Level (1-40) + + + date + + + Date is not in valid format + + + Deletes all messages (limited) + + + Deletes tagged user messages (limited) + + + Delete Raid + + + Deletes your messages (limited) + + + Description + + + Full Use + + + Lists commands. + + + You're in the team + + + Optional, default is + + + Other players (without Discord, 2nd mobile, etc.) + + + Parameter Description + + + Parameters + + + Do you really want to create a raid in the past? + + + Place + + + You probably play another game ... the allowed level is 1-40 + + + Players + + + Only these values ​​are possible + + + Lists basic boss info + + + Raid not found. + + + It is not possible to create a scheduled raid poll from this channel + + + Selected team (role) + + + Sets team and level + + + Sets the level + + + Sets the team + + + Creates a raid poll in a special channel. + + + Creates a scheduled raid poll in a special channel + + + If you would like to support the development, please contact Pako # 3904 + + + time + + + Where + + + Without Team + + \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/GymLocationService.cs b/PoGo.DiscordBot/Services/GymLocationService.cs index 0f76902..98f7eff 100644 --- a/PoGo.DiscordBot/Services/GymLocationService.cs +++ b/PoGo.DiscordBot/Services/GymLocationService.cs @@ -26,7 +26,7 @@ public GymLocationService(IOptions options) public IEnumerable Search(ulong guildId, string name) { if (!gymsInfos.TryGetValue(guildId, out var gyms)) - return null; + return default; var normalizedName = StringUtils.ToLowerWithoutDiacritics(name); return gyms diff --git a/PoGo.DiscordBot/Services/LocalizationService.cs b/PoGo.DiscordBot/Services/LocalizationService.cs new file mode 100644 index 0000000..a3427e5 --- /dev/null +++ b/PoGo.DiscordBot/Services/LocalizationService.cs @@ -0,0 +1,35 @@ +using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Resources; +using System.Text; + +namespace PoGo.DiscordBot.Services +{ + public class LocalizationService + { + protected ResourceManager resourceManager; + + private static readonly Lazy lazy + = new Lazy(() + => new LocalizationService()); + + private LocalizationService() + { + resourceManager = new ResourceManager("PoGo.DiscordBot", + Assembly.GetExecutingAssembly()); + } + + public static LocalizationService Instance + { + get + { + return lazy.Value; + } + } + + public string GetStringFromResources(String keyName) => resourceManager.GetString(keyName); + } +} diff --git a/PoGo.DiscordBot/Services/RaidChannelService.cs b/PoGo.DiscordBot/Services/RaidChannelService.cs index 9886258..2deac06 100644 --- a/PoGo.DiscordBot/Services/RaidChannelService.cs +++ b/PoGo.DiscordBot/Services/RaidChannelService.cs @@ -67,17 +67,25 @@ public bool IsKnown(ulong guildId, ulong textChannelId) => /// /// Returns raid channel for the raid poll based on the channel where the command came from. /// + /// todo: describe guildId parameter on TryGetRaidChannelBinding + /// todo: describe fromTextChannelId parameter on TryGetRaidChannelBinding public RaidChannelBindingDto TryGetRaidChannelBinding(ulong guildId, ulong fromTextChannelId) { if (guilds.TryGetValue(guildId, out var raidChannelBindings)) + { foreach (var channel in raidChannelBindings) + { if (channel.From == null || channel.From.Id == fromTextChannelId) + { return new RaidChannelBindingDto { Channel = channel.To, Mention = channel.Mention, AllowScheduledRaids = channel.ScheduledRaids, }; + } + } + } return null; } diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index 4a5c235..b68cefb 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -22,15 +22,18 @@ public UserService(ILogger logger, TeamService teamService) this.teamService = teamService; } - public int? GetPlayerLevel(SocketGuildUser user) + public static int? GetPlayerLevel(SocketGuildUser user) { var name = user.Nickname ?? user.Username; var result = Regex.Match(name, @"\(\d+\)"); var stringLevel = result.Captures.LastOrDefault()?.Value; - if (stringLevel != null && - int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out var level) && - level >= 1 && level <= 40) + if (stringLevel != null + && int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out var level) + && level >= 1 && level <= 40) + { return level; + } + return null; } @@ -39,8 +42,12 @@ public UserService(ILogger logger, TeamService teamService) var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; foreach (var role in user.Roles) + { if (teamRoles.TryGetValue(role.Id, out var team)) + { return team; + } + } return null; } From 9d9ff2326bf4b220f08a6ca795f3a5e0a1ad96d4 Mon Sep 17 00:00:00 2001 From: Aaron Date: Thu, 4 Apr 2019 18:15:18 -0400 Subject: [PATCH 02/10] Have a proper functional localization I didn't actually need a localization service. It was built in code generation automatically. The strings can be retrieved from the resources file automatically and are dependent on the supplied thread. --- PoGo.DiscordBot/Common/StringUtils.cs | 10 +- .../Options/ConfigurationOptions.cs | 5 +- PoGo.DiscordBot/Configuration/PokemonTeam.cs | 2 +- .../Configuration/TeamRoleColors.cs | 5 +- PoGo.DiscordBot/Dto/GymInfoDto.cs | 2 +- PoGo.DiscordBot/Dto/PlayerDto.cs | 7 +- PoGo.DiscordBot/Dto/RaidBossDto.cs | 2 +- PoGo.DiscordBot/Dto/RaidChannelBindingDto.cs | 2 +- PoGo.DiscordBot/Dto/RaidInfoDto.cs | 63 +- PoGo.DiscordBot/Dto/TeamRolesDto.cs | 2 +- PoGo.DiscordBot/Emojis.cs | 5 +- PoGo.DiscordBot/LogSeverityExtensions.cs | 8 +- PoGo.DiscordBot/Modules/BlameModule.cs | 10 +- PoGo.DiscordBot/Modules/CleanModule.cs | 21 +- PoGo.DiscordBot/Modules/DiagnosticModule.cs | 10 +- PoGo.DiscordBot/Modules/HelpModule.cs | 72 +-- PoGo.DiscordBot/Modules/InfoModule.cs | 10 +- PoGo.DiscordBot/Modules/InviteModule.cs | 18 +- PoGo.DiscordBot/Modules/LanguageModule.cs | 20 + PoGo.DiscordBot/Modules/LogsModule.cs | 15 +- PoGo.DiscordBot/Modules/PlayerModule.cs | 17 +- .../RaidChannelPreconditionAttribute.cs | 4 +- .../TeamPreconditionAttribute.cs | 10 +- PoGo.DiscordBot/Modules/RaidModule.cs | 119 ++-- PoGo.DiscordBot/Modules/RoleModule.cs | 16 +- PoGo.DiscordBot/Modules/StatisticsModule.cs | 16 +- PoGo.DiscordBot/Modules/TestModule.cs | 4 +- PoGo.DiscordBot/PoGo.DiscordBot.csproj | 24 +- PoGo.DiscordBot/PoGoBot.cs | 83 +-- PoGo.DiscordBot/Program.cs | 14 +- .../PublishProfiles/FolderProfile.pubxml | 2 +- .../Properties/Resources.Designer.cs | 549 ++++++++++++++++++ .../Resources.cs.resx} | 37 +- .../Resources.en.resx} | 35 +- PoGo.DiscordBot/Properties/Resources.resx | 282 +++++++++ .../Services/ConfigurationService.cs | 9 +- .../Services/GymLocationService.cs | 15 +- .../Services/LocalizationService.cs | 35 -- .../Services/RaidBossInfoService.cs | 21 +- .../Services/RaidChannelService.cs | 44 +- PoGo.DiscordBot/Services/RaidService.cs | 92 +-- .../Services/RaidStorageService.cs | 44 +- PoGo.DiscordBot/Services/RoleService.cs | 7 +- PoGo.DiscordBot/Services/TeamService.cs | 16 +- PoGo.DiscordBot/Services/UserService.cs | 44 +- .../configuration.Development.json | 4 +- PoGo.DiscordBot/configuration.Production.json | 2 +- 47 files changed, 1401 insertions(+), 433 deletions(-) create mode 100644 PoGo.DiscordBot/Modules/LanguageModule.cs create mode 100644 PoGo.DiscordBot/Properties/Resources.Designer.cs rename PoGo.DiscordBot/{Resources/Global.cs.resx => Properties/Resources.cs.resx} (89%) rename PoGo.DiscordBot/{Resources/Global.en.resx => Properties/Resources.en.resx} (89%) create mode 100644 PoGo.DiscordBot/Properties/Resources.resx delete mode 100644 PoGo.DiscordBot/Services/LocalizationService.cs diff --git a/PoGo.DiscordBot/Common/StringUtils.cs b/PoGo.DiscordBot/Common/StringUtils.cs index 0248cea..eb56d48 100644 --- a/PoGo.DiscordBot/Common/StringUtils.cs +++ b/PoGo.DiscordBot/Common/StringUtils.cs @@ -7,12 +7,12 @@ public static class StringUtils { public static string ToLowerWithoutDiacritics(string text) { - var normalizedString = text.Normalize(NormalizationForm.FormD); - var stringBuilder = new StringBuilder(text.Length); + string normalizedString = text.Normalize(NormalizationForm.FormD); + StringBuilder stringBuilder = new StringBuilder(text.Length); - foreach (var c in normalizedString) + foreach (char c in normalizedString) { - var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); + UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); if (unicodeCategory != UnicodeCategory.NonSpacingMark) { stringBuilder.Append(char.ToLower(c)); @@ -22,4 +22,4 @@ public static string ToLowerWithoutDiacritics(string text) return stringBuilder.ToString().Normalize(NormalizationForm.FormC); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs b/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs index 2b550b1..5d135db 100644 --- a/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs +++ b/PoGo.DiscordBot/Configuration/Options/ConfigurationOptions.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Globalization; namespace PoGo.DiscordBot.Configuration.Options { @@ -14,7 +15,7 @@ public class GuildOptions { public string Name { get; set; } public ulong Id { get; set; } - public string Language { get; set; } + public CultureInfo Language { get; set; } public bool IgnoreMention { get; set; } public string[] FreeRoles { get; set; } public ChannelOptions[] Channels { get; set; } @@ -44,4 +45,4 @@ public class GymInfoOptions public string Latitude { get; set; } public string Longitude { get; set; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Configuration/PokemonTeam.cs b/PoGo.DiscordBot/Configuration/PokemonTeam.cs index f7e12b4..622f9ef 100644 --- a/PoGo.DiscordBot/Configuration/PokemonTeam.cs +++ b/PoGo.DiscordBot/Configuration/PokemonTeam.cs @@ -6,4 +6,4 @@ public enum PokemonTeam Instinct, Valor } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Configuration/TeamRoleColors.cs b/PoGo.DiscordBot/Configuration/TeamRoleColors.cs index 0be326a..45946df 100644 --- a/PoGo.DiscordBot/Configuration/TeamRoleColors.cs +++ b/PoGo.DiscordBot/Configuration/TeamRoleColors.cs @@ -11,13 +11,16 @@ public static Color GetColor(PokemonTeam team) { case PokemonTeam.Mystic: return new Color(0x00, 0xb8, 0xff); + case PokemonTeam.Instinct: return new Color(0xff, 0xf5, 0x00); + case PokemonTeam.Valor: return new Color(0xff, 0x19, 0x05); + default: throw new Exception("Unknown team"); } } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/GymInfoDto.cs b/PoGo.DiscordBot/Dto/GymInfoDto.cs index 97879ee..7e8869e 100644 --- a/PoGo.DiscordBot/Dto/GymInfoDto.cs +++ b/PoGo.DiscordBot/Dto/GymInfoDto.cs @@ -6,4 +6,4 @@ public class GymInfoDto public string Latitude { get; set; } public string Longitude { get; set; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/PlayerDto.cs b/PoGo.DiscordBot/Dto/PlayerDto.cs index 0280705..9a377df 100644 --- a/PoGo.DiscordBot/Dto/PlayerDto.cs +++ b/PoGo.DiscordBot/Dto/PlayerDto.cs @@ -9,6 +9,9 @@ public class PlayerDto public PokemonTeam? Team { get; set; } public int? Level { get; set; } - public override string ToString() => User.Nickname ?? User.Username; + public override string ToString() + { + return User.Nickname ?? User.Username; + } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/RaidBossDto.cs b/PoGo.DiscordBot/Dto/RaidBossDto.cs index 7c93b55..8713e38 100644 --- a/PoGo.DiscordBot/Dto/RaidBossDto.cs +++ b/PoGo.DiscordBot/Dto/RaidBossDto.cs @@ -11,4 +11,4 @@ public class RaidBossDto public string[] ChargeAttacks { get; set; } public string[] Counters { get; set; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/RaidChannelBindingDto.cs b/PoGo.DiscordBot/Dto/RaidChannelBindingDto.cs index 5079466..bc572fd 100644 --- a/PoGo.DiscordBot/Dto/RaidChannelBindingDto.cs +++ b/PoGo.DiscordBot/Dto/RaidChannelBindingDto.cs @@ -8,4 +8,4 @@ public class RaidChannelBindingDto public IMentionable Mention { get; set; } public bool AllowScheduledRaids { get; set; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/RaidInfoDto.cs b/PoGo.DiscordBot/Dto/RaidInfoDto.cs index 25d41d9..19c4434 100644 --- a/PoGo.DiscordBot/Dto/RaidInfoDto.cs +++ b/PoGo.DiscordBot/Dto/RaidInfoDto.cs @@ -1,11 +1,9 @@ using Discord; -using Microsoft.Extensions.Localization; using PoGo.DiscordBot.Configuration; -using PoGo.DiscordBot.Services; +using PoGo.DiscordBot.Properties; using System; using System.Collections.Generic; using System.Linq; -using System.Resources; namespace PoGo.DiscordBot.Dto { @@ -20,10 +18,6 @@ public class RaidInfoDto public const string TimeFormat = "H:mm"; public const string DateTimeFormat = "d.M.yyyy H:mm"; - public readonly static string DateWord = LocalizationService.Instance.GetStringFromResources("Date"); - - public readonly static string TimeWord = LocalizationService.Instance.GetStringFromResources("Time"); - public IUserMessage Message { get; set; } public DateTime CreatedAt { get; set; } public string BossName { get; set; } @@ -34,7 +28,7 @@ public class RaidInfoDto public bool IsExpired => DateTime < DateTime.Now; public RaidType RaidType { get; set; } - string DateTimeAsString => DateTime.ToString(RaidType == RaidType.Normal ? TimeFormat : DateTimeFormat); + private string DateTimeAsString => DateTime.ToString(RaidType == RaidType.Normal ? TimeFormat : DateTimeFormat); public RaidInfoDto(RaidType raidType) { @@ -53,7 +47,7 @@ Color GetColor() return !IsExpired ? new Color(191, 155, 48) : Color.Red; } - var remainingTime = DateTime - DateTime.Now; + TimeSpan remainingTime = DateTime - DateTime.Now; if (remainingTime.TotalMinutes <= 0) return Color.Red; @@ -65,9 +59,9 @@ Color GetColor() EmbedBuilder embedBuilder = new EmbedBuilder(); embedBuilder .WithColor(GetColor()) - .AddInlineField("Boss", BossName) - .AddInlineField(LocalizationService.Instance.GetStringFromResources("Where"), Location) - .AddInlineField(RaidType == RaidType.Normal ? TimeWord : DateWord, DateTimeAsString) + .AddInlineField(Resources.Boss, BossName) + .AddInlineField(Resources.Where, Location) + .AddInlineField(RaidType == RaidType.Normal ? Resources.Time : Resources.Date, DateTimeAsString) ; if (Players.Count > 0) @@ -76,32 +70,38 @@ Color GetColor() PlayersToGroupString(Players.Values) : PlayersToString(Players.Values); - embedBuilder.AddField(LocalizationService.Instance.GetStringFromResources("Players") + $"({Players.Count})", playerFieldValue); + embedBuilder.AddField(Resources.Players + $"({Players.Count})", playerFieldValue); } if (ExtraPlayers.Count > 0) { string extraPlayersFieldValue = string.Join(" + ", ExtraPlayers.Select(t => t.Count)); - embedBuilder.AddField(LocalizationService.Instance.GetStringFromResources("OtherPlayers") + $"({ExtraPlayers.Sum(t => t.Count)})", extraPlayersFieldValue); + embedBuilder.AddField(Resources.OtherPlayers + $"({ExtraPlayers.Sum(t => t.Count)})", extraPlayersFieldValue); } return embedBuilder.Build(); } - public string ToSimpleString() => $"{BossName} {Location} {DateTimeAsString}"; + public string ToSimpleString() + { + return $"{BossName} {Location} {DateTimeAsString}"; + } - string PlayersToString(IEnumerable players) => string.Join(", ", players); + private string PlayersToString(IEnumerable players) + { + return string.Join(", ", players); + } - string PlayersToGroupString(IEnumerable allPlayers) + private string PlayersToGroupString(IEnumerable allPlayers) { - string TeamToString(PokemonTeam? team) => team != null ? team.ToString() : LocalizationService.Instance.GetStringFromResources("WithoutTeam"); + string TeamToString(PokemonTeam? team) => team != null ? team.ToString() : Resources.WithoutTeam; List formatterGroupedPlayers = new List(); - var teams = new PokemonTeam?[] { PokemonTeam.Mystic, PokemonTeam.Instinct, PokemonTeam.Valor, null }; + PokemonTeam?[] teams = new PokemonTeam?[] { PokemonTeam.Mystic, PokemonTeam.Instinct, PokemonTeam.Valor, null }; foreach (PokemonTeam? team in teams) { - var players = allPlayers.Where(t => t.Team == team).ToList(); + List players = allPlayers.Where(t => t.Team == team).ToList(); if (players.Count > 0) formatterGroupedPlayers.Add($"{TeamToString(team)} ({players.Count}) - {PlayersToString(players)}"); } @@ -109,11 +109,14 @@ string PlayersToGroupString(IEnumerable allPlayers) return string.Join(Environment.NewLine, formatterGroupedPlayers); } - public static DateTime? ParseTime(string time) => ParseTime(time, DateTime.Now.Date); + public static DateTime? ParseTime(string time) + { + return ParseTime(time, DateTime.Now.Date); + } public static DateTime? ParseTime(string time, DateTime date) { - var pieces = time.Split(' ', '.', ',', ':', ';', '\''); + string[] pieces = time.Split(' ', '.', ',', ':', ';', '\''); if (pieces.Length != 2 || !int.TryParse(pieces[0], out int hours) || !int.TryParse(pieces[1], out int minutes)) return null; @@ -126,10 +129,10 @@ string PlayersToGroupString(IEnumerable allPlayers) DateTime? result = null; try { - var tokens = dateTime.Split(new[] { ' ', '.', ',', ':', ';', '\'', '/' }, StringSplitOptions.RemoveEmptyEntries); + string[] tokens = dateTime.Split(new[] { ' ', '.', ',', ':', ';', '\'', '/' }, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 5) throw new Exception($"Invalid date '{dateTime}'"); - var intTokens = tokens.Select(int.Parse).ToArray(); + int[] intTokens = tokens.Select(int.Parse).ToArray(); result = new DateTime(intTokens[2], intTokens[1], intTokens[0], intTokens[3], intTokens[4], 0); } @@ -141,15 +144,15 @@ string PlayersToGroupString(IEnumerable allPlayers) public static RaidInfoDto Parse(IUserMessage message) { - var embed = message.Embeds.FirstOrDefault(); + IEmbed embed = message.Embeds.FirstOrDefault(); if (embed == null || embed.Fields.Length < 3) return null; RaidInfoDto result = null; - if (embed.Fields[2].Name.Equals(TimeWord,StringComparison.OrdinalIgnoreCase)) + if (embed.Fields[2].Name.Equals(Resources.Time, StringComparison.OrdinalIgnoreCase)) { - var time = ParseTime(embed.Fields[2].Value, message.CreatedAt.Date); + DateTime? time = ParseTime(embed.Fields[2].Value, message.CreatedAt.Date); if (!time.HasValue) return null; @@ -162,9 +165,9 @@ public static RaidInfoDto Parse(IUserMessage message) DateTime = time.Value, }; } - else if (embed.Fields[2].Name.Equals(DateWord,StringComparison.OrdinalIgnoreCase)) + else if (embed.Fields[2].Name.Equals(Resources.Date, StringComparison.OrdinalIgnoreCase)) { - var dateTime = ParseDateTime(embed.Fields[2].Value); + DateTime? dateTime = ParseDateTime(embed.Fields[2].Value); if (!dateTime.HasValue) return null; @@ -181,4 +184,4 @@ public static RaidInfoDto Parse(IUserMessage message) return result; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/TeamRolesDto.cs b/PoGo.DiscordBot/Dto/TeamRolesDto.cs index 98b9138..6cadfea 100644 --- a/PoGo.DiscordBot/Dto/TeamRolesDto.cs +++ b/PoGo.DiscordBot/Dto/TeamRolesDto.cs @@ -9,4 +9,4 @@ public class TeamRolesDto public IReadOnlyDictionary RoleTeams { get; set; } // public IReadOnlyDictionary TeamRoles { get; set; } // } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Emojis.cs b/PoGo.DiscordBot/Emojis.cs index 2595c2c..57ff99b 100644 --- a/PoGo.DiscordBot/Emojis.cs +++ b/PoGo.DiscordBot/Emojis.cs @@ -9,8 +9,7 @@ internal class UnicodeEmojis public const string ThumbsDown = "👎"; public const string Check = "✅"; public const string Cross = "❌"; - - const char Border = '⃣'; + private const char Border = '⃣'; public static readonly string[] KeycapDigits; static UnicodeEmojis() @@ -35,4 +34,4 @@ static Emojis() KeycapDigits = UnicodeEmojis.KeycapDigits.Select(t => new Emoji(t)).ToArray(); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/LogSeverityExtensions.cs b/PoGo.DiscordBot/LogSeverityExtensions.cs index 6edcf18..61a582c 100644 --- a/PoGo.DiscordBot/LogSeverityExtensions.cs +++ b/PoGo.DiscordBot/LogSeverityExtensions.cs @@ -11,19 +11,25 @@ public static LogLevel ToLogLevel(this LogSeverity logSeverity) { case LogSeverity.Critical: return LogLevel.Critical; + case LogSeverity.Error: return LogLevel.Error; + case LogSeverity.Warning: return LogLevel.Warning; + case LogSeverity.Info: return LogLevel.Information; + case LogSeverity.Verbose: return LogLevel.Trace; + case LogSeverity.Debug: return LogLevel.Debug; + default: return LogLevel.Critical; } } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/BlameModule.cs b/PoGo.DiscordBot/Modules/BlameModule.cs index 7c50f3d..0c9e90a 100644 --- a/PoGo.DiscordBot/Modules/BlameModule.cs +++ b/PoGo.DiscordBot/Modules/BlameModule.cs @@ -12,8 +12,8 @@ namespace PoGo.DiscordBot.Modules [Group("blame")] public class BlameModule : ModuleBase { - readonly UserService userService; - readonly ILogger logger; + private readonly UserService userService; + private readonly ILogger logger; public BlameModule(UserService userService, ILogger logger) { @@ -24,7 +24,7 @@ public BlameModule(UserService userService, ILogger logger) [Command("level")] public async Task ListPlayersWithoutLevel() { - var players = userService.GetPlayers(Context.Guild.Users) + System.Collections.Generic.IEnumerable players = userService.GetPlayers(Context.Guild.Users) .Where(t => !t.Level.HasValue); string message = string.Join(", ", players); @@ -34,11 +34,11 @@ public async Task ListPlayersWithoutLevel() [Command("team")] public async Task ListPlayersWithoutTeam() { - var players = userService.GetPlayers(Context.Guild.Users) + System.Collections.Generic.IEnumerable players = userService.GetPlayers(Context.Guild.Users) .Where(t => !t.Team.HasValue); string message = string.Join(", ", players); await ReplyAsync($"`{message}`"); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/CleanModule.cs b/PoGo.DiscordBot/Modules/CleanModule.cs index 5fa0ee1..55d52c3 100644 --- a/PoGo.DiscordBot/Modules/CleanModule.cs +++ b/PoGo.DiscordBot/Modules/CleanModule.cs @@ -1,5 +1,6 @@ using Discord; using Discord.Commands; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -10,38 +11,38 @@ public class CleanModule : ModuleBase { [Command("hardclean", RunMode = RunMode.Async)] [Summary("DeleteAllMessagesSummary")] - public async Task FullClean([Summary("Počet zpráv.")]int count = 10) + public async Task FullClean([Summary("MessageNumber")]int count = 10) { - var batchMessages = AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync(count)); - foreach (var messages in batchMessages) + IEnumerable> batchMessages = AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync(count)); + foreach (IReadOnlyCollection messages in batchMessages) await Context.Channel.DeleteMessagesAsync(messages); } [Command("clean", RunMode = RunMode.Async)] [Summary("DeleteYourMessageSummary")] - public async Task DeleteLastMessagesFromCurrentUser([Summary("Počet zpráv.")]int count = 5) + public async Task DeleteLastMessagesFromCurrentUser([Summary("MessageNumber")]int count = 5) { await DeleteMessagesAsync(Context.User.Id, count); } [Command("clean", RunMode = RunMode.Async)] [Summary("DeleteLastMessageSummary")] - public async Task DeleteLastMessages([Summary("Uživatel.")]IUser user, - [Summary("Počet zpráv.")]int count = 5) + public async Task DeleteLastMessages([Summary("User")]IUser user, + [Summary("MessageNumber")]int count = 5) { ulong userId = user != null ? user.Id : Context.User.Id; await DeleteMessagesAsync(userId, count); } - async Task DeleteMessagesAsync(ulong userId, int count) + private async Task DeleteMessagesAsync(ulong userId, int count) { - foreach (var messages in Context.Channel.GetMessagesAsync().ToEnumerable()) + foreach (IReadOnlyCollection messages in Context.Channel.GetMessagesAsync().ToEnumerable()) { - var messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); + IEnumerable messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); if (messagesToDelete != null) await Context.Channel.DeleteMessagesAsync(messagesToDelete.Take(count)); } } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/DiagnosticModule.cs b/PoGo.DiscordBot/Modules/DiagnosticModule.cs index 75ec253..55a8fcd 100644 --- a/PoGo.DiscordBot/Modules/DiagnosticModule.cs +++ b/PoGo.DiscordBot/Modules/DiagnosticModule.cs @@ -12,11 +12,11 @@ public class DiagnosticModule : ModuleBase [Command("ps")] public async Task ProcessInfo() { - var proc = Process.GetCurrentProcess(); + Process proc = Process.GetCurrentProcess(); double mem = proc.WorkingSet64; - var cpu = proc.TotalProcessorTime; + TimeSpan cpu = proc.TotalProcessorTime; - var suffixes = new[] { "", "K", "M", "G", "T" }; + string[] suffixes = new[] { "", "K", "M", "G", "T" }; int memoryIndex = 0; while (mem >= 1024) { @@ -24,7 +24,7 @@ public async Task ProcessInfo() memoryIndex++; } - var totalTime = DateTime.Now - proc.StartTime; + TimeSpan totalTime = DateTime.Now - proc.StartTime; EmbedBuilder embedBuilder = new EmbedBuilder() .AddField("Time running", $"{totalTime}") @@ -36,4 +36,4 @@ public async Task ProcessInfo() await ReplyAsync(string.Empty, embed: embedBuilder.Build()); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index 711f474..89b17db 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -3,11 +3,11 @@ using Discord.Commands; using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; -using PoGo.DiscordBot.Services; +using PoGo.DiscordBot.Properties; using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; -using System.Resources; using System.Text; using System.Threading.Tasks; @@ -15,9 +15,11 @@ namespace PoGo.DiscordBot.Modules { public class HelpModule : InteractiveBase { - readonly CommandService commandService; - readonly IServiceProvider serviceProvider; - readonly char prefix; + private readonly CommandService commandService; + private readonly IServiceProvider serviceProvider; + private readonly char prefix; + //TODO Load the current culture info from guild + readonly CultureInfo cultureInfo = CultureInfo.GetCultureInfo("cs-CS"); public HelpModule(CommandService commandService, IServiceProvider serviceProvider, IOptions config) { @@ -30,22 +32,22 @@ public HelpModule(CommandService commandService, IServiceProvider serviceProvide [Summary("ListCommandsSummary")] public async Task Help() { - var groupCommands = new Dictionary>(); + Dictionary> groupCommands = new Dictionary>(); - foreach (var module in commandService.Modules) + foreach (ModuleInfo module in commandService.Modules) { string key = module.Aliases.FirstOrDefault() ?? string.Empty; - if (!groupCommands.TryGetValue(key, out var commands)) + if (!groupCommands.TryGetValue(key, out List commands)) groupCommands[key] = commands = new List(); - foreach (var cmd in module.Commands) + foreach (CommandInfo cmd in module.Commands) { - var result = await cmd.CheckPreconditionsAsync(Context, serviceProvider); + PreconditionResult result = await cmd.CheckPreconditionsAsync(Context, serviceProvider); if (result.IsSuccess) { - string s = $"{prefix}{cmd.Aliases.First()}"; + string s = $"{prefix}{cmd.Aliases[0]}"; if (!string.IsNullOrEmpty(cmd.Summary)) - s += $" ({ cmd.Summary})"; + s += $" ({ Resources.ResourceManager.GetString(cmd.Summary,cultureInfo)})"; commands.Add(s); } @@ -55,16 +57,16 @@ public async Task Help() string CommandsToString(IEnumerable commands) => string.Join(Environment.NewLine, commands.OrderBy(t => t)); - var commandPages = new List>(); + List> commandPages = new List>(); // Commands with module that has alias equal to "" are without any group // and they are on first page without any other group commands - if (groupCommands.TryGetValue(string.Empty, out var globalCommands)) + if (groupCommands.TryGetValue(string.Empty, out List globalCommands)) commandPages.Add(globalCommands); const int MaxCommandsPerPage = 15; List currentPageCommands = new List(); - foreach (var c in groupCommands.OrderBy(t => t.Key)) + foreach (KeyValuePair> c in groupCommands.OrderBy(t => t.Key)) { if (c.Key?.Length == 0) continue; @@ -83,7 +85,7 @@ string CommandsToString(IEnumerable commands) => } if (currentPageCommands.Count > 0) commandPages.Add(currentPageCommands); - var pages = commandPages.Select(CommandsToString).ToList(); + List pages = commandPages.Select(CommandsToString).ToList(); if (pages.Count > 1) { @@ -96,12 +98,12 @@ await PagedReplyAsync(new PaginatedMessage DisplayInformationIcon = false, Timeout = TimeSpan.FromMinutes(1), }, - Title = LocalizationService.Instance.GetStringFromResources("AvailableCommands"), + Title = Resources.AllCommands, Pages = pages, }); } else if (pages.Count > 0) - await ReplyAsync($"```{pages.First()}```"); + await ReplyAsync($"```{pages[0]}```"); } private enum CommandInfoSignature @@ -111,20 +113,20 @@ private enum CommandInfoSignature } [Command("help")] - [Summary("Vypíše nápovědu pro konkrétní příkaz.")] + [Summary("HelpSummary")] public async Task Help([Remainder] string command) { - var result = commandService.Search(Context, command); + SearchResult result = commandService.Search(Context, command); if (!result.IsSuccess) { - string reply = String.Format(LocalizationService.Instance.GetStringFromResources("CommandNotFound"),command); + string reply = string.Format(Resources.CommandNotFound, command); await ReplyAsync(reply); return; } - var builder = new EmbedBuilder() + EmbedBuilder builder = new EmbedBuilder() .WithColor(Color.Blue); string ParameterInfoToString(ParameterInfo info) => !info.IsOptional ? info.Name : $"[{info.Name}]"; @@ -136,13 +138,13 @@ string ParameterInfoToDetailedString(ParameterInfo info) sb.Append(info.Name); if (!string.IsNullOrEmpty(info.Summary)) - sb.Append($" - {LocalizationService.Instance.GetStringFromResources(info.Summary)}"); + sb.Append($" - {Resources.ResourceManager.GetString(info.Summary,cultureInfo)}"); if (info.Type.IsEnum) - sb.Append(LocalizationService.Instance.GetStringFromResources("PossibleValues") + $" ({string.Join(" | ", Enum.GetNames(info.Type))})!"); + sb.Append(Resources.PossibleValues + $" ({string.Join(" | ", Enum.GetNames(info.Type))})!"); if (info.IsOptional) - sb.Append(LocalizationService.Instance.GetStringFromResources("Optional") + $" ({info.DefaultValue})"); + sb.Append(Resources.Optional + $" ({info.DefaultValue})"); return sb.ToString(); } @@ -157,7 +159,7 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) if (ci.Parameters.Count > 0) { - var parameters = ci.Parameters.AsEnumerable(); + IEnumerable parameters = ci.Parameters.AsEnumerable(); if (signature == HelpModule.CommandInfoSignature.Basic) parameters = parameters.Where(pi => !pi.IsOptional); @@ -168,16 +170,16 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) return sb.ToString(); } - foreach (var match in result.Commands) + foreach (CommandMatch match in result.Commands) { - var cmd = match.Command; + CommandInfo cmd = match.Command; StringBuilder sb = new StringBuilder() - .Append(LocalizationService.Instance.GetStringFromResources("Description")).Append(':').AppendLine(cmd.Summary) + .Append(Resources.Description).Append(':').AppendLine(cmd.Summary) .AppendLine() - .Append(LocalizationService.Instance.GetStringFromResources("BasicUse")).Append(":**").Append(CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Basic)).AppendLine("**"); + .Append(Resources.BasicUse).Append(":**").Append(CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Basic)).AppendLine("**"); if (cmd.Parameters.Any(t => t.IsOptional)) - sb.AppendLine(LocalizationService.Instance.GetStringFromResources("FullUse") + $": {CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Full)}"); + sb.AppendLine(Resources.FullUse + $": {CommandInfoSignature(cmd, HelpModule.CommandInfoSignature.Full)}"); sb.AppendLine(); if (cmd.Parameters.Count > 0) @@ -186,15 +188,15 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) string detailedParameters = string.Join(Environment.NewLine, cmd.Parameters.Select(ParameterInfoToDetailedString)); sb - .Append(LocalizationService.Instance.GetStringFromResources("Parameters")).Append(": ").AppendLine(parameters) - .AppendLine(LocalizationService.Instance.GetStringFromResources("ParameterDescription")) + .Append(Resources.Parameters).Append(": ").AppendLine(parameters) + .AppendLine(Resources.ParameterDescription) .AppendLine(detailedParameters); } - builder.AddField(LocalizationService.Instance.GetStringFromResources("Command") + $"{(cmd.Aliases.Count > 1 ? "y" : "")}: {string.Join(", ", cmd.Aliases)}", sb); + builder.AddField(Resources.Command + $"{(cmd.Aliases.Count > 1 ? "y" : "")}: {string.Join(", ", cmd.Aliases)}", sb); } await ReplyAsync(string.Empty, false, builder.Build()); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/InfoModule.cs b/PoGo.DiscordBot/Modules/InfoModule.cs index 9739f51..286edaa 100644 --- a/PoGo.DiscordBot/Modules/InfoModule.cs +++ b/PoGo.DiscordBot/Modules/InfoModule.cs @@ -2,7 +2,7 @@ using Discord.Commands; using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; -using PoGo.DiscordBot.Services; +using PoGo.DiscordBot.Properties; using System; using System.Threading.Tasks; @@ -10,7 +10,7 @@ namespace PoGo.DiscordBot.Modules { public class InfoModule : ModuleBase { - readonly ConfigurationOptions configuration; + private readonly ConfigurationOptions configuration; public InfoModule(IOptions configurationOptionsAccessor) { @@ -37,7 +37,7 @@ public async Task WriteInfo() {configuration.Prefix}raid Machamp Žirafa 12:00 2 Pozn. Jestliže má jakýkoliv parametr mezery, je nutné ho obalit uvozovkami (""parametr s mezerou"")"); - var embed = embedBuilder.Build(); + Embed embed = embedBuilder.Build(); await ReplyAsync(string.Empty, embed: embed); } @@ -51,7 +51,7 @@ public async Task Contribute() [Command("donate", RunMode = RunMode.Async)] public async Task Donate() { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("SupportDevelopment")); + await ReplyAsync(Resources.SupportDevelopment); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/InviteModule.cs b/PoGo.DiscordBot/Modules/InviteModule.cs index 522a82a..dd81ccf 100644 --- a/PoGo.DiscordBot/Modules/InviteModule.cs +++ b/PoGo.DiscordBot/Modules/InviteModule.cs @@ -1,5 +1,9 @@ using Discord.Commands; +using Discord.Rest; +using Discord.WebSocket; using Microsoft.Extensions.Logging; +using PoGo.DiscordBot.Properties; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -8,7 +12,7 @@ namespace PoGo.DiscordBot.Modules [RequireContext(ContextType.Guild)] public class InviteModule : ModuleBase { - readonly ILogger logger; + private readonly ILogger logger; public InviteModule(ILogger logger) { @@ -17,22 +21,22 @@ public InviteModule(ILogger logger) [Command("invite")] [Alias("inv")] - [Summary("Vrátí odkaz s pozvánkou sem na Discord.")] + [Summary("InviteSummary")] public async Task Invite() { - var invites = await Context.Guild.GetInvitesAsync(); - var invite = invites.FirstOrDefault(t => !t.IsTemporary); + IReadOnlyCollection invites = await Context.Guild.GetInvitesAsync(); + RestInviteMetadata invite = invites.FirstOrDefault(t => !t.IsTemporary); if (invite == null) { // TODO: call Context.Guild.DefaultChannel instead later on - var defaultChannel = Context.Guild.TextChannels + SocketTextChannel defaultChannel = Context.Guild.TextChannels .OrderBy(c => c.Position) .FirstOrDefault(); if (defaultChannel == null) { - await ReplyAsync("Sorry, žádný tu nemám :("); + await ReplyAsync("Sorry," + Resources.NoDefaultChannel + ":("); return; } @@ -43,4 +47,4 @@ public async Task Invite() await ReplyAsync(invite.Url); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/LanguageModule.cs b/PoGo.DiscordBot/Modules/LanguageModule.cs new file mode 100644 index 0000000..5f50a0f --- /dev/null +++ b/PoGo.DiscordBot/Modules/LanguageModule.cs @@ -0,0 +1,20 @@ +using Discord.Commands; +using Microsoft.Extensions.Logging; +using PoGo.DiscordBot.Services; + +namespace PoGo.DiscordBot.Modules +{ + //TODO Add a command to support changing the language in the config + public class LanguageModule : ModuleBase + { + private readonly ILogger logger; + private readonly ConfigurationService configService; + + public LanguageModule(ILogger logger + , ConfigurationService configService) + { + this.logger = logger; + this.configService = configService; + } + } +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/LogsModule.cs b/PoGo.DiscordBot/Modules/LogsModule.cs index bffe388..dae5b4e 100644 --- a/PoGo.DiscordBot/Modules/LogsModule.cs +++ b/PoGo.DiscordBot/Modules/LogsModule.cs @@ -1,6 +1,7 @@ using Discord; using Discord.Commands; using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -10,17 +11,17 @@ namespace PoGo.DiscordBot.Modules [RequireOwner] public class LogsModule : ModuleBase { - const string LogDirectory = "Logs"; + private const string LogDirectory = "Logs"; [Command("logs", RunMode = RunMode.Async)] public async Task GetLogsFiles() { - var di = new DirectoryInfo(LogDirectory); + DirectoryInfo di = new DirectoryInfo(LogDirectory); - var filenames = di.EnumerateFiles().Select(t => t.Name); + IEnumerable filenames = di.EnumerateFiles().Select(t => t.Name); string content = string.Join(Environment.NewLine, filenames); - var embedBuilder = new EmbedBuilder() + EmbedBuilder embedBuilder = new EmbedBuilder() .WithDescription(content); await ReplyAsync(string.Empty, embed: embedBuilder.Build()); } @@ -28,7 +29,7 @@ public async Task GetLogsFiles() [Command("log", RunMode = RunMode.Async)] public async Task GetLog() { - var fileInfo = new DirectoryInfo(LogDirectory) + FileInfo fileInfo = new DirectoryInfo(LogDirectory) .EnumerateFiles() .OrderByDescending(t => t.LastWriteTimeUtc) .FirstOrDefault(); @@ -47,7 +48,7 @@ public async Task GetLog(string filename) { string path = Path.Combine(LogDirectory, filename); if (!File.Exists(path)) - { + { await ReplyAsync("Log does not exists."); return; } @@ -55,4 +56,4 @@ public async Task GetLog(string filename) await Context.Channel.SendFileAsync(path); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/PlayerModule.cs b/PoGo.DiscordBot/Modules/PlayerModule.cs index 571a355..2283c4d 100644 --- a/PoGo.DiscordBot/Modules/PlayerModule.cs +++ b/PoGo.DiscordBot/Modules/PlayerModule.cs @@ -2,6 +2,7 @@ using Discord.WebSocket; using PoGo.DiscordBot.Configuration; using PoGo.DiscordBot.Modules.Preconditions; +using PoGo.DiscordBot.Properties; using PoGo.DiscordBot.Services; using System.Threading.Tasks; @@ -10,8 +11,8 @@ namespace PoGo.DiscordBot.Modules [RequireContext(ContextType.Guild)] public class PlayerModule : ModuleBase { - readonly UserService userService; - readonly TeamService teamService; + private readonly UserService userService; + private readonly TeamService teamService; public PlayerModule(UserService userService, TeamService teamService) { @@ -32,18 +33,18 @@ public async Task CheckTeam( public async Task SetTeam( [Summary("SelectedTeam")]PokemonTeam team) { - var contextUser = Context.User; + SocketUser contextUser = Context.User; if (!(contextUser is SocketGuildUser user)) return; - var userTeam = userService.GetTeam(user); + PokemonTeam? userTeam = userService.GetTeam(user); if (userTeam != null) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("InTeam")); + await ReplyAsync(Resources.InTeam); return; } - var role = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles[team]; + Discord.IRole role = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles[team]; await user.AddRoleAsync(role); } @@ -59,7 +60,7 @@ public async Task SetLevel( if (!(level >= 1 && level <= 40)) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("PlayAnotherGame")); + await ReplyAsync(Resources.PlayAnotherGame); return; } @@ -90,4 +91,4 @@ public async Task SetBasicInfo( await SetLevel(level); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs b/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs index e06c365..11e0e25 100644 --- a/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs +++ b/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs @@ -10,7 +10,7 @@ public class RaidChannelPreconditionAttribute : PreconditionAttribute { public override Task CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { - var raidChannelService = services.GetService(); + RaidChannelService raidChannelService = services.GetService(); if (raidChannelService.IsKnown(context.Guild.Id, context.Channel.Id)) return Task.FromResult(PreconditionResult.FromSuccess()); @@ -18,4 +18,4 @@ public override Task CheckPermissions(ICommandContext contex return Task.FromResult(PreconditionResult.FromError("This channel is not configured as input")); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs index 934610f..53039af 100644 --- a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs +++ b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs @@ -1,9 +1,9 @@ using Discord.Commands; using Discord.WebSocket; +using Microsoft.Extensions.DependencyInjection; using PoGo.DiscordBot.Services; using System; using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; namespace PoGo.DiscordBot.Modules.Preconditions { @@ -14,10 +14,10 @@ public override Task CheckPermissions(ICommandContext contex if (!(context.User is SocketGuildUser guildUser)) return Task.FromResult(TeamPreconditionResult.Fail); - var userService = services.GetService(); - var team = userService.GetTeam(guildUser); + UserService userService = services.GetService(); + Configuration.PokemonTeam? team = userService.GetTeam(guildUser); - if(team == null) + if (team == null) return Task.FromResult(TeamPreconditionResult.Fail); return Task.FromResult(TeamPreconditionResult.Success); @@ -34,4 +34,4 @@ protected TeamPreconditionResult(CommandError? error, string errorReason) public static TeamPreconditionResult Success => new TeamPreconditionResult(null, null); public static TeamPreconditionResult Fail => new TeamPreconditionResult(CommandError.UnmetPrecondition, "Je nutné si zvolit team."); } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/RaidModule.cs b/PoGo.DiscordBot/Modules/RaidModule.cs index b0a9e4e..51c5b4d 100644 --- a/PoGo.DiscordBot/Modules/RaidModule.cs +++ b/PoGo.DiscordBot/Modules/RaidModule.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging; using PoGo.DiscordBot.Dto; using PoGo.DiscordBot.Modules.Preconditions; +using PoGo.DiscordBot.Properties; using PoGo.DiscordBot.Services; using System; using System.Linq; @@ -18,15 +19,15 @@ namespace PoGo.DiscordBot.Modules [Alias("r")] public class RaidModule : InteractiveBase { - static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; - readonly TeamService teamService; - readonly RaidService raidService; - readonly ILogger logger; - readonly RaidChannelService raidChannelService; - readonly ConfigurationService configuration; - readonly RaidBossInfoService raidBossInfoService; - readonly GymLocationService gymLocationService; - readonly RaidStorageService raidStorageService; + private static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; + private readonly TeamService teamService; + private readonly RaidService raidService; + private readonly ILogger logger; + private readonly RaidChannelService raidChannelService; + private readonly ConfigurationService configuration; + private readonly RaidBossInfoService raidBossInfoService; + private readonly GymLocationService gymLocationService; + private readonly RaidStorageService raidStorageService; public RaidModule(TeamService teamService, RaidService raidService, ILogger logger, RaidChannelService raidChannelService, ConfigurationService configuration, RaidBossInfoService raidBossInfoService, GymLocationService gymLocationService, RaidStorageService raidStorageService) @@ -50,35 +51,35 @@ public async Task StartRaid( [Summary("Place")]string location, [Summary("Time (" + RaidInfoDto.TimeFormat + ").")]string time) { - var parsedTime = RaidInfoDto.ParseTime(time); + DateTime? parsedTime = RaidInfoDto.ParseTime(time); if (!parsedTime.HasValue) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("BadTimeFormat") + $"({RaidInfoDto.TimeFormat} 24H)."); + await ReplyAsync(Resources.BadTimeFormat + $"({RaidInfoDto.TimeFormat} 24H)."); return; } if (parsedTime < DateTime.Now) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("PastRaid")); + await ReplyAsync(Resources.PastRaid); return; } - var raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); + RaidChannelBindingDto raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); - var raidInfo = new RaidInfoDto(RaidType.Normal) + RaidInfoDto raidInfo = new RaidInfoDto(RaidType.Normal) { BossName = bossName, Location = location, DateTime = parsedTime.Value, }; - var roles = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles.Values; + System.Collections.Generic.IEnumerable roles = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles.Values; bool shouldMention = !(configuration.GetGuildOptions(Context.Guild.Id)?.IgnoreMention ?? false); string mention = string.Empty; if (shouldMention) mention = raidChannelBinding.Mention == null ? string.Join(' ', roles.Select(t => t.Mention)) : raidChannelBinding.Mention.Mention; - var message = await raidChannelBinding.Channel.SendMessageAsync($"{raidInfo.ToSimpleString()} {mention}", embed: raidInfo.ToEmbed()); + IUserMessage message = await raidChannelBinding.Channel.SendMessageAsync($"{raidInfo.ToSimpleString()} {mention}", embed: raidInfo.ToEmbed()); logger.LogInformation($"New raid has been created '{bossName}' '{location}' '{parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}'"); raidInfo.Message = message; await Context.Message.AddReactionAsync(Emojis.Check); @@ -102,34 +103,34 @@ public async Task StartScheduledRaid( [Summary("Place")]string location, [Remainder][Summary("Date (" + RaidInfoDto.DateTimeFormat + ").")]string dateTime) { - var raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); + RaidChannelBindingDto raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); if (raidChannelBinding == null || !raidChannelBinding.AllowScheduledRaids) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotPossible")); + await ReplyAsync(Resources.RaidNotPossible); return; } - var parsedDateTime = RaidInfoDto.ParseDateTime(dateTime); + DateTime? parsedDateTime = RaidInfoDto.ParseDateTime(dateTime); if (!parsedDateTime.HasValue) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("DateNotValid") + $"({RaidInfoDto.DateTimeFormat} 24H)."); + await ReplyAsync((Resources.DateNotValid) + $"({RaidInfoDto.DateTimeFormat} 24H)."); return; } if (parsedDateTime < DateTime.Now) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("PastRaid")); + await ReplyAsync(Resources.PastRaid); return; } - var raidInfo = new RaidInfoDto(RaidType.Scheduled) + RaidInfoDto raidInfo = new RaidInfoDto(RaidType.Scheduled) { BossName = bossName, Location = location, DateTime = parsedDateTime.Value, }; - var message = await raidChannelBinding.Channel.SendMessageAsync(string.Empty, embed: raidInfo.ToEmbed()); + IUserMessage message = await raidChannelBinding.Channel.SendMessageAsync(string.Empty, embed: raidInfo.ToEmbed()); logger.LogInformation($"New scheduled raid has been created '{bossName}' '{location}' '{parsedDateTime.Value.ToString(RaidInfoDto.DateTimeFormat)}'"); raidInfo.Message = message; await Context.Message.AddReactionAsync(Emojis.Check); @@ -138,10 +139,10 @@ public async Task StartScheduledRaid( raidStorageService.AddRaid(Context.Guild.Id, raidChannelBinding.Channel.Id, message.Id, raidInfo); } - RaidInfoDto GetRaid(int skip) + private RaidInfoDto GetRaid(int skip) { - var raidChannelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; - var raid = raidStorageService.GetRaid(Context.Guild.Id, raidChannelId, skip); + ulong raidChannelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; + RaidInfoDto raid = raidStorageService.GetRaid(Context.Guild.Id, raidChannelId, skip); return raid; } @@ -154,35 +155,35 @@ public async Task AdjustRaidTime( [Summary("Počet anket odspodu.")] int skip = 0) { // TODO scheduled raid - var raid = GetRaid(skip); + RaidInfoDto raid = GetRaid(skip); if (raid == null) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); + await ReplyAsync(Resources.RaidNotFound); return; } - var parsedTime = RaidInfoDto.ParseTime(time); + DateTime? parsedTime = RaidInfoDto.ParseTime(time); if (!parsedTime.HasValue) { - await ReplyAsync($"Čas není ve validním formátu ({RaidInfoDto.TimeFormat} 24H)."); + await ReplyAsync(Resources.BadTimeFormat + $" ({RaidInfoDto.TimeFormat} 24H)."); return; } if (parsedTime < DateTime.Now) { - await ReplyAsync($"Vážně změnit čas do minulosti?"); + await ReplyAsync(Resources.PastRaid); return; } - var currentUser = Context.User as SocketGuildUser; + SocketGuildUser currentUser = Context.User as SocketGuildUser; logger.LogInformation($"User '{currentUser.Nickname ?? Context.User.Username}' with id '{Context.User.Id}'" + $" changed raid with id '{raid.Message.Id}'" + $" time changed from {raid.DateTime.ToString(RaidInfoDto.TimeFormat)} to {parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}"); - foreach (var player in raid.Players.Values) + foreach (PlayerDto player in raid.Players.Values) { - var user = player.User; + IGuildUser user = player.User; await user.SendMessageAsync( $"Změna raid času z {raid.DateTime.ToString(RaidInfoDto.TimeFormat)} na {parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}!" + $" Jestli ti změna nevyhovuje, tak se odhlaš z raidu nebo se domluv s ostatními na jiném čase."); @@ -194,28 +195,28 @@ await user.SendMessageAsync( [Command("boss", RunMode = RunMode.Async)] [Alias("b")] - [Summary("Přenastaví bosse raidu.")] + [Summary("AdjustRaidBossSummary")] [RaidChannelPrecondition] public async Task AdjustRaidBoss( [Summary("Přenastaví bosse raidu.")]string boss, [Summary("Počet anket odspodu.")] int skip = 0) { - var raid = GetRaid(skip); + RaidInfoDto raid = GetRaid(skip); if (raid == null) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); + await ReplyAsync(Resources.RaidNotFound); return; } - var currentUser = Context.User as SocketGuildUser; + SocketGuildUser currentUser = Context.User as SocketGuildUser; logger.LogInformation($"User '{currentUser.Nickname ?? Context.User.Username}' with id '{Context.User.Id}'" + $" changed raid with id '{raid.Message.Id}'" + $" boss changed from {raid.BossName} to {boss}"); - foreach (var player in raid.Players.Values) + foreach (PlayerDto player in raid.Players.Values) { - var user = player.User; + IGuildUser user = player.User; await user.SendMessageAsync($"Změna raid bosse z '{raid.BossName}' na '{boss}'!"); } @@ -231,17 +232,17 @@ public async Task MentionRaidPlayers( [Summary("Počet anket odspodu.")] int skip = 0, [Remainder][Summary("Text")]string text = null) { - var raid = GetRaid(skip); + RaidInfoDto raid = GetRaid(skip); if (raid == null) { - await ReplyAsync(LocalizationService.Instance.GetStringFromResources("RaidNotFound")); + await ReplyAsync(Resources.RaidNotFound); return; } - var users = raid.Players.Values.ToHashSet(); + System.Collections.Generic.HashSet users = raid.Players.Values.ToHashSet(); - if (users.Any()) + if (users.Count > 0) { string playerMentions = string.Join(' ', users.Select(t => t.User.Mention)); string message = string.Empty; @@ -259,7 +260,7 @@ public async Task MentionRaidPlayers( public async Task DeleteRaid( [Summary("Počet anket odspodu.")] int skip = 0) { - var raid = GetRaid(skip); + RaidInfoDto raid = GetRaid(skip); if (raid == null) { @@ -267,14 +268,14 @@ public async Task DeleteRaid( return; } - var questionMessage = await ReplyAsync($"Vážně chceš smazat tenhle raid: '{raid.ToSimpleString()}'? [y]"); - var responseMessage = await NextMessageAsync(); + IUserMessage questionMessage = await ReplyAsync($"Vážně chceš smazat tenhle raid: '{raid.ToSimpleString()}'? [y]"); + SocketMessage responseMessage = await NextMessageAsync(); if (responseMessage == null || !string.Equals(responseMessage.Content, "y", StringComparison.OrdinalIgnoreCase)) return; - foreach (var player in raid.Players.Values) + foreach (PlayerDto player in raid.Players.Values) { - var user = player.User; + IGuildUser user = player.User; await user.SendMessageAsync($"Raid {raid.ToSimpleString()} se ruší!"); } @@ -288,18 +289,18 @@ public async Task DeleteRaid( public async Task RaidBossInfo( [Summary("Název bosse.")] string bossName) { - var boss = raidBossInfoService.GetBoss(bossName); + RaidBossDto boss = raidBossInfoService.GetBoss(bossName); if (boss == null) { - var availableBosses = string.Join(", ", raidBossInfoService.GetAllKnownBossNames()); + string availableBosses = string.Join(", ", raidBossInfoService.GetAllKnownBossNames()); await ReplyAsync($"Boss nenalezen - znám informace pouze o: {availableBosses}."); return; } string bossMention = raidBossInfoService.GetBossNameWithEmoji(boss.BossName, Context.Guild); - var countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); - var countersField = string.Join(", ", countersWithEmojis); + System.Collections.Generic.IEnumerable countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); + string countersField = string.Join(", ", countersWithEmojis); EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle(bossMention) .AddInlineField("Type", string.Join(", ", boss.Type)) @@ -324,15 +325,15 @@ public async Task RaidLocation( return; } - var searchResult = gymLocationService.Search(Context.Guild.Id, name); + System.Collections.Generic.IEnumerable searchResult = gymLocationService.Search(Context.Guild.Id, name); if (searchResult == null) { await ReplyAsync("Server nepodporuje tenhle příkaz."); return; } - var sb = new StringBuilder(); - foreach (var gymInfo in searchResult) + StringBuilder sb = new StringBuilder(); + foreach (GymInfoDto gymInfo in searchResult) sb.AppendLine($"{gymInfo.Name}: {gymLocationService.GetMapUrl(gymInfo)}"); await ReplyAsync(sb.ToString()); @@ -342,8 +343,8 @@ public async Task RaidLocation( [Summary("Vrátí seznam aktivních raidů včetně indexů.")] public async Task RaidList() { - var channelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; - var raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); + ulong channelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; + System.Collections.Generic.IEnumerable<(int Index, RaidInfoDto Raid)> raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); if (!raids.Any()) { await ReplyAsync("Nejsou aktivní žádné raidy."); @@ -353,4 +354,4 @@ public async Task RaidList() await ReplyAsync($"```{message}```"); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/RoleModule.cs b/PoGo.DiscordBot/Modules/RoleModule.cs index baa9587..4e74e4d 100644 --- a/PoGo.DiscordBot/Modules/RoleModule.cs +++ b/PoGo.DiscordBot/Modules/RoleModule.cs @@ -14,9 +14,9 @@ namespace PoGo.DiscordBot.Modules [Group("role")] public class RoleModule : ModuleBase { - readonly ILogger logger; - readonly RoleService roleService; - readonly Dictionary availableRoles; // + private readonly ILogger logger; + private readonly RoleService roleService; + private readonly Dictionary availableRoles; // public RoleModule(ILogger logger, IOptions options, RoleService roleService) { @@ -35,10 +35,10 @@ public async Task AddRole([Summary("Název role")]string roleName) if (!(Context.User is SocketGuildUser user)) return; - if (!availableRoles.TryGetValue(Context.Guild.Id, out var roles) || !roles.Contains(roleName)) + if (!availableRoles.TryGetValue(Context.Guild.Id, out string[] roles) || !roles.Contains(roleName)) return; - var role = roleService.GetRoleByName(Context.Guild, roleName); + SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { await ReplyAsync("Neznámá role."); @@ -57,10 +57,10 @@ public async Task RemoveRole([Summary("Název role")]string roleName) if (!(Context.User is SocketGuildUser user)) return; - if (!availableRoles.TryGetValue(Context.Guild.Id, out var roles) || !roles.Contains(roleName)) + if (!availableRoles.TryGetValue(Context.Guild.Id, out string[] roles) || !roles.Contains(roleName)) return; - var role = roleService.GetRoleByName(Context.Guild, roleName); + SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { await ReplyAsync("Neznámá role."); @@ -71,4 +71,4 @@ public async Task RemoveRole([Summary("Název role")]string roleName) await ReplyAsync($"Byla ti odebrána role '{roleName}'"); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/StatisticsModule.cs b/PoGo.DiscordBot/Modules/StatisticsModule.cs index 43eab82..812ac29 100644 --- a/PoGo.DiscordBot/Modules/StatisticsModule.cs +++ b/PoGo.DiscordBot/Modules/StatisticsModule.cs @@ -13,7 +13,7 @@ namespace PoGo.DiscordBot.Modules [Group("stats")] public class StatisticsModule : ModuleBase { - readonly UserService userService; + private readonly UserService userService; public StatisticsModule(UserService userService) { @@ -32,10 +32,10 @@ public async Task TeamsStatistics() }; int withoutTeam = 0; - var users = Context.Guild.Users.Where(t => !t.IsBot); - foreach (var user in users) + IEnumerable users = Context.Guild.Users.Where(t => !t.IsBot); + foreach (Discord.WebSocket.SocketGuildUser user in users) { - var team = userService.GetTeam(user); + PokemonTeam? team = userService.GetTeam(user); if (team != null) groups[team.Value]++; else @@ -43,7 +43,7 @@ public async Task TeamsStatistics() } EmbedBuilder embedBuilder = new EmbedBuilder(); - foreach (var item in groups) + foreach (KeyValuePair item in groups) embedBuilder.AddInlineField(item.Key.ToString(), item.Value); if (withoutTeam != 0) embedBuilder.AddInlineField("Bez teamu", withoutTeam); @@ -56,7 +56,7 @@ public async Task TeamsStatistics() [Summary("Vypíše informace o levelech hráčů.")] public async Task LevelStatistics() { - var players = userService.GetPlayers(Context.Guild.Users) + List players = userService.GetPlayers(Context.Guild.Users) .Where(t => t?.Team != null && t?.Level != null) .ToList(); @@ -70,7 +70,7 @@ public async Task LevelStatistics() double averageLevel = groupedPlayersPerTeam.Values.Average(t => t.AverageLevel); - var embedBuilder = new EmbedBuilder() + EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle("Průmerné levely"); foreach (var team in groupedPlayersPerTeam) embedBuilder.AddInlineField($"{team.Key} ({team.Value.Players.Count})", $"{team.Value.AverageLevel:f2}"); @@ -79,4 +79,4 @@ public async Task LevelStatistics() await ReplyAsync(string.Empty, embed: embedBuilder.Build()); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Modules/TestModule.cs b/PoGo.DiscordBot/Modules/TestModule.cs index c56b15a..3451851 100644 --- a/PoGo.DiscordBot/Modules/TestModule.cs +++ b/PoGo.DiscordBot/Modules/TestModule.cs @@ -7,7 +7,7 @@ namespace PoGo.DiscordBot.Modules [RequireOwner] public class TestModule : ModuleBase { - readonly ILogger logger; + private readonly ILogger logger; public TestModule(ILogger logger) { @@ -22,4 +22,4 @@ public async Task Test(string a, string b) await Task.CompletedTask; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/PoGo.DiscordBot.csproj b/PoGo.DiscordBot/PoGo.DiscordBot.csproj index 8eb85c1..4084bad 100644 --- a/PoGo.DiscordBot/PoGo.DiscordBot.csproj +++ b/PoGo.DiscordBot/PoGo.DiscordBot.csproj @@ -24,6 +24,28 @@ + + + True + True + Resources.resx + + + + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + + + PublicResXFileCodeGenerator + Resources.Designer.cs + + + + appsettings.json @@ -38,5 +60,5 @@ configuration.json - + diff --git a/PoGo.DiscordBot/PoGoBot.cs b/PoGo.DiscordBot/PoGoBot.cs index 561a33c..ce4abc4 100644 --- a/PoGo.DiscordBot/PoGoBot.cs +++ b/PoGo.DiscordBot/PoGoBot.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; using PoGo.DiscordBot.Modules.Preconditions; +using PoGo.DiscordBot.Properties; using PoGo.DiscordBot.Services; using System; using System.Diagnostics; @@ -24,11 +25,11 @@ public class PoGoBot : IDisposable public IServiceProvider ServiceProvider { get; } public IConfiguration Configuration { get; } - readonly DiscordSocketClient client; - readonly CommandService commands; - readonly ILogger logger; - readonly ConfigurationOptions configuration; - readonly Timer updateRaidsTimer; + private readonly DiscordSocketClient client; + private readonly CommandService commands; + private readonly ILogger logger; + private readonly ConfigurationOptions configuration; + private readonly Timer updateRaidsTimer; public PoGoBot() { @@ -45,7 +46,7 @@ public PoGoBot() .AddJsonFile($"appsettings.{environment}.json", false) .Build(); - var logSeverity = Enum.Parse(Configuration["Logging:LogLevel:Discord"]); + LogSeverity logSeverity = Enum.Parse(Configuration["Logging:LogLevel:Discord"]); client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = logSeverity, @@ -69,14 +70,14 @@ public PoGoBot() updateRaidsTimer = new Timer(async state => { - var raidService = (RaidService)state; + RaidService raidService = (RaidService)state; await raidService.UpdateRaidMessages(); }, ServiceProvider.GetService(), Timeout.Infinite, Timeout.Infinite); Init(); } - void Init() + private void Init() { client.Log += Log; commands.Log += Log; @@ -94,71 +95,71 @@ void Init() client.MessageDeleted += OnMessageDeleted; } - async Task OnMessageDeleted(Cacheable message, ISocketMessageChannel channel) + private async Task OnMessageDeleted(Cacheable message, ISocketMessageChannel channel) { - var raidService = ServiceProvider.GetService(); + RaidService raidService = ServiceProvider.GetService(); await raidService.OnMessageDeleted(message, channel); } - async Task OnUserJoined(SocketGuildUser user) + private async Task OnUserJoined(SocketGuildUser user) { - var userService = ServiceProvider.GetService(); + UserService userService = ServiceProvider.GetService(); await userService.OnUserJoined(user); } - async Task GuildAvailable(SocketGuild guild) + private async Task GuildAvailable(SocketGuild guild) { logger.LogInformation($"New guild: '{guild.Name}'"); - var teamService = ServiceProvider.GetService(); + TeamService teamService = ServiceProvider.GetService(); await teamService.OnNewGuild(guild); - var raidChannelService = ServiceProvider.GetService(); - var guildOptions = ServiceProvider.GetService>().Value.Guilds; + RaidChannelService raidChannelService = ServiceProvider.GetService(); + GuildOptions[] guildOptions = ServiceProvider.GetService>().Value.Guilds; raidChannelService.OnNewGuild(guild, guildOptions); - var raidService = ServiceProvider.GetService(); + RaidService raidService = ServiceProvider.GetService(); await raidService.OnNewGuild(guild); } - async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) + private async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { - var raidService = ServiceProvider.GetService(); + RaidService raidService = ServiceProvider.GetService(); await raidService.OnReactionRemoved(message, channel, reaction); } - async Task ReactionAdded(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) + private async Task ReactionAdded(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { - var raidService = ServiceProvider.GetService(); + RaidService raidService = ServiceProvider.GetService(); await raidService.OnReactionAdded(message, channel, reaction); } - async Task JoinedGuild(SocketGuild guild) + private async Task JoinedGuild(SocketGuild guild) { - var raidService = ServiceProvider.GetService(); + RaidService raidService = ServiceProvider.GetService(); await raidService.OnNewGuild(guild); } - Task LoggedIn() + private Task LoggedIn() { logger.LogInformation("Logged in"); return Task.CompletedTask; } - Task LoggedOut() + private Task LoggedOut() { logger.LogInformation("Logged out"); return Task.CompletedTask; } - async Task Connected() + private async Task Connected() { logger.LogInformation("Connected"); await client.SetGameAsync(Debugger.IsAttached ? "Debugging" : "Pokémon GO"); updateRaidsTimer.Change(TimeSpan.FromSeconds(120 - DateTime.Now.Second), TimeSpan.FromMinutes(1)); } - Task Disconnected(Exception exception) + private Task Disconnected(Exception exception) { logger.LogInformation(exception, "Disconnected"); updateRaidsTimer.Change(Timeout.Infinite, Timeout.Infinite); @@ -167,7 +168,7 @@ Task Disconnected(Exception exception) public IServiceProvider ConfigureServices() { - var services = new ServiceCollection(); + ServiceCollection services = new ServiceCollection(); services.AddOptions(); services.Configure(Configuration); @@ -204,16 +205,16 @@ public async Task RunAsync() await client.StartAsync(); } - async Task InitCommands() + private async Task InitCommands() { - var modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); + System.Collections.Generic.IEnumerable modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); logger.LogDebug("Loading modules"); - foreach (var module in modules) + foreach (ModuleInfo module in modules) logger.LogDebug($"{module.Name}: {string.Join(", ", module.Commands.Select(t => t.Name))}"); logger.LogDebug("Modules loaded"); } - async Task HandleCommand(SocketMessage messageParam) + private async Task HandleCommand(SocketMessage messageParam) { // Don't process the command if it was a System Message if (!(messageParam is SocketUserMessage message)) @@ -223,10 +224,10 @@ async Task HandleCommand(SocketMessage messageParam) // Determine if the message is a command, based on if it starts with '!' or a mention prefix if (!(message.HasCharPrefix(configuration.Prefix, ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) return; // Create a Command Context - var context = new SocketCommandContext(client, message); - // Execute the command. (result does not indicate a return value, + SocketCommandContext context = new SocketCommandContext(client, message); + // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed succesfully) - var result = await commands.ExecuteAsync(context, argPos, ServiceProvider); + IResult result = await commands.ExecuteAsync(context, argPos, ServiceProvider); if (!result.IsSuccess) { if (result.Error == CommandError.BadArgCount) @@ -234,12 +235,12 @@ async Task HandleCommand(SocketMessage messageParam) const string TooFewArgs = "The input text has too few parameters."; const string TooManyArgs = "The input text has too many parameters."; if (result.ErrorReason == TooFewArgs) - await context.Channel.SendMessageAsync("Chybí některý z parametrů."); + await context.Channel.SendMessageAsync(Resources.TooFewArgs); else if (result.ErrorReason == TooManyArgs) - await context.Channel.SendMessageAsync("Hodně parametrů - nechybí ti tam uvozovky?"); + await context.Channel.SendMessageAsync(Resources.TooManyArgs); } else if (result.Error == CommandError.ParseFailed) - await context.Channel.SendMessageAsync("Špatné parametry."); + await context.Channel.SendMessageAsync(Resources.BadParameters); else if (result is TeamPreconditionResult teamResult) await context.Channel.SendMessageAsync(teamResult.ErrorReason); @@ -248,7 +249,7 @@ async Task HandleCommand(SocketMessage messageParam) // await context.Channel.SendMessageAsync(result.ErrorReason); } - Task Log(LogMessage message) + private Task Log(LogMessage message) { LogLevel logLevel = message.Severity.ToLogLevel(); logger.Log(logLevel, 0, message, null, LogMessageFormatter); @@ -259,9 +260,9 @@ Task Log(LogMessage message) return Task.CompletedTask; } - string LogMessageFormatter(LogMessage message, Exception exception) + private string LogMessageFormatter(LogMessage message, Exception exception) { return $"{message.Source}: {message.Message}"; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Program.cs b/PoGo.DiscordBot/Program.cs index 73963e3..bf30fff 100644 --- a/PoGo.DiscordBot/Program.cs +++ b/PoGo.DiscordBot/Program.cs @@ -1,17 +1,21 @@ -using System.Threading; +using PoGo.DiscordBot.Properties; +using System; +using System.Globalization; +using System.Threading; using System.Threading.Tasks; namespace PoGo.DiscordBot { - class Program + internal class Program { - static async Task Main(string[] args) + private static async Task Main(string[] args) { - using (var bot = new PoGoBot()) + using (PoGoBot bot = new PoGoBot()) { + Console.WriteLine(Resources.FullUse); await bot.RunAsync(); await Task.Delay(Timeout.Infinite); } } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Properties/PublishProfiles/FolderProfile.pubxml b/PoGo.DiscordBot/Properties/PublishProfiles/FolderProfile.pubxml index 548b9af..ae788bf 100644 --- a/PoGo.DiscordBot/Properties/PublishProfiles/FolderProfile.pubxml +++ b/PoGo.DiscordBot/Properties/PublishProfiles/FolderProfile.pubxml @@ -1,7 +1,7 @@  diff --git a/PoGo.DiscordBot/Properties/Resources.Designer.cs b/PoGo.DiscordBot/Properties/Resources.Designer.cs new file mode 100644 index 0000000..259d7bb --- /dev/null +++ b/PoGo.DiscordBot/Properties/Resources.Designer.cs @@ -0,0 +1,549 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace PoGo.DiscordBot.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("PoGo.DiscordBot.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Adds a role to the user. + /// + public static string AddRoleSummary { + get { + return ResourceManager.GetString("AddRoleSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Rebuilds boss raid. + /// + public static string AdjustRaidBossSummary { + get { + return ResourceManager.GetString("AdjustRaidBossSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It will reset the raid time. + /// + public static string AdjustRaidTimeSummary { + get { + return ResourceManager.GetString("AdjustRaidTimeSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to All Commands. + /// + public static string AllCommands { + get { + return ResourceManager.GetString("AllCommands", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Available commands. + /// + public static string AvailableCommands { + get { + return ResourceManager.GetString("AvailableCommands", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Bad parameters. + /// + public static string BadParameters { + get { + return ResourceManager.GetString("BadParameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Time is not in valid format. + /// + public static string BadTimeFormat { + get { + return ResourceManager.GetString("BadTimeFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Basic Use. + /// + public static string BasicUse { + get { + return ResourceManager.GetString("BasicUse", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Boss. + /// + public static string Boss { + get { + return ResourceManager.GetString("Boss", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Name of the boss.. + /// + public static string BossName { + get { + return ResourceManager.GetString("BossName", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Checks whether the user has a team set up. If not, he will receive a message with information on how to set it. + /// + public static string CheckTeamSummary { + get { + return ResourceManager.GetString("CheckTeamSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Command. + /// + public static string Command { + get { + return ResourceManager.GetString("Command", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No command found {0}, I couldn't find it. + /// + public static string CommandNotFound { + get { + return ResourceManager.GetString("CommandNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Controlled user. + /// + public static string ControlledUser { + get { + return ResourceManager.GetString("ControlledUser", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Current Level (1-40). + /// + public static string CurrentLevel { + get { + return ResourceManager.GetString("CurrentLevel", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to date. + /// + public static string Date { + get { + return ResourceManager.GetString("Date", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Date is not in valid format . + /// + public static string DateNotValid { + get { + return ResourceManager.GetString("DateNotValid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deletes all messages (limited). + /// + public static string DeleteAllMessagesSummary { + get { + return ResourceManager.GetString("DeleteAllMessagesSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deletes tagged user messages (limited). + /// + public static string DeleteLastMessageSummary { + get { + return ResourceManager.GetString("DeleteLastMessageSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Delete Raid. + /// + public static string DeleteRaidSummary { + get { + return ResourceManager.GetString("DeleteRaidSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Deletes your messages (limited). + /// + public static string DeleteYourMessagesSummary { + get { + return ResourceManager.GetString("DeleteYourMessagesSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Description. + /// + public static string Description { + get { + return ResourceManager.GetString("Description", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Full Use. + /// + public static string FullUse { + get { + return ResourceManager.GetString("FullUse", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Lists help for a specific command. + /// + public static string HelpSummary { + get { + return ResourceManager.GetString("HelpSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You're in the team. + /// + public static string InTeam { + get { + return ResourceManager.GetString("InTeam", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Returns a link to the Discord invitation here. + /// + public static string InviteSummary { + get { + return ResourceManager.GetString("InviteSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Lists Commands.. + /// + public static string ListCommandsSummary { + get { + return ResourceManager.GetString("ListCommandsSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Number Of Messages. + /// + public static string MessageNumber { + get { + return ResourceManager.GetString("MessageNumber", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to none here. + /// + public static string NoDefaultChannel { + get { + return ResourceManager.GetString("NoDefaultChannel", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Optional, default is. + /// + public static string Optional { + get { + return ResourceManager.GetString("Optional", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Other players (without Discord, 2nd mobile, etc.). + /// + public static string OtherPlayers { + get { + return ResourceManager.GetString("OtherPlayers", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parameter Description. + /// + public static string ParameterDescription { + get { + return ResourceManager.GetString("ParameterDescription", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Parameters. + /// + public static string Parameters { + get { + return ResourceManager.GetString("Parameters", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Do you really want to create a raid in the past?. + /// + public static string PastRaid { + get { + return ResourceManager.GetString("PastRaid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Place. + /// + public static string Place { + get { + return ResourceManager.GetString("Place", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You probably play another game ... the allowed level is 1-40. + /// + public static string PlayAnotherGame { + get { + return ResourceManager.GetString("PlayAnotherGame", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Players. + /// + public static string Players { + get { + return ResourceManager.GetString("Players", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Only these values ​​are possible. + /// + public static string PossibleValues { + get { + return ResourceManager.GetString("PossibleValues", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Lists basic boss info. + /// + public static string RaidBossInfoSummary { + get { + return ResourceManager.GetString("RaidBossInfoSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Raid not found.. + /// + public static string RaidNotFound { + get { + return ResourceManager.GetString("RaidNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to It is not possible to create a scheduled raid poll from this channel. + /// + public static string RaidNotPossible { + get { + return ResourceManager.GetString("RaidNotPossible", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Selected team (role). + /// + public static string SelectedTeam { + get { + return ResourceManager.GetString("SelectedTeam", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sets team and level. + /// + public static string SetBasicInfoSummary { + get { + return ResourceManager.GetString("SetBasicInfoSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sets the level. + /// + public static string SetLevelSummary { + get { + return ResourceManager.GetString("SetLevelSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Sets the team. + /// + public static string SetTeamSummary { + get { + return ResourceManager.GetString("SetTeamSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creates a raid poll in a special channel.. + /// + public static string StartRaidSummary { + get { + return ResourceManager.GetString("StartRaidSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Creates a scheduled raid poll in a special channel. + /// + public static string StartScheduledRaidSummary { + get { + return ResourceManager.GetString("StartScheduledRaidSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to If you would like to support the development, please contact Pako # 3904. + /// + public static string SupportDevelopment { + get { + return ResourceManager.GetString("SupportDevelopment", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to time. + /// + public static string Time { + get { + return ResourceManager.GetString("Time", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The input text has too few parameters. + /// + public static string TooFewArgs { + get { + return ResourceManager.GetString("TooFewArgs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The input text has too many parameters. + /// + public static string TooManyArgs { + get { + return ResourceManager.GetString("TooManyArgs", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to User. + /// + public static string User { + get { + return ResourceManager.GetString("User", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Where. + /// + public static string Where { + get { + return ResourceManager.GetString("Where", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Without Team. + /// + public static string WithoutTeam { + get { + return ResourceManager.GetString("WithoutTeam", resourceCulture); + } + } + } +} diff --git a/PoGo.DiscordBot/Resources/Global.cs.resx b/PoGo.DiscordBot/Properties/Resources.cs.resx similarity index 89% rename from PoGo.DiscordBot/Resources/Global.cs.resx rename to PoGo.DiscordBot/Properties/Resources.cs.resx index 7ff3d11..cd42ba1 100644 --- a/PoGo.DiscordBot/Resources/Global.cs.resx +++ b/PoGo.DiscordBot/Properties/Resources.cs.resx @@ -120,18 +120,30 @@ Přidá uživateli roli + + Přenastaví bosse raidu + Přenastaví čas raidu + + Všechny příkazy + Dostupné příkazy + + Špatné parametry + Čas není ve validním formátu Základní použití + + Boss + Název bosse @@ -175,11 +187,23 @@ Plné použití - Vypíše seznam příkazů. + Vypíše nápovědu pro konkrétní příkaz Už jsi v teamu + + Vrátí odkaz s pozvánkou sem na Discord + + + Vypíše seznam příkazů. + + + Počet zpráv + + + žádný tu nemám + Volitelný, výchozí hodnota je @@ -226,7 +250,7 @@ Nastaví level - Sets the team + Nastaví tým. Vytvoří raid anketu do speciálního kanálu. @@ -240,6 +264,15 @@ Čas + + Chybí některý z parametrů + + + Hodně parametrů - nechybí ti tam uvozovky? + + + Uživatel + Kde diff --git a/PoGo.DiscordBot/Resources/Global.en.resx b/PoGo.DiscordBot/Properties/Resources.en.resx similarity index 89% rename from PoGo.DiscordBot/Resources/Global.en.resx rename to PoGo.DiscordBot/Properties/Resources.en.resx index d795f6e..4b60c79 100644 --- a/PoGo.DiscordBot/Resources/Global.en.resx +++ b/PoGo.DiscordBot/Properties/Resources.en.resx @@ -120,18 +120,30 @@ Adds a role to the user + + Rebuilds boss raid + It will reset the raid time + + All Commands + Available commands + + Bad parameters + Time is not in valid format Basic Use + + Boss + Name of the boss. @@ -175,11 +187,23 @@ Full Use - Lists commands. + Lists help for a specific command You're in the team + + Returns a link to the Discord invitation here + + + Lists Commands + + + Number Of Messages + + + None here + Optional, default is @@ -240,6 +264,15 @@ time + + The input text has too few parameters + + + The input text has too many parameters + + + User + Where diff --git a/PoGo.DiscordBot/Properties/Resources.resx b/PoGo.DiscordBot/Properties/Resources.resx new file mode 100644 index 0000000..c030c42 --- /dev/null +++ b/PoGo.DiscordBot/Properties/Resources.resx @@ -0,0 +1,282 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Adds a role to the user + + + Rebuilds boss raid + + + It will reset the raid time + + + All Commands + + + Available commands + + + Bad parameters + + + Time is not in valid format + + + Basic Use + + + Boss + + + Name of the boss. + + + Checks whether the user has a team set up. If not, he will receive a message with information on how to set it + + + Command + + + No command found {0}, I couldn't find it + + + Controlled user + + + Current Level (1-40) + + + date + + + Date is not in valid format + + + Deletes all messages (limited) + + + Deletes tagged user messages (limited) + + + Delete Raid + + + Deletes your messages (limited) + + + Description + + + Full Use + + + Lists help for a specific command + + + You're in the team + + + Returns a link to the Discord invitation here + + + Lists Commands. + + + Number Of Messages + + + none here + + + Optional, default is + + + Other players (without Discord, 2nd mobile, etc.) + + + Parameter Description + + + Parameters + + + Do you really want to create a raid in the past? + + + Place + + + You probably play another game ... the allowed level is 1-40 + + + Players + + + Only these values ​​are possible + + + Lists basic boss info + + + Raid not found. + + + It is not possible to create a scheduled raid poll from this channel + + + Selected team (role) + + + Sets team and level + + + Sets the level + + + Sets the team + + + Creates a raid poll in a special channel. + + + Creates a scheduled raid poll in a special channel + + + If you would like to support the development, please contact Pako # 3904 + + + time + + + The input text has too few parameters + + + The input text has too many parameters + + + User + + + Where + + + Without Team + + \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/ConfigurationService.cs b/PoGo.DiscordBot/Services/ConfigurationService.cs index 3c7806e..67c288e 100644 --- a/PoGo.DiscordBot/Services/ConfigurationService.cs +++ b/PoGo.DiscordBot/Services/ConfigurationService.cs @@ -6,13 +6,16 @@ namespace PoGo.DiscordBot.Services { public class ConfigurationService { - readonly ConfigurationOptions configurationOptions; + private readonly ConfigurationOptions configurationOptions; public ConfigurationService(IOptions configurationOptions) { this.configurationOptions = configurationOptions.Value; } - public GuildOptions GetGuildOptions(ulong guildId) => configurationOptions.Guilds.FirstOrDefault(t => t.Id == guildId); + public GuildOptions GetGuildOptions(ulong guildId) + { + return configurationOptions.Guilds.FirstOrDefault(t => t.Id == guildId); + } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/GymLocationService.cs b/PoGo.DiscordBot/Services/GymLocationService.cs index 98f7eff..2e3e2aa 100644 --- a/PoGo.DiscordBot/Services/GymLocationService.cs +++ b/PoGo.DiscordBot/Services/GymLocationService.cs @@ -9,7 +9,7 @@ namespace PoGo.DiscordBot.Services { public class GymLocationService { - readonly Dictionary gymsInfos; // + private readonly Dictionary gymsInfos; // public GymLocationService(IOptions options) { @@ -21,19 +21,22 @@ public GymLocationService(IOptions options) Latitude = g.Latitude, Longitude = g.Longitude })).ToArray()); - } + } public IEnumerable Search(ulong guildId, string name) { - if (!gymsInfos.TryGetValue(guildId, out var gyms)) + if (!gymsInfos.TryGetValue(guildId, out (string NormalizedName, GymInfoDto GymInfo)[] gyms)) return default; - var normalizedName = StringUtils.ToLowerWithoutDiacritics(name); + string normalizedName = StringUtils.ToLowerWithoutDiacritics(name); return gyms .Where(t => t.NormalizedName.Contains(normalizedName)) .Select(t => t.GymInfo); } - public string GetMapUrl(GymInfoDto gymInfo) => $"http://maps.google.com/maps?q={gymInfo.Latitude},{gymInfo.Longitude}"; + public string GetMapUrl(GymInfoDto gymInfo) + { + return $"http://maps.google.com/maps?q={gymInfo.Latitude},{gymInfo.Longitude}"; + } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/LocalizationService.cs b/PoGo.DiscordBot/Services/LocalizationService.cs deleted file mode 100644 index a3427e5..0000000 --- a/PoGo.DiscordBot/Services/LocalizationService.cs +++ /dev/null @@ -1,35 +0,0 @@ -using Microsoft.Extensions.Localization; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Reflection; -using System.Resources; -using System.Text; - -namespace PoGo.DiscordBot.Services -{ - public class LocalizationService - { - protected ResourceManager resourceManager; - - private static readonly Lazy lazy - = new Lazy(() - => new LocalizationService()); - - private LocalizationService() - { - resourceManager = new ResourceManager("PoGo.DiscordBot", - Assembly.GetExecutingAssembly()); - } - - public static LocalizationService Instance - { - get - { - return lazy.Value; - } - } - - public string GetStringFromResources(String keyName) => resourceManager.GetString(keyName); - } -} diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index c8f7981..660893c 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -9,7 +9,7 @@ namespace PoGo.DiscordBot.Services { public class RaidBossInfoService { - readonly Dictionary raidBosses; // + private readonly Dictionary raidBosses; // public RaidBossInfoService(IOptions options) { @@ -24,16 +24,21 @@ public RaidBossInfoService(IOptions options) }); } - public IEnumerable GetAllKnownBossNames() => raidBosses.Values - .Select(t => t.BossName) - .OrderBy(t => t); + public IEnumerable GetAllKnownBossNames() + { + return raidBosses.Values +.Select(t => t.BossName) +.OrderBy(t => t); + } - public RaidBossDto GetBoss(string bossName) => - raidBosses.TryGetValue(bossName.ToLower(), out var dto) ? dto : null; + public RaidBossDto GetBoss(string bossName) + { + return raidBosses.TryGetValue(bossName.ToLower(), out RaidBossDto dto) ? dto : null; + } public string GetBossNameWithEmoji(string bossName, SocketGuild guild) { - var emote = guild.Emotes.FirstOrDefault(t => string.Compare(t.Name, bossName, true) == 0); + Discord.GuildEmote emote = guild.Emotes.FirstOrDefault(t => string.Compare(t.Name, bossName, true) == 0); if (emote != null) return $"{bossName} {emote}"; @@ -41,4 +46,4 @@ public string GetBossNameWithEmoji(string bossName, SocketGuild guild) return bossName; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/RaidChannelService.cs b/PoGo.DiscordBot/Services/RaidChannelService.cs index 2deac06..8de6579 100644 --- a/PoGo.DiscordBot/Services/RaidChannelService.cs +++ b/PoGo.DiscordBot/Services/RaidChannelService.cs @@ -10,7 +10,7 @@ namespace PoGo.DiscordBot.Services { public class RaidChannelService { - class RaidChannelBinding + private class RaidChannelBinding { public ITextChannel From { get; } public ITextChannel To { get; } @@ -26,8 +26,8 @@ public RaidChannelBinding(ITextChannel from, ITextChannel to, IMentionable menti } } - readonly Dictionary> guilds; // - readonly ILogger logger; + private readonly Dictionary> guilds; // + private readonly ILogger logger; public RaidChannelService(ILogger logger) { @@ -37,7 +37,7 @@ public RaidChannelService(ILogger logger) public void OnNewGuild(SocketGuild guild, GuildOptions[] guildOptions) { - var guildConfig = guildOptions.FirstOrDefault(t => t.Id == guild.Id); + GuildOptions guildConfig = guildOptions.FirstOrDefault(t => t.Id == guild.Id); if (guildConfig == null) { logger.LogWarning($"Unknown guild with id '{guild.Id}', name '{guild.Name}'"); @@ -50,19 +50,27 @@ public void OnNewGuild(SocketGuild guild, GuildOptions[] guildOptions) return; } - var channelBindings = guilds[guild.Id] = new List(); + List channelBindings = guilds[guild.Id] = new List(); // go through configured channels and register them - foreach (var channel in guildConfig.Channels) + foreach (ChannelOptions channel in guildConfig.Channels) AddBindingIfValid(channelBindings, guild, channel); } - public bool IsKnown(ulong guildId) => guilds.ContainsKey(guildId); + public bool IsKnown(ulong guildId) + { + return guilds.ContainsKey(guildId); + } - public bool IsKnown(ulong guildId, ulong textChannelId) => - TryGetRaidChannelBinding(guildId, textChannelId) != null; + public bool IsKnown(ulong guildId, ulong textChannelId) + { + return TryGetRaidChannelBinding(guildId, textChannelId) != null; + } - public IEnumerable GetRaidChannels(ulong guildId) => guilds[guildId].Select(t => t.To); + public IEnumerable GetRaidChannels(ulong guildId) + { + return guilds[guildId].Select(t => t.To); + } /// /// Returns raid channel for the raid poll based on the channel where the command came from. @@ -71,9 +79,9 @@ public bool IsKnown(ulong guildId, ulong textChannelId) => /// todo: describe fromTextChannelId parameter on TryGetRaidChannelBinding public RaidChannelBindingDto TryGetRaidChannelBinding(ulong guildId, ulong fromTextChannelId) { - if (guilds.TryGetValue(guildId, out var raidChannelBindings)) + if (guilds.TryGetValue(guildId, out List raidChannelBindings)) { - foreach (var channel in raidChannelBindings) + foreach (RaidChannelBinding channel in raidChannelBindings) { if (channel.From == null || channel.From.Id == fromTextChannelId) { @@ -92,8 +100,8 @@ public RaidChannelBindingDto TryGetRaidChannelBinding(ulong guildId, ulong fromT public RaidChannelBindingDto TryGetRaidChannelBindingTo(ulong guildId, ulong toTextChannelId) { - if (guilds.TryGetValue(guildId, out var raidChannelBindings)) - foreach (var channel in raidChannelBindings) + if (guilds.TryGetValue(guildId, out List raidChannelBindings)) + foreach (RaidChannelBinding channel in raidChannelBindings) if (channel.To.Id == toTextChannelId) return new RaidChannelBindingDto { @@ -105,10 +113,10 @@ public RaidChannelBindingDto TryGetRaidChannelBindingTo(ulong guildId, ulong toT return null; } - void AddBindingIfValid(List channelBindings, SocketGuild guild, ChannelOptions channelOptions) + private void AddBindingIfValid(List channelBindings, SocketGuild guild, ChannelOptions channelOptions) { - var channelFrom = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.From); - var channelTo = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.To); + SocketTextChannel channelFrom = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.From); + SocketTextChannel channelTo = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.To); bool channelFromBinding = channelFrom == null && channelOptions.From != "*"; bool channelToBinding = channelTo == null; @@ -132,4 +140,4 @@ void AddBindingIfValid(List channelBindings, SocketGuild gui channelBindings.Add(new RaidChannelBinding(channelFrom, channelTo, mention, channelOptions.ScheduledRaids)); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/RaidService.cs b/PoGo.DiscordBot/Services/RaidService.cs index 79ae353..5cacca1 100644 --- a/PoGo.DiscordBot/Services/RaidService.cs +++ b/PoGo.DiscordBot/Services/RaidService.cs @@ -11,13 +11,12 @@ namespace PoGo.DiscordBot.Services { public class RaidService { - const ulong DefaultRaidChannelId = 348844165741936641; - - static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; - readonly ILogger logger; - readonly UserService userService; - readonly RaidChannelService raidChannelService; - readonly RaidStorageService raidStorageService; + private const ulong DefaultRaidChannelId = 348844165741936641; + private static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; + private readonly ILogger logger; + private readonly UserService userService; + private readonly RaidChannelService raidChannelService; + private readonly RaidStorageService raidStorageService; public RaidService(ILogger logger, UserService userService, RaidChannelService raidChannelService, RaidStorageService raidStorageService) { @@ -33,7 +32,7 @@ public async Task OnNewGuild(SocketGuild guild) // ignore unknown guilds for now return; - foreach (var channel in raidChannelService.GetRaidChannels(guild.Id)) + foreach (ITextChannel channel in raidChannelService.GetRaidChannels(guild.Id)) await UpdateRaidMessages(guild, channel); } @@ -41,19 +40,19 @@ public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, { try { - var channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); - var mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; - var dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.AddHours(-2) : DateTime.UtcNow.AddDays(-14); + RaidChannelBindingDto channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); + bool mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; + DateTime dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.AddHours(-2) : DateTime.UtcNow.AddDays(-14); - var batchMessages = await channel.GetMessagesAsync(count, options: retryOptions) + List> batchMessages = await channel.GetMessagesAsync(count, options: retryOptions) .ToList(); - var latestMessages = batchMessages.SelectMany(t => t.Where(m => m.CreatedAt.UtcDateTime > dateTimeFrom)) + List latestMessages = batchMessages.SelectMany(t => t.Where(m => m.CreatedAt.UtcDateTime > dateTimeFrom)) .ToList(); if (!latestMessages.Any()) return; logger.LogInformation($"start updating raid messages for channel '{channel.Name}'"); - foreach (var message in latestMessages) + foreach (IMessage message in latestMessages) if (message is IUserMessage userMessage) await FixRaidMessageAfterLoad(guild, userMessage); logger.LogInformation($"end updating raid messages for channel '{channel.Name}'"); @@ -64,9 +63,9 @@ public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, } } - async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message) + private async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message) { - var raidInfo = RaidInfoDto.Parse(message); + RaidInfoDto raidInfo = RaidInfoDto.Parse(message); if (raidInfo == null) return false; @@ -74,33 +73,33 @@ async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message raidStorageService.AddRaid(guild.Id, message.Channel.Id, message.Id, raidInfo); // Adjust user count - var allUsersWithThumbsUp = await message.GetReactionUsersAsync(UnicodeEmojis.ThumbsUp); - var usersWithThumbsUp = allUsersWithThumbsUp + IReadOnlyCollection allUsersWithThumbsUp = await message.GetReactionUsersAsync(UnicodeEmojis.ThumbsUp); + IEnumerable usersWithThumbsUp = allUsersWithThumbsUp .Where(t => !t.IsBot) .Select(t => guild.GetUser(t.Id)) .Where(t => t != null); - foreach (var user in usersWithThumbsUp) + foreach (SocketGuildUser user in usersWithThumbsUp) raidInfo.Players[user.Id] = userService.GetPlayer(guild.GetUser(user.Id)); // Extra players for (int i = 0; i < UnicodeEmojis.KeycapDigits.Length; i++) { - var emoji = UnicodeEmojis.KeycapDigits[i]; - var usersWithKeycapReaction = await message.GetReactionUsersAsync(emoji); + string emoji = UnicodeEmojis.KeycapDigits[i]; + IReadOnlyCollection usersWithKeycapReaction = await message.GetReactionUsersAsync(emoji); - foreach (var user in usersWithKeycapReaction.Where(t => !t.IsBot)) + foreach (IUser user in usersWithKeycapReaction.Where(t => !t.IsBot)) raidInfo.ExtraPlayers.Add((user.Id, ExtraPlayerKeycapDigitToCount(emoji))); } await message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); - var allReactions = message.Reactions; - var invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); + IReadOnlyDictionary allReactions = message.Reactions; + List> invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); // Remove invalid reactions - foreach (var react in invalidReactions) + foreach (KeyValuePair react in invalidReactions) { - var users = await message.GetReactionUsersAsync(react.Key.Name, options: retryOptions); - foreach (var user in users) + IReadOnlyCollection users = await message.GetReactionUsersAsync(react.Key.Name, options: retryOptions); + foreach (IUser user in users) await message.RemoveReactionAsync(react.Key, user, options: retryOptions); } @@ -112,7 +111,7 @@ public Task OnMessageDeleted(Cacheable cacheableMessage, ISocke if (!(channel is SocketTextChannel socketChannel)) return Task.CompletedTask; - var messageId = cacheableMessage.Id; + ulong messageId = cacheableMessage.Id; if (raidStorageService.TryRemove(socketChannel.Guild.Id, socketChannel.Id, messageId)) logger.LogInformation($"Raid message '{messageId}' was removed."); @@ -125,25 +124,30 @@ public async Task SetDefaultReactions(IUserMessage message) await message.AddReactionAsync(Emojis.ThumbsDown, retryOptions); } - bool IsValidReactionEmote(string emote) => - emote == UnicodeEmojis.ThumbsUp || - emote == UnicodeEmojis.ThumbsDown || - UnicodeEmojis.KeycapDigits.Contains(emote); + private bool IsValidReactionEmote(string emote) + { + return emote == UnicodeEmojis.ThumbsUp || +emote == UnicodeEmojis.ThumbsDown || +UnicodeEmojis.KeycapDigits.Contains(emote); + } - int ExtraPlayerKeycapDigitToCount(string name) => Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; + private int ExtraPlayerKeycapDigitToCount(string name) + { + return Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; + } public async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { if (!(channel is SocketGuildChannel socketGuildChannel)) return; - var raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); + RaidInfoDto raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); if (raidInfo == null || raidInfo.IsExpired) return; IUserMessage raidMessage = await message.GetOrDownloadAsync(); if (reaction.Emote.Name == UnicodeEmojis.ThumbsUp) { - if (raidInfo.Players.TryGetValue(reaction.UserId, out var player)) + if (raidInfo.Players.TryGetValue(reaction.UserId, out PlayerDto player)) { logger.LogInformation($"Player '{player}' removed {nameof(UnicodeEmojis.ThumbsUp)} on raid {raidInfo.Message.Id}"); raidInfo.Players.Remove(reaction.UserId); @@ -152,7 +156,7 @@ public async Task OnReactionRemoved(Cacheable message, ISoc } else if (Emojis.KeycapDigits.Contains(reaction.Emote)) { - var count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); + int count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); if (raidInfo.ExtraPlayers.Remove((reaction.UserId, count))) await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } @@ -162,12 +166,12 @@ public async Task OnReactionAdded(Cacheable message, ISocke { if (!(channel is SocketGuildChannel socketGuildChannel)) return; - var raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); + RaidInfoDto raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); if (raidInfo == null || raidInfo.IsExpired) return; IUserMessage raidMessage = await message.GetOrDownloadAsync(); - var user = socketGuildChannel.GetUser(reaction.UserId); + SocketGuildUser user = socketGuildChannel.GetUser(reaction.UserId); if (user.IsBot) return; if (!IsValidReactionEmote(reaction.Emote.Name)) @@ -178,14 +182,14 @@ public async Task OnReactionAdded(Cacheable message, ISocke if (reaction.Emote.Name == UnicodeEmojis.ThumbsUp) { - var player = userService.GetPlayer(user); + PlayerDto player = userService.GetPlayer(user); raidInfo.Players[reaction.UserId] = player; logger.LogInformation($"Player '{player}' added {nameof(UnicodeEmojis.ThumbsUp)} on raid {raidInfo.Message.Id}"); await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } else if (Emojis.KeycapDigits.Contains(reaction.Emote)) { - var count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); + int count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); raidInfo.ExtraPlayers.Add((reaction.UserId, count)); await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } @@ -193,9 +197,9 @@ public async Task OnReactionAdded(Cacheable message, ISocke public async Task UpdateRaidMessages() { - var toRemove = new List<(ulong guildId, ulong channelId, ulong messageId)>(); + List<(ulong guildId, ulong channelId, ulong messageId)> toRemove = new List<(ulong guildId, ulong channelId, ulong messageId)>(); - foreach (var (guildId, channelId, messageId, raidInfo) in raidStorageService.GetAll()) + foreach ((ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfo) in raidStorageService.GetAll()) { await raidInfo.Message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); @@ -203,8 +207,8 @@ public async Task UpdateRaidMessages() toRemove.Add((guildId, channelId, messageId)); } - foreach (var (guildId, channelId, messageId) in toRemove) + foreach ((ulong guildId, ulong channelId, ulong messageId) in toRemove) raidStorageService.TryRemove(guildId, channelId, messageId); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/RaidStorageService.cs b/PoGo.DiscordBot/Services/RaidStorageService.cs index 4b49b76..1736470 100644 --- a/PoGo.DiscordBot/Services/RaidStorageService.cs +++ b/PoGo.DiscordBot/Services/RaidStorageService.cs @@ -9,7 +9,7 @@ public class RaidStorageService { // >> //readonly ConcurrentDictionary>> raids; - readonly RaidGuildMapping raidGuilds; + private readonly RaidGuildMapping raidGuilds; public RaidStorageService() { @@ -18,15 +18,15 @@ public RaidStorageService() public void AddRaid(ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfoDto) { - var raidChannels = raidGuilds.GuildRaids.GetOrAdd(guildId, _ => new RaidChannelMapping()); - var raidMessages = raidChannels.RaidChannels.GetOrAdd(channelId, _ => new RaidMessageMapping()); + RaidChannelMapping raidChannels = raidGuilds.GuildRaids.GetOrAdd(guildId, _ => new RaidChannelMapping()); + RaidMessageMapping raidMessages = raidChannels.RaidChannels.GetOrAdd(channelId, _ => new RaidMessageMapping()); raidMessages.RaidMessages[messageId] = raidInfoDto; } public RaidInfoDto GetRaid(ulong guildId, ulong channelId, int skip) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages)) return raidMessages.RaidMessages.Values .OrderByDescending(t => t.CreatedAt) .Skip(skip) @@ -37,23 +37,25 @@ public RaidInfoDto GetRaid(ulong guildId, ulong channelId, int skip) public RaidInfoDto GetRaid(ulong guildId, ulong channelId, ulong messageId) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && - raidMessages.RaidMessages.TryGetValue(messageId, out var raidInfoDto)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages) && + raidMessages.RaidMessages.TryGetValue(messageId, out RaidInfoDto raidInfoDto)) return raidInfoDto; return null; } - public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) => - raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && - raidMessages.RaidMessages.TryRemove(messageId, out _); + public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) + { + return raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && +raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages) && +raidMessages.RaidMessages.TryRemove(messageId, out _); + } public IEnumerable<(int Index, RaidInfoDto Raid)> GetActiveRaidsWithIndexes(ulong guildId, ulong channelId) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages)) return raidMessages.RaidMessages.Values .OrderByDescending(t => t.CreatedAt) .Select((t, i) => (i, t)) @@ -64,13 +66,13 @@ public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) => public IEnumerable<(ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfo)> GetAll() { - foreach (var guild in raidGuilds.GuildRaids) - foreach (var channel in guild.Value.RaidChannels) - foreach (var raidMessage in channel.Value.RaidMessages) + foreach (KeyValuePair guild in raidGuilds.GuildRaids) + foreach (KeyValuePair channel in guild.Value.RaidChannels) + foreach (KeyValuePair raidMessage in channel.Value.RaidMessages) yield return (guild.Key, channel.Key, raidMessage.Key, raidMessage.Value); } - class RaidGuildMapping + private class RaidGuildMapping { // public ConcurrentDictionary GuildRaids { get; } @@ -81,7 +83,7 @@ public RaidGuildMapping() } } - class RaidChannelMapping + private class RaidChannelMapping { // public ConcurrentDictionary RaidChannels { get; } @@ -92,7 +94,7 @@ public RaidChannelMapping() } } - class RaidMessageMapping + private class RaidMessageMapping { // public ConcurrentDictionary RaidMessages { get; } @@ -103,4 +105,4 @@ public RaidMessageMapping() } } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/RoleService.cs b/PoGo.DiscordBot/Services/RoleService.cs index c4a1752..260f904 100644 --- a/PoGo.DiscordBot/Services/RoleService.cs +++ b/PoGo.DiscordBot/Services/RoleService.cs @@ -5,6 +5,9 @@ namespace PoGo.DiscordBot.Services { public class RoleService { - public SocketRole GetRoleByName(SocketGuild guild, string name) => guild.Roles.FirstOrDefault(t => t.Name == name); + public SocketRole GetRoleByName(SocketGuild guild, string name) + { + return guild.Roles.FirstOrDefault(t => t.Name == name); + } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/TeamService.cs b/PoGo.DiscordBot/Services/TeamService.cs index 87834a2..f2c9b08 100644 --- a/PoGo.DiscordBot/Services/TeamService.cs +++ b/PoGo.DiscordBot/Services/TeamService.cs @@ -13,7 +13,7 @@ namespace PoGo.DiscordBot.Services { public class TeamService { - readonly ILogger logger; + private readonly ILogger logger; public ConcurrentDictionary GuildTeamRoles { get; } // @@ -28,9 +28,9 @@ public async Task OnNewGuild(SocketGuild socketGuild) GuildTeamRoles[socketGuild.Id] = await GetTeamRoles(socketGuild); } - async Task GetOrCreateRole(IGuild guild, PokemonTeam pokemonTeam) + private async Task GetOrCreateRole(IGuild guild, PokemonTeam pokemonTeam) { - var role = guild.Roles.FirstOrDefault(t => Enum.TryParse(t.Name, out var team) && pokemonTeam == team); + IRole role = guild.Roles.FirstOrDefault(t => Enum.TryParse(t.Name, out PokemonTeam team) && pokemonTeam == team); if (role == null) { logger.LogInformation($"Creating new role for team {pokemonTeam}"); @@ -44,14 +44,14 @@ await role.ModifyAsync(t => return role; } - async Task GetTeamRoles(IGuild guild) + private async Task GetTeamRoles(IGuild guild) { - var roleIdtoTeam = new Dictionary(); - var teamToRole = new Dictionary(); + Dictionary roleIdtoTeam = new Dictionary(); + Dictionary teamToRole = new Dictionary(); foreach (PokemonTeam team in Enum.GetValues(typeof(PokemonTeam))) { - var role = await GetOrCreateRole(guild, team); + IRole role = await GetOrCreateRole(guild, team); roleIdtoTeam[role.Id] = team; teamToRole[team] = role; @@ -64,4 +64,4 @@ async Task GetTeamRoles(IGuild guild) }; } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index b68cefb..cf0193b 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -13,8 +13,8 @@ namespace PoGo.DiscordBot.Services { public class UserService { - readonly ILogger logger; - readonly TeamService teamService; + private readonly ILogger logger; + private readonly TeamService teamService; public UserService(ILogger logger, TeamService teamService) { @@ -24,11 +24,11 @@ public UserService(ILogger logger, TeamService teamService) public static int? GetPlayerLevel(SocketGuildUser user) { - var name = user.Nickname ?? user.Username; - var result = Regex.Match(name, @"\(\d+\)"); - var stringLevel = result.Captures.LastOrDefault()?.Value; + string name = user.Nickname ?? user.Username; + Match result = Regex.Match(name, @"\(\d+\)"); + string stringLevel = result.Captures.LastOrDefault()?.Value; if (stringLevel != null - && int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out var level) + && int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out int level) && level >= 1 && level <= 40) { return level; @@ -39,11 +39,11 @@ public UserService(ILogger logger, TeamService teamService) public PokemonTeam? GetTeam(SocketGuildUser user) { - var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; + IReadOnlyDictionary teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; - foreach (var role in user.Roles) + foreach (SocketRole role in user.Roles) { - if (teamRoles.TryGetValue(role.Id, out var team)) + if (teamRoles.TryGetValue(role.Id, out PokemonTeam team)) { return team; } @@ -52,20 +52,26 @@ public UserService(ILogger logger, TeamService teamService) return null; } - public PlayerDto GetPlayer(SocketGuildUser user) => new PlayerDto + public PlayerDto GetPlayer(SocketGuildUser user) { - User = user, - Team = GetTeam(user), - Level = GetPlayerLevel(user), - }; + return new PlayerDto + { + User = user, + Team = GetTeam(user), + Level = GetPlayerLevel(user), + }; + } - public IEnumerable GetPlayers(IEnumerable users) => users - .Where(t => !t.IsBot) - .Select(GetPlayer); + public IEnumerable GetPlayers(IEnumerable users) + { + return users +.Where(t => !t.IsBot) +.Select(GetPlayer); + } public async Task CheckTeam(SocketGuildUser user) { - var team = GetTeam(user); + PokemonTeam? team = GetTeam(user); if (team == null) { @@ -86,4 +92,4 @@ public Task OnUserJoined(SocketGuildUser user) return CheckTeam(user); } } -} +} \ No newline at end of file diff --git a/PoGo.DiscordBot/configuration.Development.json b/PoGo.DiscordBot/configuration.Development.json index c885bc3..91265de 100644 --- a/PoGo.DiscordBot/configuration.Development.json +++ b/PoGo.DiscordBot/configuration.Development.json @@ -1,3 +1,3 @@ { - "Token": "" -} + "Token": "", +} \ No newline at end of file diff --git a/PoGo.DiscordBot/configuration.Production.json b/PoGo.DiscordBot/configuration.Production.json index c885bc3..9d79664 100644 --- a/PoGo.DiscordBot/configuration.Production.json +++ b/PoGo.DiscordBot/configuration.Production.json @@ -1,3 +1,3 @@ { "Token": "" -} +} \ No newline at end of file From 8956229ca2290169e954b91c878e129a27991d2f Mon Sep 17 00:00:00 2001 From: Aaron Date: Thu, 4 Apr 2019 19:00:47 -0400 Subject: [PATCH 03/10] Translate some more phrases Still have more to go. --- PoGo.DiscordBot/Modules/HelpModule.cs | 2 +- PoGo.DiscordBot/Modules/RaidModule.cs | 23 +++--- PoGo.DiscordBot/Modules/RoleModule.cs | 7 +- .../Properties/Resources.Designer.cs | 72 +++++++++++++++++++ PoGo.DiscordBot/Properties/Resources.cs.resx | 24 +++++++ PoGo.DiscordBot/Properties/Resources.en.resx | 24 +++++++ PoGo.DiscordBot/Properties/Resources.resx | 24 +++++++ 7 files changed, 161 insertions(+), 15 deletions(-) diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index 89b17db..d2f658d 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -19,7 +19,7 @@ public class HelpModule : InteractiveBase private readonly IServiceProvider serviceProvider; private readonly char prefix; //TODO Load the current culture info from guild - readonly CultureInfo cultureInfo = CultureInfo.GetCultureInfo("cs-CS"); + private readonly CultureInfo cultureInfo = CultureInfo.GetCultureInfo("cs-CS"); public HelpModule(CommandService commandService, IServiceProvider serviceProvider, IOptions config) { diff --git a/PoGo.DiscordBot/Modules/RaidModule.cs b/PoGo.DiscordBot/Modules/RaidModule.cs index 51c5b4d..474b84c 100644 --- a/PoGo.DiscordBot/Modules/RaidModule.cs +++ b/PoGo.DiscordBot/Modules/RaidModule.cs @@ -8,6 +8,7 @@ using PoGo.DiscordBot.Properties; using PoGo.DiscordBot.Services; using System; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -226,7 +227,7 @@ public async Task AdjustRaidBoss( [Command("mention", RunMode = RunMode.Async)] [Alias("m")] - [Summary("Označí lidi, kteří jsou zapsáni na raid.")] + [Summary("MentionRaidPlayersSummary")] [RaidChannelPrecondition] public async Task MentionRaidPlayers( [Summary("Počet anket odspodu.")] int skip = 0, @@ -240,7 +241,7 @@ public async Task MentionRaidPlayers( return; } - System.Collections.Generic.HashSet users = raid.Players.Values.ToHashSet(); + HashSet users = raid.Players.Values.ToHashSet(); if (users.Count > 0) { @@ -264,7 +265,7 @@ public async Task DeleteRaid( if (raid == null) { - await ReplyAsync("Raid nenalezen."); + await ReplyAsync(Resources.RaidNotFound); return; } @@ -299,7 +300,7 @@ public async Task RaidBossInfo( } string bossMention = raidBossInfoService.GetBossNameWithEmoji(boss.BossName, Context.Guild); - System.Collections.Generic.IEnumerable countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); + IEnumerable countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); string countersField = string.Join(", ", countersWithEmojis); EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle(bossMention) @@ -315,20 +316,20 @@ public async Task RaidBossInfo( [Command("location", RunMode = RunMode.Async)] [Alias("l", "loc")] - [Summary("Vrátí lokaci gymu.")] + [Summary("RaidLocationSummary")] public async Task RaidLocation( [Remainder][Summary("Část názvu gymu")]string name) { if (string.IsNullOrEmpty(name) || name.Length < 3) { - await ReplyAsync("Moc krátký název."); + await ReplyAsync(Resources.VeryShortName); return; } - System.Collections.Generic.IEnumerable searchResult = gymLocationService.Search(Context.Guild.Id, name); + IEnumerable searchResult = gymLocationService.Search(Context.Guild.Id, name); if (searchResult == null) { - await ReplyAsync("Server nepodporuje tenhle příkaz."); + await ReplyAsync(Resources.CommandNotSupported); return; } @@ -340,14 +341,14 @@ public async Task RaidLocation( } [Command("list", RunMode = RunMode.Async)] - [Summary("Vrátí seznam aktivních raidů včetně indexů.")] + [Summary("RaidListSummary")] public async Task RaidList() { ulong channelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; - System.Collections.Generic.IEnumerable<(int Index, RaidInfoDto Raid)> raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); + IEnumerable<(int Index, RaidInfoDto Raid)> raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); if (!raids.Any()) { - await ReplyAsync("Nejsou aktivní žádné raidy."); + await ReplyAsync(Resources.NoActiveRaids); return; } string message = string.Join(Environment.NewLine, raids.Select(t => $"{t.Index} - {t.Raid.ToSimpleString()}").Reverse()); diff --git a/PoGo.DiscordBot/Modules/RoleModule.cs b/PoGo.DiscordBot/Modules/RoleModule.cs index 4e74e4d..b7b6891 100644 --- a/PoGo.DiscordBot/Modules/RoleModule.cs +++ b/PoGo.DiscordBot/Modules/RoleModule.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using PoGo.DiscordBot.Configuration.Options; +using PoGo.DiscordBot.Properties; using PoGo.DiscordBot.Services; using System.Collections.Generic; using System.Linq; @@ -41,7 +42,7 @@ public async Task AddRole([Summary("Název role")]string roleName) SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { - await ReplyAsync("Neznámá role."); + await ReplyAsync(Resources.UnknownRole); return; } @@ -51,7 +52,7 @@ public async Task AddRole([Summary("Název role")]string roleName) [Command("remove")] [Alias("r")] - [Summary("Smaže uživateli roli.")] + [Summary("RemoveRoleSummary")] public async Task RemoveRole([Summary("Název role")]string roleName) { if (!(Context.User is SocketGuildUser user)) @@ -63,7 +64,7 @@ public async Task RemoveRole([Summary("Název role")]string roleName) SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { - await ReplyAsync("Neznámá role."); + await ReplyAsync(Resources.UnknownRole); return; } diff --git a/PoGo.DiscordBot/Properties/Resources.Designer.cs b/PoGo.DiscordBot/Properties/Resources.Designer.cs index 259d7bb..e7eaa95 100644 --- a/PoGo.DiscordBot/Properties/Resources.Designer.cs +++ b/PoGo.DiscordBot/Properties/Resources.Designer.cs @@ -177,6 +177,15 @@ public static string CommandNotFound { } } + /// + /// Looks up a localized string similar to Server does not support this command. + /// + public static string CommandNotSupported { + get { + return ResourceManager.GetString("CommandNotSupported", resourceCulture); + } + } + /// /// Looks up a localized string similar to Controlled user. /// @@ -303,6 +312,15 @@ public static string ListCommandsSummary { } } + /// + /// Looks up a localized string similar to Mark people who are enrolled on raid. + /// + public static string MentionRaidPlayersSummary { + get { + return ResourceManager.GetString("MentionRaidPlayersSummary", resourceCulture); + } + } + /// /// Looks up a localized string similar to Number Of Messages. /// @@ -312,6 +330,15 @@ public static string MessageNumber { } } + /// + /// Looks up a localized string similar to No raids active. + /// + public static string NoActiveRaids { + get { + return ResourceManager.GetString("NoActiveRaids", resourceCulture); + } + } + /// /// Looks up a localized string similar to none here. /// @@ -411,6 +438,24 @@ public static string RaidBossInfoSummary { } } + /// + /// Looks up a localized string similar to Returns a list of active raids, including indexes. + /// + public static string RaidListSummary { + get { + return ResourceManager.GetString("RaidListSummary", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Returns the location of the gym. + /// + public static string RaidLocationSummary { + get { + return ResourceManager.GetString("RaidLocationSummary", resourceCulture); + } + } + /// /// Looks up a localized string similar to Raid not found.. /// @@ -429,6 +474,15 @@ public static string RaidNotPossible { } } + /// + /// Looks up a localized string similar to Delete a role for the user. + /// + public static string RemoveRollSummary { + get { + return ResourceManager.GetString("RemoveRollSummary", resourceCulture); + } + } + /// /// Looks up a localized string similar to Selected team (role). /// @@ -519,6 +573,15 @@ public static string TooManyArgs { } } + /// + /// Looks up a localized string similar to Unknown Role. + /// + public static string UnknownRole { + get { + return ResourceManager.GetString("UnknownRole", resourceCulture); + } + } + /// /// Looks up a localized string similar to User. /// @@ -528,6 +591,15 @@ public static string User { } } + /// + /// Looks up a localized string similar to Very Short Name. + /// + public static string VeryShortName { + get { + return ResourceManager.GetString("VeryShortName", resourceCulture); + } + } + /// /// Looks up a localized string similar to Where. /// diff --git a/PoGo.DiscordBot/Properties/Resources.cs.resx b/PoGo.DiscordBot/Properties/Resources.cs.resx index cd42ba1..dccf27c 100644 --- a/PoGo.DiscordBot/Properties/Resources.cs.resx +++ b/PoGo.DiscordBot/Properties/Resources.cs.resx @@ -156,6 +156,9 @@ Žádný příkaz **{0}** jsem nemohl najít + + Server nepodporuje tenhle příkaz + Kontrolovaný uživatel @@ -198,9 +201,15 @@ Vypíše seznam příkazů. + + Označí lidi, kteří jsou zapsáni na raid + Počet zpráv + + Nejsou aktivní žádné raidy + žádný tu nemám @@ -234,12 +243,21 @@ Vypíše základní info o bossovi + + Vrátí seznam aktivních raidů včetně indexů + + + Vrátí lokaci gymu + Raid nenalezen. Z tohoto kanálu není možné vytvořit naplánovanou raid anketu + + Smaže uživateli roli. + Zvolený team (roli) @@ -270,9 +288,15 @@ Hodně parametrů - nechybí ti tam uvozovky? + + Neznámá role + Uživatel + + Moc krátký název + Kde diff --git a/PoGo.DiscordBot/Properties/Resources.en.resx b/PoGo.DiscordBot/Properties/Resources.en.resx index 4b60c79..03a5394 100644 --- a/PoGo.DiscordBot/Properties/Resources.en.resx +++ b/PoGo.DiscordBot/Properties/Resources.en.resx @@ -156,6 +156,9 @@ No command found {0}, I couldn't find it + + Server does not support this command + Controlled user @@ -198,9 +201,15 @@ Lists Commands + + Mark people who are enrolled on raid + Number Of Messages + + No Active Raids + None here @@ -234,12 +243,21 @@ Lists basic boss info + + Returns a list of active raids, including indexes + + + Returns the location of the gym + Raid not found. It is not possible to create a scheduled raid poll from this channel + + Delete a role for the user + Selected team (role) @@ -270,9 +288,15 @@ The input text has too many parameters + + Unknown Role + User + + Very Short Name + Where diff --git a/PoGo.DiscordBot/Properties/Resources.resx b/PoGo.DiscordBot/Properties/Resources.resx index c030c42..ba25b39 100644 --- a/PoGo.DiscordBot/Properties/Resources.resx +++ b/PoGo.DiscordBot/Properties/Resources.resx @@ -156,6 +156,9 @@ No command found {0}, I couldn't find it + + Server does not support this command + Controlled user @@ -198,9 +201,15 @@ Lists Commands. + + Mark people who are enrolled on raid + Number Of Messages + + No raids active + none here @@ -234,12 +243,21 @@ Lists basic boss info + + Returns a list of active raids, including indexes + + + Returns the location of the gym + Raid not found. It is not possible to create a scheduled raid poll from this channel + + Delete a role for the user + Selected team (role) @@ -270,9 +288,15 @@ The input text has too many parameters + + Unknown Role + User + + Very Short Name + Where From b7f84c219c4ddb53568c0f718febbdd1710dce70 Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 8 Apr 2019 14:14:33 -0400 Subject: [PATCH 04/10] Revert a major chunk of the cosmetic style changes I made earlier. --- PoGo.DiscordBot/Common/StringUtils.cs | 4 +- PoGo.DiscordBot/Dto/PlayerDto.cs | 5 +- PoGo.DiscordBot/Dto/RaidInfoDto.cs | 33 +++---- PoGo.DiscordBot/Emojis.cs | 2 +- PoGo.DiscordBot/Modules/BlameModule.cs | 8 +- PoGo.DiscordBot/Modules/CleanModule.cs | 6 +- PoGo.DiscordBot/Modules/DiagnosticModule.cs | 8 +- PoGo.DiscordBot/Modules/HelpModule.cs | 30 +++---- PoGo.DiscordBot/Modules/InfoModule.cs | 4 +- PoGo.DiscordBot/Modules/InviteModule.cs | 8 +- PoGo.DiscordBot/Modules/LanguageModule.cs | 4 +- PoGo.DiscordBot/Modules/LogsModule.cs | 10 +-- PoGo.DiscordBot/Modules/PlayerModule.cs | 10 +-- .../RaidChannelPreconditionAttribute.cs | 2 +- .../TeamPreconditionAttribute.cs | 4 +- PoGo.DiscordBot/Modules/RoleModule.cs | 12 +-- PoGo.DiscordBot/Modules/StatisticsModule.cs | 14 +-- PoGo.DiscordBot/Modules/TestModule.cs | 2 +- PoGo.DiscordBot/PoGoBot.cs | 66 +++++++------- PoGo.DiscordBot/Program.cs | 3 +- .../Services/ConfigurationService.cs | 7 +- .../Services/GymLocationService.cs | 11 +-- .../Services/RaidBossInfoService.cs | 19 ++--- .../Services/RaidChannelService.cs | 38 ++++----- PoGo.DiscordBot/Services/RaidService.cs | 85 +++++++++---------- .../Services/RaidStorageService.cs | 36 ++++---- PoGo.DiscordBot/Services/RoleService.cs | 6 +- PoGo.DiscordBot/Services/TeamService.cs | 14 +-- PoGo.DiscordBot/Services/UserService.cs | 34 ++++---- .../configuration.Development.json | 2 +- 30 files changed, 224 insertions(+), 263 deletions(-) diff --git a/PoGo.DiscordBot/Common/StringUtils.cs b/PoGo.DiscordBot/Common/StringUtils.cs index eb56d48..67fec11 100644 --- a/PoGo.DiscordBot/Common/StringUtils.cs +++ b/PoGo.DiscordBot/Common/StringUtils.cs @@ -10,9 +10,9 @@ public static string ToLowerWithoutDiacritics(string text) string normalizedString = text.Normalize(NormalizationForm.FormD); StringBuilder stringBuilder = new StringBuilder(text.Length); - foreach (char c in normalizedString) + foreach (var c in normalizedString) { - UnicodeCategory unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); + var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); if (unicodeCategory != UnicodeCategory.NonSpacingMark) { stringBuilder.Append(char.ToLower(c)); diff --git a/PoGo.DiscordBot/Dto/PlayerDto.cs b/PoGo.DiscordBot/Dto/PlayerDto.cs index 9a377df..ddc59b8 100644 --- a/PoGo.DiscordBot/Dto/PlayerDto.cs +++ b/PoGo.DiscordBot/Dto/PlayerDto.cs @@ -9,9 +9,6 @@ public class PlayerDto public PokemonTeam? Team { get; set; } public int? Level { get; set; } - public override string ToString() - { - return User.Nickname ?? User.Username; - } + public override string ToString() => User.Nickname ?? User.Username; } } \ No newline at end of file diff --git a/PoGo.DiscordBot/Dto/RaidInfoDto.cs b/PoGo.DiscordBot/Dto/RaidInfoDto.cs index 19c4434..e13cd4b 100644 --- a/PoGo.DiscordBot/Dto/RaidInfoDto.cs +++ b/PoGo.DiscordBot/Dto/RaidInfoDto.cs @@ -28,7 +28,7 @@ public class RaidInfoDto public bool IsExpired => DateTime < DateTime.Now; public RaidType RaidType { get; set; } - private string DateTimeAsString => DateTime.ToString(RaidType == RaidType.Normal ? TimeFormat : DateTimeFormat); + string DateTimeAsString => DateTime.ToString(RaidType == RaidType.Normal ? TimeFormat : DateTimeFormat); public RaidInfoDto(RaidType raidType) { @@ -47,7 +47,7 @@ Color GetColor() return !IsExpired ? new Color(191, 155, 48) : Color.Red; } - TimeSpan remainingTime = DateTime - DateTime.Now; + var remainingTime = DateTime - DateTime.Now; if (remainingTime.TotalMinutes <= 0) return Color.Red; @@ -82,26 +82,20 @@ Color GetColor() return embedBuilder.Build(); } - public string ToSimpleString() - { - return $"{BossName} {Location} {DateTimeAsString}"; - } + public string ToSimpleString() => $"{BossName} {Location} {DateTimeAsString}"; - private string PlayersToString(IEnumerable players) - { - return string.Join(", ", players); - } + string PlayersToString(IEnumerable players) => string.Join(", ", players); - private string PlayersToGroupString(IEnumerable allPlayers) + string PlayersToGroupString(IEnumerable allPlayers) { string TeamToString(PokemonTeam? team) => team != null ? team.ToString() : Resources.WithoutTeam; List formatterGroupedPlayers = new List(); - PokemonTeam?[] teams = new PokemonTeam?[] { PokemonTeam.Mystic, PokemonTeam.Instinct, PokemonTeam.Valor, null }; + var teams = new PokemonTeam?[] { PokemonTeam.Mystic, PokemonTeam.Instinct, PokemonTeam.Valor, null }; foreach (PokemonTeam? team in teams) { - List players = allPlayers.Where(t => t.Team == team).ToList(); + var players = allPlayers.Where(t => t.Team == team).ToList(); if (players.Count > 0) formatterGroupedPlayers.Add($"{TeamToString(team)} ({players.Count}) - {PlayersToString(players)}"); } @@ -109,14 +103,11 @@ private string PlayersToGroupString(IEnumerable allPlayers) return string.Join(Environment.NewLine, formatterGroupedPlayers); } - public static DateTime? ParseTime(string time) - { - return ParseTime(time, DateTime.Now.Date); - } + public static DateTime? ParseTime(string time) => ParseTime(time, DateTime.Now.Date); public static DateTime? ParseTime(string time, DateTime date) { - string[] pieces = time.Split(' ', '.', ',', ':', ';', '\''); + var pieces = time.Split(' ', '.', ',', ':', ';', '\''); if (pieces.Length != 2 || !int.TryParse(pieces[0], out int hours) || !int.TryParse(pieces[1], out int minutes)) return null; @@ -129,10 +120,10 @@ private string PlayersToGroupString(IEnumerable allPlayers) DateTime? result = null; try { - string[] tokens = dateTime.Split(new[] { ' ', '.', ',', ':', ';', '\'', '/' }, StringSplitOptions.RemoveEmptyEntries); + var tokens = dateTime.Split(new[] { ' ', '.', ',', ':', ';', '\'', '/' }, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 5) throw new Exception($"Invalid date '{dateTime}'"); - int[] intTokens = tokens.Select(int.Parse).ToArray(); + var intTokens = tokens.Select(int.Parse).ToArray(); result = new DateTime(intTokens[2], intTokens[1], intTokens[0], intTokens[3], intTokens[4], 0); } @@ -144,7 +135,7 @@ private string PlayersToGroupString(IEnumerable allPlayers) public static RaidInfoDto Parse(IUserMessage message) { - IEmbed embed = message.Embeds.FirstOrDefault(); + var embed = message.Embeds.FirstOrDefault(); if (embed == null || embed.Fields.Length < 3) return null; diff --git a/PoGo.DiscordBot/Emojis.cs b/PoGo.DiscordBot/Emojis.cs index 57ff99b..570c5af 100644 --- a/PoGo.DiscordBot/Emojis.cs +++ b/PoGo.DiscordBot/Emojis.cs @@ -9,7 +9,7 @@ internal class UnicodeEmojis public const string ThumbsDown = "👎"; public const string Check = "✅"; public const string Cross = "❌"; - private const char Border = '⃣'; + const char Border = '⃣'; public static readonly string[] KeycapDigits; static UnicodeEmojis() diff --git a/PoGo.DiscordBot/Modules/BlameModule.cs b/PoGo.DiscordBot/Modules/BlameModule.cs index 0c9e90a..5f44692 100644 --- a/PoGo.DiscordBot/Modules/BlameModule.cs +++ b/PoGo.DiscordBot/Modules/BlameModule.cs @@ -12,8 +12,8 @@ namespace PoGo.DiscordBot.Modules [Group("blame")] public class BlameModule : ModuleBase { - private readonly UserService userService; - private readonly ILogger logger; + readonly UserService userService; + readonly ILogger logger; public BlameModule(UserService userService, ILogger logger) { @@ -24,7 +24,7 @@ public BlameModule(UserService userService, ILogger logger) [Command("level")] public async Task ListPlayersWithoutLevel() { - System.Collections.Generic.IEnumerable players = userService.GetPlayers(Context.Guild.Users) + var players = userService.GetPlayers(Context.Guild.Users) .Where(t => !t.Level.HasValue); string message = string.Join(", ", players); @@ -34,7 +34,7 @@ public async Task ListPlayersWithoutLevel() [Command("team")] public async Task ListPlayersWithoutTeam() { - System.Collections.Generic.IEnumerable players = userService.GetPlayers(Context.Guild.Users) + var players = userService.GetPlayers(Context.Guild.Users) .Where(t => !t.Team.HasValue); string message = string.Join(", ", players); diff --git a/PoGo.DiscordBot/Modules/CleanModule.cs b/PoGo.DiscordBot/Modules/CleanModule.cs index 55d52c3..baf70d8 100644 --- a/PoGo.DiscordBot/Modules/CleanModule.cs +++ b/PoGo.DiscordBot/Modules/CleanModule.cs @@ -13,8 +13,8 @@ public class CleanModule : ModuleBase [Summary("DeleteAllMessagesSummary")] public async Task FullClean([Summary("MessageNumber")]int count = 10) { - IEnumerable> batchMessages = AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync(count)); - foreach (IReadOnlyCollection messages in batchMessages) + var batchMessages = AsyncEnumerable.ToEnumerable(Context.Channel.GetMessagesAsync(count)); + foreach (var messages in batchMessages) await Context.Channel.DeleteMessagesAsync(messages); } @@ -39,7 +39,7 @@ private async Task DeleteMessagesAsync(ulong userId, int count) { foreach (IReadOnlyCollection messages in Context.Channel.GetMessagesAsync().ToEnumerable()) { - IEnumerable messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); + var messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); if (messagesToDelete != null) await Context.Channel.DeleteMessagesAsync(messagesToDelete.Take(count)); } diff --git a/PoGo.DiscordBot/Modules/DiagnosticModule.cs b/PoGo.DiscordBot/Modules/DiagnosticModule.cs index 55a8fcd..fe71b45 100644 --- a/PoGo.DiscordBot/Modules/DiagnosticModule.cs +++ b/PoGo.DiscordBot/Modules/DiagnosticModule.cs @@ -12,11 +12,11 @@ public class DiagnosticModule : ModuleBase [Command("ps")] public async Task ProcessInfo() { - Process proc = Process.GetCurrentProcess(); + var proc = Process.GetCurrentProcess(); double mem = proc.WorkingSet64; - TimeSpan cpu = proc.TotalProcessorTime; + var cpu = proc.TotalProcessorTime; - string[] suffixes = new[] { "", "K", "M", "G", "T" }; + var suffixes = new[] { "", "K", "M", "G", "T" }; int memoryIndex = 0; while (mem >= 1024) { @@ -24,7 +24,7 @@ public async Task ProcessInfo() memoryIndex++; } - TimeSpan totalTime = DateTime.Now - proc.StartTime; + var totalTime = DateTime.Now - proc.StartTime; EmbedBuilder embedBuilder = new EmbedBuilder() .AddField("Time running", $"{totalTime}") diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index d2f658d..0607529 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -15,11 +15,11 @@ namespace PoGo.DiscordBot.Modules { public class HelpModule : InteractiveBase { - private readonly CommandService commandService; - private readonly IServiceProvider serviceProvider; - private readonly char prefix; + readonly CommandService commandService; + readonly IServiceProvider serviceProvider; + readonly char prefix; //TODO Load the current culture info from guild - private readonly CultureInfo cultureInfo = CultureInfo.GetCultureInfo("cs-CS"); + readonly CultureInfo cultureInfo = CultureInfo.GetCultureInfo("cs-CS"); public HelpModule(CommandService commandService, IServiceProvider serviceProvider, IOptions config) { @@ -34,15 +34,15 @@ public async Task Help() { Dictionary> groupCommands = new Dictionary>(); - foreach (ModuleInfo module in commandService.Modules) + foreach (var module in commandService.Modules) { string key = module.Aliases.FirstOrDefault() ?? string.Empty; - if (!groupCommands.TryGetValue(key, out List commands)) + if (!groupCommands.TryGetValue(key, out var commands)) groupCommands[key] = commands = new List(); - foreach (CommandInfo cmd in module.Commands) + foreach (var cmd in module.Commands) { - PreconditionResult result = await cmd.CheckPreconditionsAsync(Context, serviceProvider); + var result = await cmd.CheckPreconditionsAsync(Context, serviceProvider); if (result.IsSuccess) { string s = $"{prefix}{cmd.Aliases[0]}"; @@ -57,16 +57,16 @@ public async Task Help() string CommandsToString(IEnumerable commands) => string.Join(Environment.NewLine, commands.OrderBy(t => t)); - List> commandPages = new List>(); + var commandPages = new List>(); // Commands with module that has alias equal to "" are without any group // and they are on first page without any other group commands - if (groupCommands.TryGetValue(string.Empty, out List globalCommands)) + if (groupCommands.TryGetValue(string.Empty, out var globalCommands)) commandPages.Add(globalCommands); const int MaxCommandsPerPage = 15; List currentPageCommands = new List(); - foreach (KeyValuePair> c in groupCommands.OrderBy(t => t.Key)) + foreach (var c in groupCommands.OrderBy(t => t.Key)) { if (c.Key?.Length == 0) continue; @@ -116,7 +116,7 @@ private enum CommandInfoSignature [Summary("HelpSummary")] public async Task Help([Remainder] string command) { - SearchResult result = commandService.Search(Context, command); + var result = commandService.Search(Context, command); if (!result.IsSuccess) { @@ -126,7 +126,7 @@ public async Task Help([Remainder] string command) return; } - EmbedBuilder builder = new EmbedBuilder() + var builder = new EmbedBuilder() .WithColor(Color.Blue); string ParameterInfoToString(ParameterInfo info) => !info.IsOptional ? info.Name : $"[{info.Name}]"; @@ -159,7 +159,7 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) if (ci.Parameters.Count > 0) { - IEnumerable parameters = ci.Parameters.AsEnumerable(); + var parameters = ci.Parameters.AsEnumerable(); if (signature == HelpModule.CommandInfoSignature.Basic) parameters = parameters.Where(pi => !pi.IsOptional); @@ -172,7 +172,7 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) foreach (CommandMatch match in result.Commands) { - CommandInfo cmd = match.Command; + var cmd = match.Command; StringBuilder sb = new StringBuilder() .Append(Resources.Description).Append(':').AppendLine(cmd.Summary) .AppendLine() diff --git a/PoGo.DiscordBot/Modules/InfoModule.cs b/PoGo.DiscordBot/Modules/InfoModule.cs index 286edaa..07c9b35 100644 --- a/PoGo.DiscordBot/Modules/InfoModule.cs +++ b/PoGo.DiscordBot/Modules/InfoModule.cs @@ -10,7 +10,7 @@ namespace PoGo.DiscordBot.Modules { public class InfoModule : ModuleBase { - private readonly ConfigurationOptions configuration; + readonly ConfigurationOptions configuration; public InfoModule(IOptions configurationOptionsAccessor) { @@ -37,7 +37,7 @@ public async Task WriteInfo() {configuration.Prefix}raid Machamp Žirafa 12:00 2 Pozn. Jestliže má jakýkoliv parametr mezery, je nutné ho obalit uvozovkami (""parametr s mezerou"")"); - Embed embed = embedBuilder.Build(); + var embed = embedBuilder.Build(); await ReplyAsync(string.Empty, embed: embed); } diff --git a/PoGo.DiscordBot/Modules/InviteModule.cs b/PoGo.DiscordBot/Modules/InviteModule.cs index dd81ccf..78d5a46 100644 --- a/PoGo.DiscordBot/Modules/InviteModule.cs +++ b/PoGo.DiscordBot/Modules/InviteModule.cs @@ -12,7 +12,7 @@ namespace PoGo.DiscordBot.Modules [RequireContext(ContextType.Guild)] public class InviteModule : ModuleBase { - private readonly ILogger logger; + readonly ILogger logger; public InviteModule(ILogger logger) { @@ -24,13 +24,13 @@ public InviteModule(ILogger logger) [Summary("InviteSummary")] public async Task Invite() { - IReadOnlyCollection invites = await Context.Guild.GetInvitesAsync(); - RestInviteMetadata invite = invites.FirstOrDefault(t => !t.IsTemporary); + var invites = await Context.Guild.GetInvitesAsync(); + var invite = invites.FirstOrDefault(t => !t.IsTemporary); if (invite == null) { // TODO: call Context.Guild.DefaultChannel instead later on - SocketTextChannel defaultChannel = Context.Guild.TextChannels + var defaultChannel = Context.Guild.TextChannels .OrderBy(c => c.Position) .FirstOrDefault(); diff --git a/PoGo.DiscordBot/Modules/LanguageModule.cs b/PoGo.DiscordBot/Modules/LanguageModule.cs index 5f50a0f..6971f7e 100644 --- a/PoGo.DiscordBot/Modules/LanguageModule.cs +++ b/PoGo.DiscordBot/Modules/LanguageModule.cs @@ -7,8 +7,8 @@ namespace PoGo.DiscordBot.Modules //TODO Add a command to support changing the language in the config public class LanguageModule : ModuleBase { - private readonly ILogger logger; - private readonly ConfigurationService configService; + readonly ILogger logger; + readonly ConfigurationService configService; public LanguageModule(ILogger logger , ConfigurationService configService) diff --git a/PoGo.DiscordBot/Modules/LogsModule.cs b/PoGo.DiscordBot/Modules/LogsModule.cs index dae5b4e..a4f7aaa 100644 --- a/PoGo.DiscordBot/Modules/LogsModule.cs +++ b/PoGo.DiscordBot/Modules/LogsModule.cs @@ -11,17 +11,17 @@ namespace PoGo.DiscordBot.Modules [RequireOwner] public class LogsModule : ModuleBase { - private const string LogDirectory = "Logs"; + const string LogDirectory = "Logs"; [Command("logs", RunMode = RunMode.Async)] public async Task GetLogsFiles() { - DirectoryInfo di = new DirectoryInfo(LogDirectory); + var di = new DirectoryInfo(LogDirectory); - IEnumerable filenames = di.EnumerateFiles().Select(t => t.Name); + var filenames = di.EnumerateFiles().Select(t => t.Name); string content = string.Join(Environment.NewLine, filenames); - EmbedBuilder embedBuilder = new EmbedBuilder() + var embedBuilder = new EmbedBuilder() .WithDescription(content); await ReplyAsync(string.Empty, embed: embedBuilder.Build()); } @@ -29,7 +29,7 @@ public async Task GetLogsFiles() [Command("log", RunMode = RunMode.Async)] public async Task GetLog() { - FileInfo fileInfo = new DirectoryInfo(LogDirectory) + var fileInfo = new DirectoryInfo(LogDirectory) .EnumerateFiles() .OrderByDescending(t => t.LastWriteTimeUtc) .FirstOrDefault(); diff --git a/PoGo.DiscordBot/Modules/PlayerModule.cs b/PoGo.DiscordBot/Modules/PlayerModule.cs index 2283c4d..e09de57 100644 --- a/PoGo.DiscordBot/Modules/PlayerModule.cs +++ b/PoGo.DiscordBot/Modules/PlayerModule.cs @@ -11,8 +11,8 @@ namespace PoGo.DiscordBot.Modules [RequireContext(ContextType.Guild)] public class PlayerModule : ModuleBase { - private readonly UserService userService; - private readonly TeamService teamService; + readonly UserService userService; + readonly TeamService teamService; public PlayerModule(UserService userService, TeamService teamService) { @@ -33,18 +33,18 @@ public async Task CheckTeam( public async Task SetTeam( [Summary("SelectedTeam")]PokemonTeam team) { - SocketUser contextUser = Context.User; + var contextUser = Context.User; if (!(contextUser is SocketGuildUser user)) return; - PokemonTeam? userTeam = userService.GetTeam(user); + var userTeam = userService.GetTeam(user); if (userTeam != null) { await ReplyAsync(Resources.InTeam); return; } - Discord.IRole role = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles[team]; + var role = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles[team]; await user.AddRoleAsync(role); } diff --git a/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs b/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs index 11e0e25..3f5d18d 100644 --- a/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs +++ b/PoGo.DiscordBot/Modules/Preconditions/RaidChannelPreconditionAttribute.cs @@ -10,7 +10,7 @@ public class RaidChannelPreconditionAttribute : PreconditionAttribute { public override Task CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services) { - RaidChannelService raidChannelService = services.GetService(); + var raidChannelService = services.GetService(); if (raidChannelService.IsKnown(context.Guild.Id, context.Channel.Id)) return Task.FromResult(PreconditionResult.FromSuccess()); diff --git a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs index 53039af..68a04e2 100644 --- a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs +++ b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs @@ -14,8 +14,8 @@ public override Task CheckPermissions(ICommandContext contex if (!(context.User is SocketGuildUser guildUser)) return Task.FromResult(TeamPreconditionResult.Fail); - UserService userService = services.GetService(); - Configuration.PokemonTeam? team = userService.GetTeam(guildUser); + var userService = services.GetService(); + var team = userService.GetTeam(guildUser); if (team == null) return Task.FromResult(TeamPreconditionResult.Fail); diff --git a/PoGo.DiscordBot/Modules/RoleModule.cs b/PoGo.DiscordBot/Modules/RoleModule.cs index b7b6891..c645337 100644 --- a/PoGo.DiscordBot/Modules/RoleModule.cs +++ b/PoGo.DiscordBot/Modules/RoleModule.cs @@ -15,9 +15,9 @@ namespace PoGo.DiscordBot.Modules [Group("role")] public class RoleModule : ModuleBase { - private readonly ILogger logger; - private readonly RoleService roleService; - private readonly Dictionary availableRoles; // + readonly ILogger logger; + readonly RoleService roleService; + readonly Dictionary availableRoles; // public RoleModule(ILogger logger, IOptions options, RoleService roleService) { @@ -36,10 +36,10 @@ public async Task AddRole([Summary("Název role")]string roleName) if (!(Context.User is SocketGuildUser user)) return; - if (!availableRoles.TryGetValue(Context.Guild.Id, out string[] roles) || !roles.Contains(roleName)) + if (!availableRoles.TryGetValue(Context.Guild.Id, out var roles) || !roles.Contains(roleName)) return; - SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); + var role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { await ReplyAsync(Resources.UnknownRole); @@ -61,7 +61,7 @@ public async Task RemoveRole([Summary("Název role")]string roleName) if (!availableRoles.TryGetValue(Context.Guild.Id, out string[] roles) || !roles.Contains(roleName)) return; - SocketRole role = roleService.GetRoleByName(Context.Guild, roleName); + var role = roleService.GetRoleByName(Context.Guild, roleName); if (role == null) { await ReplyAsync(Resources.UnknownRole); diff --git a/PoGo.DiscordBot/Modules/StatisticsModule.cs b/PoGo.DiscordBot/Modules/StatisticsModule.cs index 812ac29..46fa7cb 100644 --- a/PoGo.DiscordBot/Modules/StatisticsModule.cs +++ b/PoGo.DiscordBot/Modules/StatisticsModule.cs @@ -13,7 +13,7 @@ namespace PoGo.DiscordBot.Modules [Group("stats")] public class StatisticsModule : ModuleBase { - private readonly UserService userService; + readonly UserService userService; public StatisticsModule(UserService userService) { @@ -32,10 +32,10 @@ public async Task TeamsStatistics() }; int withoutTeam = 0; - IEnumerable users = Context.Guild.Users.Where(t => !t.IsBot); - foreach (Discord.WebSocket.SocketGuildUser user in users) + var users = Context.Guild.Users.Where(t => !t.IsBot); + foreach (var user in users) { - PokemonTeam? team = userService.GetTeam(user); + var team = userService.GetTeam(user); if (team != null) groups[team.Value]++; else @@ -43,7 +43,7 @@ public async Task TeamsStatistics() } EmbedBuilder embedBuilder = new EmbedBuilder(); - foreach (KeyValuePair item in groups) + foreach (var item in groups) embedBuilder.AddInlineField(item.Key.ToString(), item.Value); if (withoutTeam != 0) embedBuilder.AddInlineField("Bez teamu", withoutTeam); @@ -56,7 +56,7 @@ public async Task TeamsStatistics() [Summary("Vypíše informace o levelech hráčů.")] public async Task LevelStatistics() { - List players = userService.GetPlayers(Context.Guild.Users) + var players = userService.GetPlayers(Context.Guild.Users) .Where(t => t?.Team != null && t?.Level != null) .ToList(); @@ -70,7 +70,7 @@ public async Task LevelStatistics() double averageLevel = groupedPlayersPerTeam.Values.Average(t => t.AverageLevel); - EmbedBuilder embedBuilder = new EmbedBuilder() + var embedBuilder = new EmbedBuilder() .WithTitle("Průmerné levely"); foreach (var team in groupedPlayersPerTeam) embedBuilder.AddInlineField($"{team.Key} ({team.Value.Players.Count})", $"{team.Value.AverageLevel:f2}"); diff --git a/PoGo.DiscordBot/Modules/TestModule.cs b/PoGo.DiscordBot/Modules/TestModule.cs index 3451851..26777f8 100644 --- a/PoGo.DiscordBot/Modules/TestModule.cs +++ b/PoGo.DiscordBot/Modules/TestModule.cs @@ -7,7 +7,7 @@ namespace PoGo.DiscordBot.Modules [RequireOwner] public class TestModule : ModuleBase { - private readonly ILogger logger; + readonly ILogger logger; public TestModule(ILogger logger) { diff --git a/PoGo.DiscordBot/PoGoBot.cs b/PoGo.DiscordBot/PoGoBot.cs index ce4abc4..1f695a0 100644 --- a/PoGo.DiscordBot/PoGoBot.cs +++ b/PoGo.DiscordBot/PoGoBot.cs @@ -25,11 +25,11 @@ public class PoGoBot : IDisposable public IServiceProvider ServiceProvider { get; } public IConfiguration Configuration { get; } - private readonly DiscordSocketClient client; - private readonly CommandService commands; - private readonly ILogger logger; - private readonly ConfigurationOptions configuration; - private readonly Timer updateRaidsTimer; + readonly DiscordSocketClient client; + readonly CommandService commands; + readonly ILogger logger; + readonly ConfigurationOptions configuration; + readonly Timer updateRaidsTimer; public PoGoBot() { @@ -46,7 +46,7 @@ public PoGoBot() .AddJsonFile($"appsettings.{environment}.json", false) .Build(); - LogSeverity logSeverity = Enum.Parse(Configuration["Logging:LogLevel:Discord"]); + var logSeverity = Enum.Parse(Configuration["Logging:LogLevel:Discord"]); client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = logSeverity, @@ -70,14 +70,14 @@ public PoGoBot() updateRaidsTimer = new Timer(async state => { - RaidService raidService = (RaidService)state; + var raidService = (RaidService)state; await raidService.UpdateRaidMessages(); }, ServiceProvider.GetService(), Timeout.Infinite, Timeout.Infinite); Init(); } - private void Init() + void Init() { client.Log += Log; commands.Log += Log; @@ -95,71 +95,71 @@ private void Init() client.MessageDeleted += OnMessageDeleted; } - private async Task OnMessageDeleted(Cacheable message, ISocketMessageChannel channel) + async Task OnMessageDeleted(Cacheable message, ISocketMessageChannel channel) { - RaidService raidService = ServiceProvider.GetService(); + var raidService = ServiceProvider.GetService(); await raidService.OnMessageDeleted(message, channel); } - private async Task OnUserJoined(SocketGuildUser user) + async Task OnUserJoined(SocketGuildUser user) { - UserService userService = ServiceProvider.GetService(); + var userService = ServiceProvider.GetService(); await userService.OnUserJoined(user); } - private async Task GuildAvailable(SocketGuild guild) + async Task GuildAvailable(SocketGuild guild) { logger.LogInformation($"New guild: '{guild.Name}'"); - TeamService teamService = ServiceProvider.GetService(); + var teamService = ServiceProvider.GetService(); await teamService.OnNewGuild(guild); - RaidChannelService raidChannelService = ServiceProvider.GetService(); - GuildOptions[] guildOptions = ServiceProvider.GetService>().Value.Guilds; + var raidChannelService = ServiceProvider.GetService(); + var guildOptions = ServiceProvider.GetService>().Value.Guilds; raidChannelService.OnNewGuild(guild, guildOptions); RaidService raidService = ServiceProvider.GetService(); await raidService.OnNewGuild(guild); } - private async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) + async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { - RaidService raidService = ServiceProvider.GetService(); + var raidService = ServiceProvider.GetService(); await raidService.OnReactionRemoved(message, channel, reaction); } private async Task ReactionAdded(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { - RaidService raidService = ServiceProvider.GetService(); + var raidService = ServiceProvider.GetService(); await raidService.OnReactionAdded(message, channel, reaction); } - private async Task JoinedGuild(SocketGuild guild) + async Task JoinedGuild(SocketGuild guild) { - RaidService raidService = ServiceProvider.GetService(); + var raidService = ServiceProvider.GetService(); await raidService.OnNewGuild(guild); } - private Task LoggedIn() + Task LoggedIn() { logger.LogInformation("Logged in"); return Task.CompletedTask; } - private Task LoggedOut() + Task LoggedOut() { logger.LogInformation("Logged out"); return Task.CompletedTask; } - private async Task Connected() + async Task Connected() { logger.LogInformation("Connected"); await client.SetGameAsync(Debugger.IsAttached ? "Debugging" : "Pokémon GO"); updateRaidsTimer.Change(TimeSpan.FromSeconds(120 - DateTime.Now.Second), TimeSpan.FromMinutes(1)); } - private Task Disconnected(Exception exception) + Task Disconnected(Exception exception) { logger.LogInformation(exception, "Disconnected"); updateRaidsTimer.Change(Timeout.Infinite, Timeout.Infinite); @@ -205,16 +205,16 @@ public async Task RunAsync() await client.StartAsync(); } - private async Task InitCommands() + async Task InitCommands() { - System.Collections.Generic.IEnumerable modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); + var modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); logger.LogDebug("Loading modules"); - foreach (ModuleInfo module in modules) + foreach (var module in modules) logger.LogDebug($"{module.Name}: {string.Join(", ", module.Commands.Select(t => t.Name))}"); logger.LogDebug("Modules loaded"); } - private async Task HandleCommand(SocketMessage messageParam) + async Task HandleCommand(SocketMessage messageParam) { // Don't process the command if it was a System Message if (!(messageParam is SocketUserMessage message)) @@ -224,10 +224,10 @@ private async Task HandleCommand(SocketMessage messageParam) // Determine if the message is a command, based on if it starts with '!' or a mention prefix if (!(message.HasCharPrefix(configuration.Prefix, ref argPos) || message.HasMentionPrefix(client.CurrentUser, ref argPos))) return; // Create a Command Context - SocketCommandContext context = new SocketCommandContext(client, message); + var context = new SocketCommandContext(client, message); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed succesfully) - IResult result = await commands.ExecuteAsync(context, argPos, ServiceProvider); + var result = await commands.ExecuteAsync(context, argPos, ServiceProvider); if (!result.IsSuccess) { if (result.Error == CommandError.BadArgCount) @@ -249,7 +249,7 @@ private async Task HandleCommand(SocketMessage messageParam) // await context.Channel.SendMessageAsync(result.ErrorReason); } - private Task Log(LogMessage message) + Task Log(LogMessage message) { LogLevel logLevel = message.Severity.ToLogLevel(); logger.Log(logLevel, 0, message, null, LogMessageFormatter); @@ -260,7 +260,7 @@ private Task Log(LogMessage message) return Task.CompletedTask; } - private string LogMessageFormatter(LogMessage message, Exception exception) + string LogMessageFormatter(LogMessage message, Exception exception) { return $"{message.Source}: {message.Message}"; } diff --git a/PoGo.DiscordBot/Program.cs b/PoGo.DiscordBot/Program.cs index bf30fff..9321328 100644 --- a/PoGo.DiscordBot/Program.cs +++ b/PoGo.DiscordBot/Program.cs @@ -10,9 +10,8 @@ internal class Program { private static async Task Main(string[] args) { - using (PoGoBot bot = new PoGoBot()) + using (var bot = new PoGoBot()) { - Console.WriteLine(Resources.FullUse); await bot.RunAsync(); await Task.Delay(Timeout.Infinite); } diff --git a/PoGo.DiscordBot/Services/ConfigurationService.cs b/PoGo.DiscordBot/Services/ConfigurationService.cs index 67c288e..8565cf3 100644 --- a/PoGo.DiscordBot/Services/ConfigurationService.cs +++ b/PoGo.DiscordBot/Services/ConfigurationService.cs @@ -6,16 +6,13 @@ namespace PoGo.DiscordBot.Services { public class ConfigurationService { - private readonly ConfigurationOptions configurationOptions; + readonly ConfigurationOptions configurationOptions; public ConfigurationService(IOptions configurationOptions) { this.configurationOptions = configurationOptions.Value; } - public GuildOptions GetGuildOptions(ulong guildId) - { - return configurationOptions.Guilds.FirstOrDefault(t => t.Id == guildId); - } + public GuildOptions GetGuildOptions(ulong guildId) => configurationOptions.Guilds.FirstOrDefault(t => t.Id == guildId); } } \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/GymLocationService.cs b/PoGo.DiscordBot/Services/GymLocationService.cs index 2e3e2aa..ae3d916 100644 --- a/PoGo.DiscordBot/Services/GymLocationService.cs +++ b/PoGo.DiscordBot/Services/GymLocationService.cs @@ -9,7 +9,7 @@ namespace PoGo.DiscordBot.Services { public class GymLocationService { - private readonly Dictionary gymsInfos; // + readonly Dictionary gymsInfos; // public GymLocationService(IOptions options) { @@ -25,18 +25,15 @@ public GymLocationService(IOptions options) public IEnumerable Search(ulong guildId, string name) { - if (!gymsInfos.TryGetValue(guildId, out (string NormalizedName, GymInfoDto GymInfo)[] gyms)) + if (!gymsInfos.TryGetValue(guildId, out var gyms)) return default; - string normalizedName = StringUtils.ToLowerWithoutDiacritics(name); + var normalizedName = StringUtils.ToLowerWithoutDiacritics(name); return gyms .Where(t => t.NormalizedName.Contains(normalizedName)) .Select(t => t.GymInfo); } - public string GetMapUrl(GymInfoDto gymInfo) - { - return $"http://maps.google.com/maps?q={gymInfo.Latitude},{gymInfo.Longitude}"; - } + public string GetMapUrl(GymInfoDto gymInfo) => $"http://maps.google.com/maps?q={gymInfo.Latitude},{gymInfo.Longitude}"; } } \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index 660893c..2796ece 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -9,7 +9,7 @@ namespace PoGo.DiscordBot.Services { public class RaidBossInfoService { - private readonly Dictionary raidBosses; // + readonly Dictionary raidBosses; // public RaidBossInfoService(IOptions options) { @@ -24,21 +24,16 @@ public RaidBossInfoService(IOptions options) }); } - public IEnumerable GetAllKnownBossNames() - { - return raidBosses.Values -.Select(t => t.BossName) -.OrderBy(t => t); - } + public IEnumerable GetAllKnownBossNames() =>raidBosses.Values + .Select(t => t.BossName) + .OrderBy(t => t); - public RaidBossDto GetBoss(string bossName) - { - return raidBosses.TryGetValue(bossName.ToLower(), out RaidBossDto dto) ? dto : null; - } + public RaidBossDto GetBoss(string bossName) => + raidBosses.TryGetValue(bossName.ToLower(), out RaidBossDto dto) ? dto : null; public string GetBossNameWithEmoji(string bossName, SocketGuild guild) { - Discord.GuildEmote emote = guild.Emotes.FirstOrDefault(t => string.Compare(t.Name, bossName, true) == 0); + var emote = guild.Emotes.FirstOrDefault(t => string.Compare(t.Name, bossName, true) == 0); if (emote != null) return $"{bossName} {emote}"; diff --git a/PoGo.DiscordBot/Services/RaidChannelService.cs b/PoGo.DiscordBot/Services/RaidChannelService.cs index 8de6579..d227eaf 100644 --- a/PoGo.DiscordBot/Services/RaidChannelService.cs +++ b/PoGo.DiscordBot/Services/RaidChannelService.cs @@ -26,8 +26,8 @@ public RaidChannelBinding(ITextChannel from, ITextChannel to, IMentionable menti } } - private readonly Dictionary> guilds; // - private readonly ILogger logger; + readonly Dictionary> guilds; // + readonly ILogger logger; public RaidChannelService(ILogger logger) { @@ -37,7 +37,7 @@ public RaidChannelService(ILogger logger) public void OnNewGuild(SocketGuild guild, GuildOptions[] guildOptions) { - GuildOptions guildConfig = guildOptions.FirstOrDefault(t => t.Id == guild.Id); + var guildConfig = guildOptions.FirstOrDefault(t => t.Id == guild.Id); if (guildConfig == null) { logger.LogWarning($"Unknown guild with id '{guild.Id}', name '{guild.Name}'"); @@ -50,27 +50,21 @@ public void OnNewGuild(SocketGuild guild, GuildOptions[] guildOptions) return; } - List channelBindings = guilds[guild.Id] = new List(); + var channelBindings = guilds[guild.Id] = new List(); // go through configured channels and register them - foreach (ChannelOptions channel in guildConfig.Channels) + foreach (var channel in guildConfig.Channels) AddBindingIfValid(channelBindings, guild, channel); } - public bool IsKnown(ulong guildId) - { - return guilds.ContainsKey(guildId); - } + public bool IsKnown(ulong guildId) => guilds.ContainsKey(guildId); - public bool IsKnown(ulong guildId, ulong textChannelId) - { - return TryGetRaidChannelBinding(guildId, textChannelId) != null; - } - public IEnumerable GetRaidChannels(ulong guildId) - { - return guilds[guildId].Select(t => t.To); - } + public bool IsKnown(ulong guildId, ulong textChannelId) => + TryGetRaidChannelBinding(guildId, textChannelId) != null; + + + public IEnumerable GetRaidChannels(ulong guildId) => guilds[guildId].Select(t => t.To); /// /// Returns raid channel for the raid poll based on the channel where the command came from. @@ -79,9 +73,9 @@ public IEnumerable GetRaidChannels(ulong guildId) /// todo: describe fromTextChannelId parameter on TryGetRaidChannelBinding public RaidChannelBindingDto TryGetRaidChannelBinding(ulong guildId, ulong fromTextChannelId) { - if (guilds.TryGetValue(guildId, out List raidChannelBindings)) + if (guilds.TryGetValue(guildId, out var raidChannelBindings)) { - foreach (RaidChannelBinding channel in raidChannelBindings) + foreach (var channel in raidChannelBindings) { if (channel.From == null || channel.From.Id == fromTextChannelId) { @@ -113,10 +107,10 @@ public RaidChannelBindingDto TryGetRaidChannelBindingTo(ulong guildId, ulong toT return null; } - private void AddBindingIfValid(List channelBindings, SocketGuild guild, ChannelOptions channelOptions) + void AddBindingIfValid(List channelBindings, SocketGuild guild, ChannelOptions channelOptions) { - SocketTextChannel channelFrom = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.From); - SocketTextChannel channelTo = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.To); + var channelFrom = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.From); + var channelTo = guild.TextChannels.FirstOrDefault(t => t.Name == channelOptions.To); bool channelFromBinding = channelFrom == null && channelOptions.From != "*"; bool channelToBinding = channelTo == null; diff --git a/PoGo.DiscordBot/Services/RaidService.cs b/PoGo.DiscordBot/Services/RaidService.cs index 5cacca1..515b66f 100644 --- a/PoGo.DiscordBot/Services/RaidService.cs +++ b/PoGo.DiscordBot/Services/RaidService.cs @@ -11,12 +11,12 @@ namespace PoGo.DiscordBot.Services { public class RaidService { - private const ulong DefaultRaidChannelId = 348844165741936641; - private static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; - private readonly ILogger logger; - private readonly UserService userService; - private readonly RaidChannelService raidChannelService; - private readonly RaidStorageService raidStorageService; + const ulong DefaultRaidChannelId = 348844165741936641; + static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; + readonly ILogger logger; + readonly UserService userService; + readonly RaidChannelService raidChannelService; + readonly RaidStorageService raidStorageService; public RaidService(ILogger logger, UserService userService, RaidChannelService raidChannelService, RaidStorageService raidStorageService) { @@ -32,7 +32,7 @@ public async Task OnNewGuild(SocketGuild guild) // ignore unknown guilds for now return; - foreach (ITextChannel channel in raidChannelService.GetRaidChannels(guild.Id)) + foreach (var channel in raidChannelService.GetRaidChannels(guild.Id)) await UpdateRaidMessages(guild, channel); } @@ -40,19 +40,19 @@ public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, { try { - RaidChannelBindingDto channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); + var channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); bool mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; DateTime dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.AddHours(-2) : DateTime.UtcNow.AddDays(-14); - List> batchMessages = await channel.GetMessagesAsync(count, options: retryOptions) + var batchMessages = await channel.GetMessagesAsync(count, options: retryOptions) .ToList(); - List latestMessages = batchMessages.SelectMany(t => t.Where(m => m.CreatedAt.UtcDateTime > dateTimeFrom)) + var latestMessages = batchMessages.SelectMany(t => t.Where(m => m.CreatedAt.UtcDateTime > dateTimeFrom)) .ToList(); - if (!latestMessages.Any()) + if (latestMessages.Count == 0) return; logger.LogInformation($"start updating raid messages for channel '{channel.Name}'"); - foreach (IMessage message in latestMessages) + foreach (var message in latestMessages) if (message is IUserMessage userMessage) await FixRaidMessageAfterLoad(guild, userMessage); logger.LogInformation($"end updating raid messages for channel '{channel.Name}'"); @@ -63,9 +63,9 @@ public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, } } - private async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message) + async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message) { - RaidInfoDto raidInfo = RaidInfoDto.Parse(message); + var raidInfo = RaidInfoDto.Parse(message); if (raidInfo == null) return false; @@ -73,33 +73,33 @@ private async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage raidStorageService.AddRaid(guild.Id, message.Channel.Id, message.Id, raidInfo); // Adjust user count - IReadOnlyCollection allUsersWithThumbsUp = await message.GetReactionUsersAsync(UnicodeEmojis.ThumbsUp); - IEnumerable usersWithThumbsUp = allUsersWithThumbsUp + var allUsersWithThumbsUp = await message.GetReactionUsersAsync(UnicodeEmojis.ThumbsUp); + var usersWithThumbsUp = allUsersWithThumbsUp .Where(t => !t.IsBot) .Select(t => guild.GetUser(t.Id)) .Where(t => t != null); - foreach (SocketGuildUser user in usersWithThumbsUp) + foreach (var user in usersWithThumbsUp) raidInfo.Players[user.Id] = userService.GetPlayer(guild.GetUser(user.Id)); // Extra players for (int i = 0; i < UnicodeEmojis.KeycapDigits.Length; i++) { - string emoji = UnicodeEmojis.KeycapDigits[i]; - IReadOnlyCollection usersWithKeycapReaction = await message.GetReactionUsersAsync(emoji); + var emoji = UnicodeEmojis.KeycapDigits[i]; + var usersWithKeycapReaction = await message.GetReactionUsersAsync(emoji); - foreach (IUser user in usersWithKeycapReaction.Where(t => !t.IsBot)) + foreach (var user in usersWithKeycapReaction.Where(t => !t.IsBot)) raidInfo.ExtraPlayers.Add((user.Id, ExtraPlayerKeycapDigitToCount(emoji))); } await message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); - IReadOnlyDictionary allReactions = message.Reactions; - List> invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); + var allReactions = message.Reactions; + var invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); // Remove invalid reactions - foreach (KeyValuePair react in invalidReactions) + foreach (var react in invalidReactions) { IReadOnlyCollection users = await message.GetReactionUsersAsync(react.Key.Name, options: retryOptions); - foreach (IUser user in users) + foreach (var user in users) await message.RemoveReactionAsync(react.Key, user, options: retryOptions); } @@ -111,7 +111,7 @@ public Task OnMessageDeleted(Cacheable cacheableMessage, ISocke if (!(channel is SocketTextChannel socketChannel)) return Task.CompletedTask; - ulong messageId = cacheableMessage.Id; + var messageId = cacheableMessage.Id; if (raidStorageService.TryRemove(socketChannel.Guild.Id, socketChannel.Id, messageId)) logger.LogInformation($"Raid message '{messageId}' was removed."); @@ -124,30 +124,27 @@ public async Task SetDefaultReactions(IUserMessage message) await message.AddReactionAsync(Emojis.ThumbsDown, retryOptions); } - private bool IsValidReactionEmote(string emote) - { - return emote == UnicodeEmojis.ThumbsUp || -emote == UnicodeEmojis.ThumbsDown || -UnicodeEmojis.KeycapDigits.Contains(emote); - } + bool IsValidReactionEmote(string emote) => + emote == UnicodeEmojis.ThumbsUp || + emote == UnicodeEmojis.ThumbsDown || + UnicodeEmojis.KeycapDigits.Contains(emote); + + + int ExtraPlayerKeycapDigitToCount(string name) => Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; - private int ExtraPlayerKeycapDigitToCount(string name) - { - return Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; - } public async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { if (!(channel is SocketGuildChannel socketGuildChannel)) return; - RaidInfoDto raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); + var raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); if (raidInfo == null || raidInfo.IsExpired) return; IUserMessage raidMessage = await message.GetOrDownloadAsync(); if (reaction.Emote.Name == UnicodeEmojis.ThumbsUp) { - if (raidInfo.Players.TryGetValue(reaction.UserId, out PlayerDto player)) + if (raidInfo.Players.TryGetValue(reaction.UserId, out var player)) { logger.LogInformation($"Player '{player}' removed {nameof(UnicodeEmojis.ThumbsUp)} on raid {raidInfo.Message.Id}"); raidInfo.Players.Remove(reaction.UserId); @@ -156,7 +153,7 @@ public async Task OnReactionRemoved(Cacheable message, ISoc } else if (Emojis.KeycapDigits.Contains(reaction.Emote)) { - int count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); + var count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); if (raidInfo.ExtraPlayers.Remove((reaction.UserId, count))) await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } @@ -166,7 +163,7 @@ public async Task OnReactionAdded(Cacheable message, ISocke { if (!(channel is SocketGuildChannel socketGuildChannel)) return; - RaidInfoDto raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); + var raidInfo = raidStorageService.GetRaid(socketGuildChannel.Guild.Id, channel.Id, message.Id); if (raidInfo == null || raidInfo.IsExpired) return; @@ -182,14 +179,14 @@ public async Task OnReactionAdded(Cacheable message, ISocke if (reaction.Emote.Name == UnicodeEmojis.ThumbsUp) { - PlayerDto player = userService.GetPlayer(user); + var player = userService.GetPlayer(user); raidInfo.Players[reaction.UserId] = player; logger.LogInformation($"Player '{player}' added {nameof(UnicodeEmojis.ThumbsUp)} on raid {raidInfo.Message.Id}"); await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } else if (Emojis.KeycapDigits.Contains(reaction.Emote)) { - int count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); + var count = ExtraPlayerKeycapDigitToCount(reaction.Emote.Name); raidInfo.ExtraPlayers.Add((reaction.UserId, count)); await raidMessage.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); } @@ -197,9 +194,9 @@ public async Task OnReactionAdded(Cacheable message, ISocke public async Task UpdateRaidMessages() { - List<(ulong guildId, ulong channelId, ulong messageId)> toRemove = new List<(ulong guildId, ulong channelId, ulong messageId)>(); + var toRemove = new List<(ulong guildId, ulong channelId, ulong messageId)>(); - foreach ((ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfo) in raidStorageService.GetAll()) + foreach (var(guildId,channelId, messageId,raidInfo) in raidStorageService.GetAll()) { await raidInfo.Message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); @@ -207,7 +204,7 @@ public async Task UpdateRaidMessages() toRemove.Add((guildId, channelId, messageId)); } - foreach ((ulong guildId, ulong channelId, ulong messageId) in toRemove) + foreach (var(guildId,channelId,messageId) in toRemove) raidStorageService.TryRemove(guildId, channelId, messageId); } } diff --git a/PoGo.DiscordBot/Services/RaidStorageService.cs b/PoGo.DiscordBot/Services/RaidStorageService.cs index 1736470..f064b46 100644 --- a/PoGo.DiscordBot/Services/RaidStorageService.cs +++ b/PoGo.DiscordBot/Services/RaidStorageService.cs @@ -9,7 +9,7 @@ public class RaidStorageService { // >> //readonly ConcurrentDictionary>> raids; - private readonly RaidGuildMapping raidGuilds; + readonly RaidGuildMapping raidGuilds; public RaidStorageService() { @@ -18,15 +18,15 @@ public RaidStorageService() public void AddRaid(ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfoDto) { - RaidChannelMapping raidChannels = raidGuilds.GuildRaids.GetOrAdd(guildId, _ => new RaidChannelMapping()); - RaidMessageMapping raidMessages = raidChannels.RaidChannels.GetOrAdd(channelId, _ => new RaidMessageMapping()); + var raidChannels = raidGuilds.GuildRaids.GetOrAdd(guildId, _ => new RaidChannelMapping()); + var raidMessages = raidChannels.RaidChannels.GetOrAdd(channelId, _ => new RaidMessageMapping()); raidMessages.RaidMessages[messageId] = raidInfoDto; } public RaidInfoDto GetRaid(ulong guildId, ulong channelId, int skip) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages)) return raidMessages.RaidMessages.Values .OrderByDescending(t => t.CreatedAt) .Skip(skip) @@ -37,9 +37,9 @@ public RaidInfoDto GetRaid(ulong guildId, ulong channelId, int skip) public RaidInfoDto GetRaid(ulong guildId, ulong channelId, ulong messageId) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages) && - raidMessages.RaidMessages.TryGetValue(messageId, out RaidInfoDto raidInfoDto)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && + raidMessages.RaidMessages.TryGetValue(messageId, out var raidInfoDto)) return raidInfoDto; return null; @@ -47,15 +47,15 @@ public RaidInfoDto GetRaid(ulong guildId, ulong channelId, ulong messageId) public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) { - return raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && -raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages) && + return raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && +raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && raidMessages.RaidMessages.TryRemove(messageId, out _); } public IEnumerable<(int Index, RaidInfoDto Raid)> GetActiveRaidsWithIndexes(ulong guildId, ulong channelId) { - if (raidGuilds.GuildRaids.TryGetValue(guildId, out RaidChannelMapping raidChannels) && - raidChannels.RaidChannels.TryGetValue(channelId, out RaidMessageMapping raidMessages)) + if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages)) return raidMessages.RaidMessages.Values .OrderByDescending(t => t.CreatedAt) .Select((t, i) => (i, t)) @@ -66,13 +66,13 @@ public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) public IEnumerable<(ulong guildId, ulong channelId, ulong messageId, RaidInfoDto raidInfo)> GetAll() { - foreach (KeyValuePair guild in raidGuilds.GuildRaids) - foreach (KeyValuePair channel in guild.Value.RaidChannels) - foreach (KeyValuePair raidMessage in channel.Value.RaidMessages) + foreach (var guild in raidGuilds.GuildRaids) + foreach (var channel in guild.Value.RaidChannels) + foreach (var raidMessage in channel.Value.RaidMessages) yield return (guild.Key, channel.Key, raidMessage.Key, raidMessage.Value); } - private class RaidGuildMapping + class RaidGuildMapping { // public ConcurrentDictionary GuildRaids { get; } @@ -83,7 +83,7 @@ public RaidGuildMapping() } } - private class RaidChannelMapping + class RaidChannelMapping { // public ConcurrentDictionary RaidChannels { get; } @@ -94,7 +94,7 @@ public RaidChannelMapping() } } - private class RaidMessageMapping + class RaidMessageMapping { // public ConcurrentDictionary RaidMessages { get; } diff --git a/PoGo.DiscordBot/Services/RoleService.cs b/PoGo.DiscordBot/Services/RoleService.cs index 260f904..49902af 100644 --- a/PoGo.DiscordBot/Services/RoleService.cs +++ b/PoGo.DiscordBot/Services/RoleService.cs @@ -5,9 +5,7 @@ namespace PoGo.DiscordBot.Services { public class RoleService { - public SocketRole GetRoleByName(SocketGuild guild, string name) - { - return guild.Roles.FirstOrDefault(t => t.Name == name); - } + public SocketRole GetRoleByName(SocketGuild guild, string name) => guild.Roles.FirstOrDefault(t => t.Name == name); + } } \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/TeamService.cs b/PoGo.DiscordBot/Services/TeamService.cs index f2c9b08..61fd955 100644 --- a/PoGo.DiscordBot/Services/TeamService.cs +++ b/PoGo.DiscordBot/Services/TeamService.cs @@ -13,7 +13,7 @@ namespace PoGo.DiscordBot.Services { public class TeamService { - private readonly ILogger logger; + readonly ILogger logger; public ConcurrentDictionary GuildTeamRoles { get; } // @@ -28,9 +28,9 @@ public async Task OnNewGuild(SocketGuild socketGuild) GuildTeamRoles[socketGuild.Id] = await GetTeamRoles(socketGuild); } - private async Task GetOrCreateRole(IGuild guild, PokemonTeam pokemonTeam) + async Task GetOrCreateRole(IGuild guild, PokemonTeam pokemonTeam) { - IRole role = guild.Roles.FirstOrDefault(t => Enum.TryParse(t.Name, out PokemonTeam team) && pokemonTeam == team); + var role = guild.Roles.FirstOrDefault(t => Enum.TryParse(t.Name, out var team) && pokemonTeam == team); if (role == null) { logger.LogInformation($"Creating new role for team {pokemonTeam}"); @@ -44,14 +44,14 @@ await role.ModifyAsync(t => return role; } - private async Task GetTeamRoles(IGuild guild) + async Task GetTeamRoles(IGuild guild) { - Dictionary roleIdtoTeam = new Dictionary(); - Dictionary teamToRole = new Dictionary(); + var roleIdtoTeam = new Dictionary(); + var teamToRole = new Dictionary(); foreach (PokemonTeam team in Enum.GetValues(typeof(PokemonTeam))) { - IRole role = await GetOrCreateRole(guild, team); + var role = await GetOrCreateRole(guild, team); roleIdtoTeam[role.Id] = team; teamToRole[team] = role; diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index cf0193b..7fdf7ea 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -13,8 +13,8 @@ namespace PoGo.DiscordBot.Services { public class UserService { - private readonly ILogger logger; - private readonly TeamService teamService; + readonly ILogger logger; + readonly TeamService teamService; public UserService(ILogger logger, TeamService teamService) { @@ -22,11 +22,11 @@ public UserService(ILogger logger, TeamService teamService) this.teamService = teamService; } - public static int? GetPlayerLevel(SocketGuildUser user) + public int? GetPlayerLevel(SocketGuildUser user) { - string name = user.Nickname ?? user.Username; - Match result = Regex.Match(name, @"\(\d+\)"); - string stringLevel = result.Captures.LastOrDefault()?.Value; + var name = user.Nickname ?? user.Username; + var result = Regex.Match(name, @"\(\d+\)"); + var stringLevel = result.Captures.LastOrDefault()?.Value; if (stringLevel != null && int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out int level) && level >= 1 && level <= 40) @@ -39,9 +39,9 @@ public UserService(ILogger logger, TeamService teamService) public PokemonTeam? GetTeam(SocketGuildUser user) { - IReadOnlyDictionary teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; + var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; - foreach (SocketRole role in user.Roles) + foreach (var role in user.Roles) { if (teamRoles.TryGetValue(role.Id, out PokemonTeam team)) { @@ -52,26 +52,22 @@ public UserService(ILogger logger, TeamService teamService) return null; } - public PlayerDto GetPlayer(SocketGuildUser user) - { - return new PlayerDto + public PlayerDto GetPlayer(SocketGuildUser user) => new PlayerDto { User = user, Team = GetTeam(user), Level = GetPlayerLevel(user), }; - } - public IEnumerable GetPlayers(IEnumerable users) - { - return users -.Where(t => !t.IsBot) -.Select(GetPlayer); - } + + public IEnumerable GetPlayers(IEnumerable users) => users + .Where(t => !t.IsBot) + .Select(GetPlayer); + public async Task CheckTeam(SocketGuildUser user) { - PokemonTeam? team = GetTeam(user); + var team = GetTeam(user); if (team == null) { diff --git a/PoGo.DiscordBot/configuration.Development.json b/PoGo.DiscordBot/configuration.Development.json index 91265de..9d79664 100644 --- a/PoGo.DiscordBot/configuration.Development.json +++ b/PoGo.DiscordBot/configuration.Development.json @@ -1,3 +1,3 @@ { - "Token": "", + "Token": "" } \ No newline at end of file From 340620d4ba4fde213c4eb2b9a0153cba5b93035e Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 8 Apr 2019 14:23:46 -0400 Subject: [PATCH 05/10] Revert some more cosmetic changes. --- PoGo.DiscordBot/Common/StringUtils.cs | 4 ++-- PoGo.DiscordBot/Dto/RaidInfoDto.cs | 4 ++-- PoGo.DiscordBot/Modules/HelpModule.cs | 4 ++-- PoGo.DiscordBot/Modules/RoleModule.cs | 2 +- PoGo.DiscordBot/PoGoBot.cs | 8 ++++---- PoGo.DiscordBot/Program.cs | 4 ++-- PoGo.DiscordBot/Services/RaidBossInfoService.cs | 2 +- PoGo.DiscordBot/Services/RaidChannelService.cs | 2 +- PoGo.DiscordBot/Services/RaidService.cs | 4 ++-- PoGo.DiscordBot/Services/RaidStorageService.cs | 11 +++++------ PoGo.DiscordBot/Services/UserService.cs | 2 +- 11 files changed, 23 insertions(+), 24 deletions(-) diff --git a/PoGo.DiscordBot/Common/StringUtils.cs b/PoGo.DiscordBot/Common/StringUtils.cs index 67fec11..5180ea4 100644 --- a/PoGo.DiscordBot/Common/StringUtils.cs +++ b/PoGo.DiscordBot/Common/StringUtils.cs @@ -7,8 +7,8 @@ public static class StringUtils { public static string ToLowerWithoutDiacritics(string text) { - string normalizedString = text.Normalize(NormalizationForm.FormD); - StringBuilder stringBuilder = new StringBuilder(text.Length); + var normalizedString = text.Normalize(NormalizationForm.FormD); + var stringBuilder = new StringBuilder(text.Length); foreach (var c in normalizedString) { diff --git a/PoGo.DiscordBot/Dto/RaidInfoDto.cs b/PoGo.DiscordBot/Dto/RaidInfoDto.cs index e13cd4b..c46bb75 100644 --- a/PoGo.DiscordBot/Dto/RaidInfoDto.cs +++ b/PoGo.DiscordBot/Dto/RaidInfoDto.cs @@ -143,7 +143,7 @@ public static RaidInfoDto Parse(IUserMessage message) if (embed.Fields[2].Name.Equals(Resources.Time, StringComparison.OrdinalIgnoreCase)) { - DateTime? time = ParseTime(embed.Fields[2].Value, message.CreatedAt.Date); + var time = ParseTime(embed.Fields[2].Value, message.CreatedAt.Date); if (!time.HasValue) return null; @@ -158,7 +158,7 @@ public static RaidInfoDto Parse(IUserMessage message) } else if (embed.Fields[2].Name.Equals(Resources.Date, StringComparison.OrdinalIgnoreCase)) { - DateTime? dateTime = ParseDateTime(embed.Fields[2].Value); + var dateTime = ParseDateTime(embed.Fields[2].Value); if (!dateTime.HasValue) return null; diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index 0607529..b3bb251 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -32,7 +32,7 @@ public HelpModule(CommandService commandService, IServiceProvider serviceProvide [Summary("ListCommandsSummary")] public async Task Help() { - Dictionary> groupCommands = new Dictionary>(); + var groupCommands = new Dictionary>(); foreach (var module in commandService.Modules) { @@ -85,7 +85,7 @@ string CommandsToString(IEnumerable commands) => } if (currentPageCommands.Count > 0) commandPages.Add(currentPageCommands); - List pages = commandPages.Select(CommandsToString).ToList(); + var pages = commandPages.Select(CommandsToString).ToList(); if (pages.Count > 1) { diff --git a/PoGo.DiscordBot/Modules/RoleModule.cs b/PoGo.DiscordBot/Modules/RoleModule.cs index c645337..a2ff854 100644 --- a/PoGo.DiscordBot/Modules/RoleModule.cs +++ b/PoGo.DiscordBot/Modules/RoleModule.cs @@ -58,7 +58,7 @@ public async Task RemoveRole([Summary("Název role")]string roleName) if (!(Context.User is SocketGuildUser user)) return; - if (!availableRoles.TryGetValue(Context.Guild.Id, out string[] roles) || !roles.Contains(roleName)) + if (!availableRoles.TryGetValue(Context.Guild.Id, out var roles) || !roles.Contains(roleName)) return; var role = roleService.GetRoleByName(Context.Guild, roleName); diff --git a/PoGo.DiscordBot/PoGoBot.cs b/PoGo.DiscordBot/PoGoBot.cs index 1f695a0..dbe3e99 100644 --- a/PoGo.DiscordBot/PoGoBot.cs +++ b/PoGo.DiscordBot/PoGoBot.cs @@ -118,7 +118,7 @@ async Task GuildAvailable(SocketGuild guild) var guildOptions = ServiceProvider.GetService>().Value.Guilds; raidChannelService.OnNewGuild(guild, guildOptions); - RaidService raidService = ServiceProvider.GetService(); + var raidService = ServiceProvider.GetService(); await raidService.OnNewGuild(guild); } @@ -128,7 +128,7 @@ async Task OnReactionRemoved(Cacheable message, ISocketMess await raidService.OnReactionRemoved(message, channel, reaction); } - private async Task ReactionAdded(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) + async Task ReactionAdded(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { var raidService = ServiceProvider.GetService(); await raidService.OnReactionAdded(message, channel, reaction); @@ -168,7 +168,7 @@ Task Disconnected(Exception exception) public IServiceProvider ConfigureServices() { - ServiceCollection services = new ServiceCollection(); + var services = new ServiceCollection(); services.AddOptions(); services.Configure(Configuration); @@ -207,7 +207,7 @@ public async Task RunAsync() async Task InitCommands() { - var modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); + var modules = await commands.AddModulesAsync(Assembly.GetEntryAssembly()); logger.LogDebug("Loading modules"); foreach (var module in modules) logger.LogDebug($"{module.Name}: {string.Join(", ", module.Commands.Select(t => t.Name))}"); diff --git a/PoGo.DiscordBot/Program.cs b/PoGo.DiscordBot/Program.cs index 9321328..8ac03a9 100644 --- a/PoGo.DiscordBot/Program.cs +++ b/PoGo.DiscordBot/Program.cs @@ -6,9 +6,9 @@ namespace PoGo.DiscordBot { - internal class Program + class Program { - private static async Task Main(string[] args) + static async Task Main(string[] args) { using (var bot = new PoGoBot()) { diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index 2796ece..f528469 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -29,7 +29,7 @@ public IEnumerable GetAllKnownBossNames() =>raidBosses.Values .OrderBy(t => t); public RaidBossDto GetBoss(string bossName) => - raidBosses.TryGetValue(bossName.ToLower(), out RaidBossDto dto) ? dto : null; + raidBosses.TryGetValue(bossName.ToLower(), out var dto) ? dto : null; public string GetBossNameWithEmoji(string bossName, SocketGuild guild) { diff --git a/PoGo.DiscordBot/Services/RaidChannelService.cs b/PoGo.DiscordBot/Services/RaidChannelService.cs index d227eaf..b33778a 100644 --- a/PoGo.DiscordBot/Services/RaidChannelService.cs +++ b/PoGo.DiscordBot/Services/RaidChannelService.cs @@ -10,7 +10,7 @@ namespace PoGo.DiscordBot.Services { public class RaidChannelService { - private class RaidChannelBinding + class RaidChannelBinding { public ITextChannel From { get; } public ITextChannel To { get; } diff --git a/PoGo.DiscordBot/Services/RaidService.cs b/PoGo.DiscordBot/Services/RaidService.cs index 515b66f..102841d 100644 --- a/PoGo.DiscordBot/Services/RaidService.cs +++ b/PoGo.DiscordBot/Services/RaidService.cs @@ -98,7 +98,7 @@ async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message // Remove invalid reactions foreach (var react in invalidReactions) { - IReadOnlyCollection users = await message.GetReactionUsersAsync(react.Key.Name, options: retryOptions); + var users = await message.GetReactionUsersAsync(react.Key.Name, options: retryOptions); foreach (var user in users) await message.RemoveReactionAsync(react.Key, user, options: retryOptions); } @@ -168,7 +168,7 @@ public async Task OnReactionAdded(Cacheable message, ISocke return; IUserMessage raidMessage = await message.GetOrDownloadAsync(); - SocketGuildUser user = socketGuildChannel.GetUser(reaction.UserId); + var user = socketGuildChannel.GetUser(reaction.UserId); if (user.IsBot) return; if (!IsValidReactionEmote(reaction.Emote.Name)) diff --git a/PoGo.DiscordBot/Services/RaidStorageService.cs b/PoGo.DiscordBot/Services/RaidStorageService.cs index f064b46..b9bfe99 100644 --- a/PoGo.DiscordBot/Services/RaidStorageService.cs +++ b/PoGo.DiscordBot/Services/RaidStorageService.cs @@ -45,12 +45,11 @@ public RaidInfoDto GetRaid(ulong guildId, ulong channelId, ulong messageId) return null; } - public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) - { - return raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && -raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && -raidMessages.RaidMessages.TryRemove(messageId, out _); - } + public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) => + raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && + raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && + raidMessages.RaidMessages.TryRemove(messageId, out _); + public IEnumerable<(int Index, RaidInfoDto Raid)> GetActiveRaidsWithIndexes(ulong guildId, ulong channelId) { diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index 7fdf7ea..ed04b12 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -43,7 +43,7 @@ public UserService(ILogger logger, TeamService teamService) foreach (var role in user.Roles) { - if (teamRoles.TryGetValue(role.Id, out PokemonTeam team)) + if (teamRoles.TryGetValue(role.Id, out var team)) { return team; } From e2d12c9616fdeb06a0ad35dff4c266fd5871e0a6 Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 8 Apr 2019 14:35:33 -0400 Subject: [PATCH 06/10] Revert more cosmetic changes. --- PoGo.DiscordBot/Modules/CleanModule.cs | 4 +- PoGo.DiscordBot/Modules/HelpModule.cs | 2 +- PoGo.DiscordBot/Modules/RaidModule.cs | 84 +++++++++---------- .../Services/RaidBossInfoService.cs | 4 +- .../Services/RaidChannelService.cs | 4 +- PoGo.DiscordBot/Services/RaidService.cs | 14 ++-- PoGo.DiscordBot/Services/UserService.cs | 10 +-- 7 files changed, 61 insertions(+), 61 deletions(-) diff --git a/PoGo.DiscordBot/Modules/CleanModule.cs b/PoGo.DiscordBot/Modules/CleanModule.cs index baf70d8..c281c4e 100644 --- a/PoGo.DiscordBot/Modules/CleanModule.cs +++ b/PoGo.DiscordBot/Modules/CleanModule.cs @@ -35,9 +35,9 @@ public async Task DeleteLastMessages([Summary("User")]IUser user, await DeleteMessagesAsync(userId, count); } - private async Task DeleteMessagesAsync(ulong userId, int count) + async Task DeleteMessagesAsync(ulong userId, int count) { - foreach (IReadOnlyCollection messages in Context.Channel.GetMessagesAsync().ToEnumerable()) + foreach (var messages in Context.Channel.GetMessagesAsync().ToEnumerable()) { var messagesToDelete = messages.Where(t => t.Author.Id == userId).Take(count); if (messagesToDelete != null) diff --git a/PoGo.DiscordBot/Modules/HelpModule.cs b/PoGo.DiscordBot/Modules/HelpModule.cs index b3bb251..c3f8f72 100644 --- a/PoGo.DiscordBot/Modules/HelpModule.cs +++ b/PoGo.DiscordBot/Modules/HelpModule.cs @@ -170,7 +170,7 @@ string CommandInfoSignature(CommandInfo ci, CommandInfoSignature signature) return sb.ToString(); } - foreach (CommandMatch match in result.Commands) + foreach (var match in result.Commands) { var cmd = match.Command; StringBuilder sb = new StringBuilder() diff --git a/PoGo.DiscordBot/Modules/RaidModule.cs b/PoGo.DiscordBot/Modules/RaidModule.cs index 474b84c..fa599d8 100644 --- a/PoGo.DiscordBot/Modules/RaidModule.cs +++ b/PoGo.DiscordBot/Modules/RaidModule.cs @@ -20,15 +20,15 @@ namespace PoGo.DiscordBot.Modules [Alias("r")] public class RaidModule : InteractiveBase { - private static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; - private readonly TeamService teamService; - private readonly RaidService raidService; - private readonly ILogger logger; - private readonly RaidChannelService raidChannelService; - private readonly ConfigurationService configuration; - private readonly RaidBossInfoService raidBossInfoService; - private readonly GymLocationService gymLocationService; - private readonly RaidStorageService raidStorageService; + static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; + readonly TeamService teamService; + readonly RaidService raidService; + readonly ILogger logger; + readonly RaidChannelService raidChannelService; + readonly ConfigurationService configuration; + readonly RaidBossInfoService raidBossInfoService; + readonly GymLocationService gymLocationService; + readonly RaidStorageService raidStorageService; public RaidModule(TeamService teamService, RaidService raidService, ILogger logger, RaidChannelService raidChannelService, ConfigurationService configuration, RaidBossInfoService raidBossInfoService, GymLocationService gymLocationService, RaidStorageService raidStorageService) @@ -52,7 +52,7 @@ public async Task StartRaid( [Summary("Place")]string location, [Summary("Time (" + RaidInfoDto.TimeFormat + ").")]string time) { - DateTime? parsedTime = RaidInfoDto.ParseTime(time); + var parsedTime = RaidInfoDto.ParseTime(time); if (!parsedTime.HasValue) { await ReplyAsync(Resources.BadTimeFormat + $"({RaidInfoDto.TimeFormat} 24H)."); @@ -65,22 +65,22 @@ public async Task StartRaid( return; } - RaidChannelBindingDto raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); + var raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); - RaidInfoDto raidInfo = new RaidInfoDto(RaidType.Normal) + var raidInfo = new RaidInfoDto(RaidType.Normal) { BossName = bossName, Location = location, DateTime = parsedTime.Value, }; - System.Collections.Generic.IEnumerable roles = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles.Values; + var roles = teamService.GuildTeamRoles[Context.Guild.Id].TeamRoles.Values; bool shouldMention = !(configuration.GetGuildOptions(Context.Guild.Id)?.IgnoreMention ?? false); string mention = string.Empty; if (shouldMention) mention = raidChannelBinding.Mention == null ? string.Join(' ', roles.Select(t => t.Mention)) : raidChannelBinding.Mention.Mention; - IUserMessage message = await raidChannelBinding.Channel.SendMessageAsync($"{raidInfo.ToSimpleString()} {mention}", embed: raidInfo.ToEmbed()); + var message = await raidChannelBinding.Channel.SendMessageAsync($"{raidInfo.ToSimpleString()} {mention}", embed: raidInfo.ToEmbed()); logger.LogInformation($"New raid has been created '{bossName}' '{location}' '{parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}'"); raidInfo.Message = message; await Context.Message.AddReactionAsync(Emojis.Check); @@ -104,14 +104,14 @@ public async Task StartScheduledRaid( [Summary("Place")]string location, [Remainder][Summary("Date (" + RaidInfoDto.DateTimeFormat + ").")]string dateTime) { - RaidChannelBindingDto raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); + var raidChannelBinding = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id); if (raidChannelBinding == null || !raidChannelBinding.AllowScheduledRaids) { await ReplyAsync(Resources.RaidNotPossible); return; } - DateTime? parsedDateTime = RaidInfoDto.ParseDateTime(dateTime); + var parsedDateTime = RaidInfoDto.ParseDateTime(dateTime); if (!parsedDateTime.HasValue) { await ReplyAsync((Resources.DateNotValid) + $"({RaidInfoDto.DateTimeFormat} 24H)."); @@ -124,14 +124,14 @@ public async Task StartScheduledRaid( return; } - RaidInfoDto raidInfo = new RaidInfoDto(RaidType.Scheduled) + var raidInfo = new RaidInfoDto(RaidType.Scheduled) { BossName = bossName, Location = location, DateTime = parsedDateTime.Value, }; - IUserMessage message = await raidChannelBinding.Channel.SendMessageAsync(string.Empty, embed: raidInfo.ToEmbed()); + var message = await raidChannelBinding.Channel.SendMessageAsync(string.Empty, embed: raidInfo.ToEmbed()); logger.LogInformation($"New scheduled raid has been created '{bossName}' '{location}' '{parsedDateTime.Value.ToString(RaidInfoDto.DateTimeFormat)}'"); raidInfo.Message = message; await Context.Message.AddReactionAsync(Emojis.Check); @@ -140,10 +140,10 @@ public async Task StartScheduledRaid( raidStorageService.AddRaid(Context.Guild.Id, raidChannelBinding.Channel.Id, message.Id, raidInfo); } - private RaidInfoDto GetRaid(int skip) + RaidInfoDto GetRaid(int skip) { - ulong raidChannelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; - RaidInfoDto raid = raidStorageService.GetRaid(Context.Guild.Id, raidChannelId, skip); + var raidChannelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; + var raid = raidStorageService.GetRaid(Context.Guild.Id, raidChannelId, skip); return raid; } @@ -156,7 +156,7 @@ public async Task AdjustRaidTime( [Summary("Počet anket odspodu.")] int skip = 0) { // TODO scheduled raid - RaidInfoDto raid = GetRaid(skip); + var raid = GetRaid(skip); if (raid == null) { @@ -164,7 +164,7 @@ public async Task AdjustRaidTime( return; } - DateTime? parsedTime = RaidInfoDto.ParseTime(time); + var parsedTime = RaidInfoDto.ParseTime(time); if (!parsedTime.HasValue) { await ReplyAsync(Resources.BadTimeFormat + $" ({RaidInfoDto.TimeFormat} 24H)."); @@ -177,14 +177,14 @@ public async Task AdjustRaidTime( return; } - SocketGuildUser currentUser = Context.User as SocketGuildUser; + var currentUser = Context.User as SocketGuildUser; logger.LogInformation($"User '{currentUser.Nickname ?? Context.User.Username}' with id '{Context.User.Id}'" + $" changed raid with id '{raid.Message.Id}'" + $" time changed from {raid.DateTime.ToString(RaidInfoDto.TimeFormat)} to {parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}"); - foreach (PlayerDto player in raid.Players.Values) + foreach (var player in raid.Players.Values) { - IGuildUser user = player.User; + var user = player.User; await user.SendMessageAsync( $"Změna raid času z {raid.DateTime.ToString(RaidInfoDto.TimeFormat)} na {parsedTime.Value.ToString(RaidInfoDto.TimeFormat)}!" + $" Jestli ti změna nevyhovuje, tak se odhlaš z raidu nebo se domluv s ostatními na jiném čase."); @@ -202,7 +202,7 @@ public async Task AdjustRaidBoss( [Summary("Přenastaví bosse raidu.")]string boss, [Summary("Počet anket odspodu.")] int skip = 0) { - RaidInfoDto raid = GetRaid(skip); + var raid = GetRaid(skip); if (raid == null) { @@ -233,7 +233,7 @@ public async Task MentionRaidPlayers( [Summary("Počet anket odspodu.")] int skip = 0, [Remainder][Summary("Text")]string text = null) { - RaidInfoDto raid = GetRaid(skip); + var raid = GetRaid(skip); if (raid == null) { @@ -241,7 +241,7 @@ public async Task MentionRaidPlayers( return; } - HashSet users = raid.Players.Values.ToHashSet(); + var users = raid.Players.Values.ToHashSet(); if (users.Count > 0) { @@ -261,7 +261,7 @@ public async Task MentionRaidPlayers( public async Task DeleteRaid( [Summary("Počet anket odspodu.")] int skip = 0) { - RaidInfoDto raid = GetRaid(skip); + var raid = GetRaid(skip); if (raid == null) { @@ -269,14 +269,14 @@ public async Task DeleteRaid( return; } - IUserMessage questionMessage = await ReplyAsync($"Vážně chceš smazat tenhle raid: '{raid.ToSimpleString()}'? [y]"); - SocketMessage responseMessage = await NextMessageAsync(); + var questionMessage = await ReplyAsync($"Vážně chceš smazat tenhle raid: '{raid.ToSimpleString()}'? [y]"); + var responseMessage = await NextMessageAsync(); if (responseMessage == null || !string.Equals(responseMessage.Content, "y", StringComparison.OrdinalIgnoreCase)) return; - foreach (PlayerDto player in raid.Players.Values) + foreach (var player in raid.Players.Values) { - IGuildUser user = player.User; + var user = player.User; await user.SendMessageAsync($"Raid {raid.ToSimpleString()} se ruší!"); } @@ -290,7 +290,7 @@ public async Task DeleteRaid( public async Task RaidBossInfo( [Summary("Název bosse.")] string bossName) { - RaidBossDto boss = raidBossInfoService.GetBoss(bossName); + var boss = raidBossInfoService.GetBoss(bossName); if (boss == null) { @@ -300,8 +300,8 @@ public async Task RaidBossInfo( } string bossMention = raidBossInfoService.GetBossNameWithEmoji(boss.BossName, Context.Guild); - IEnumerable countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); - string countersField = string.Join(", ", countersWithEmojis); + var countersWithEmojis = boss.Counters?.Select(c => raidBossInfoService.GetBossNameWithEmoji(c, Context.Guild)) ?? Enumerable.Empty(); + var countersField = string.Join(", ", countersWithEmojis); EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle(bossMention) .AddInlineField("Type", string.Join(", ", boss.Type)) @@ -326,15 +326,15 @@ public async Task RaidLocation( return; } - IEnumerable searchResult = gymLocationService.Search(Context.Guild.Id, name); + var searchResult = gymLocationService.Search(Context.Guild.Id, name); if (searchResult == null) { await ReplyAsync(Resources.CommandNotSupported); return; } - StringBuilder sb = new StringBuilder(); - foreach (GymInfoDto gymInfo in searchResult) + var sb = new StringBuilder(); + foreach (var gymInfo in searchResult) sb.AppendLine($"{gymInfo.Name}: {gymLocationService.GetMapUrl(gymInfo)}"); await ReplyAsync(sb.ToString()); @@ -344,8 +344,8 @@ public async Task RaidLocation( [Summary("RaidListSummary")] public async Task RaidList() { - ulong channelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; - IEnumerable<(int Index, RaidInfoDto Raid)> raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); + var channelId = raidChannelService.TryGetRaidChannelBinding(Context.Guild.Id, Context.Channel.Id).Channel.Id; + var raids = raidStorageService.GetActiveRaidsWithIndexes(Context.Guild.Id, channelId); if (!raids.Any()) { await ReplyAsync(Resources.NoActiveRaids); diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index f528469..b548845 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -25,8 +25,8 @@ public RaidBossInfoService(IOptions options) } public IEnumerable GetAllKnownBossNames() =>raidBosses.Values - .Select(t => t.BossName) - .OrderBy(t => t); + .Select(t => t.BossName) + .OrderBy(t => t); public RaidBossDto GetBoss(string bossName) => raidBosses.TryGetValue(bossName.ToLower(), out var dto) ? dto : null; diff --git a/PoGo.DiscordBot/Services/RaidChannelService.cs b/PoGo.DiscordBot/Services/RaidChannelService.cs index b33778a..8eddcbe 100644 --- a/PoGo.DiscordBot/Services/RaidChannelService.cs +++ b/PoGo.DiscordBot/Services/RaidChannelService.cs @@ -94,8 +94,8 @@ public RaidChannelBindingDto TryGetRaidChannelBinding(ulong guildId, ulong fromT public RaidChannelBindingDto TryGetRaidChannelBindingTo(ulong guildId, ulong toTextChannelId) { - if (guilds.TryGetValue(guildId, out List raidChannelBindings)) - foreach (RaidChannelBinding channel in raidChannelBindings) + if (guilds.TryGetValue(guildId, out var raidChannelBindings)) + foreach (var channel in raidChannelBindings) if (channel.To.Id == toTextChannelId) return new RaidChannelBindingDto { diff --git a/PoGo.DiscordBot/Services/RaidService.cs b/PoGo.DiscordBot/Services/RaidService.cs index 102841d..ecd4e1f 100644 --- a/PoGo.DiscordBot/Services/RaidService.cs +++ b/PoGo.DiscordBot/Services/RaidService.cs @@ -41,8 +41,8 @@ public async Task UpdateRaidMessages(SocketGuild guild, IMessageChannel channel, try { var channelBinding = raidChannelService.TryGetRaidChannelBindingTo(guild.Id, channel.Id); - bool mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; - DateTime dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.AddHours(-2) : DateTime.UtcNow.AddDays(-14); + var mayContainScheduledRaids = channelBinding != null && channelBinding.AllowScheduledRaids; + var dateTimeFrom = !mayContainScheduledRaids ? DateTime.UtcNow.AddHours(-2) : DateTime.UtcNow.AddDays(-14); var batchMessages = await channel.GetMessagesAsync(count, options: retryOptions) .ToList(); @@ -93,8 +93,8 @@ async Task FixRaidMessageAfterLoad(SocketGuild guild, IUserMessage message await message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); - var allReactions = message.Reactions; - var invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); + var allReactions = message.Reactions; + var invalidReactions = allReactions.Where(t => !IsValidReactionEmote(t.Key.Name)).ToList(); // Remove invalid reactions foreach (var react in invalidReactions) { @@ -130,7 +130,7 @@ bool IsValidReactionEmote(string emote) => UnicodeEmojis.KeycapDigits.Contains(emote); - int ExtraPlayerKeycapDigitToCount(string name) => Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; + int ExtraPlayerKeycapDigitToCount(string name) => Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; public async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) @@ -196,7 +196,7 @@ public async Task UpdateRaidMessages() { var toRemove = new List<(ulong guildId, ulong channelId, ulong messageId)>(); - foreach (var(guildId,channelId, messageId,raidInfo) in raidStorageService.GetAll()) + foreach (var (guildId, channelId, messageId, raidInfo) in raidStorageService.GetAll()) { await raidInfo.Message.ModifyAsync(t => t.Embed = raidInfo.ToEmbed()); @@ -204,7 +204,7 @@ public async Task UpdateRaidMessages() toRemove.Add((guildId, channelId, messageId)); } - foreach (var(guildId,channelId,messageId) in toRemove) + foreach (var (guildId, channelId, messageId) in toRemove) raidStorageService.TryRemove(guildId, channelId, messageId); } } diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index ed04b12..24740c1 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -53,11 +53,11 @@ public UserService(ILogger logger, TeamService teamService) } public PlayerDto GetPlayer(SocketGuildUser user) => new PlayerDto - { - User = user, - Team = GetTeam(user), - Level = GetPlayerLevel(user), - }; + { + User = user, + Team = GetTeam(user), + Level = GetPlayerLevel(user), + }; public IEnumerable GetPlayers(IEnumerable users) => users From b2ff0b3767d072899d071d16dce116150c7186ab Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 8 Apr 2019 14:40:32 -0400 Subject: [PATCH 07/10] Changes in both raid module and raid boss info service were applied. --- PoGo.DiscordBot/Modules/RaidModule.cs | 8 ++++---- PoGo.DiscordBot/Services/RaidBossInfoService.cs | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/PoGo.DiscordBot/Modules/RaidModule.cs b/PoGo.DiscordBot/Modules/RaidModule.cs index fa599d8..728556a 100644 --- a/PoGo.DiscordBot/Modules/RaidModule.cs +++ b/PoGo.DiscordBot/Modules/RaidModule.cs @@ -210,14 +210,14 @@ public async Task AdjustRaidBoss( return; } - SocketGuildUser currentUser = Context.User as SocketGuildUser; + var currentUser = Context.User as SocketGuildUser; logger.LogInformation($"User '{currentUser.Nickname ?? Context.User.Username}' with id '{Context.User.Id}'" + $" changed raid with id '{raid.Message.Id}'" + $" boss changed from {raid.BossName} to {boss}"); - foreach (PlayerDto player in raid.Players.Values) + foreach (var player in raid.Players.Values) { - IGuildUser user = player.User; + var user = player.User; await user.SendMessageAsync($"Změna raid bosse z '{raid.BossName}' na '{boss}'!"); } @@ -294,7 +294,7 @@ public async Task RaidBossInfo( if (boss == null) { - string availableBosses = string.Join(", ", raidBossInfoService.GetAllKnownBossNames()); + var availableBosses = string.Join(", ", raidBossInfoService.GetAllKnownBossNames()); await ReplyAsync($"Boss nenalezen - znám informace pouze o: {availableBosses}."); return; } diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index b548845..3a89237 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -24,9 +24,9 @@ public RaidBossInfoService(IOptions options) }); } - public IEnumerable GetAllKnownBossNames() =>raidBosses.Values - .Select(t => t.BossName) - .OrderBy(t => t); + public IEnumerable GetAllKnownBossNames() => raidBosses.Values + .Select(t => t.BossName) + .OrderBy(t => t); public RaidBossDto GetBoss(string bossName) => raidBosses.TryGetValue(bossName.ToLower(), out var dto) ? dto : null; From d20716e54645137545de477f3ab067b4f6b923fa Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 8 Apr 2019 14:46:24 -0400 Subject: [PATCH 08/10] More slight cosmetic reversions. --- .../Modules/Preconditions/TeamPreconditionAttribute.cs | 2 +- PoGo.DiscordBot/Services/UserService.cs | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs index 68a04e2..c5fe41d 100644 --- a/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs +++ b/PoGo.DiscordBot/Modules/Preconditions/TeamPreconditionAttribute.cs @@ -17,7 +17,7 @@ public override Task CheckPermissions(ICommandContext contex var userService = services.GetService(); var team = userService.GetTeam(guildUser); - if (team == null) + if(team == null) return Task.FromResult(TeamPreconditionResult.Fail); return Task.FromResult(TeamPreconditionResult.Success); diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index 24740c1..8c2f6c0 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -42,12 +42,8 @@ public UserService(ILogger logger, TeamService teamService) var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; foreach (var role in user.Roles) - { if (teamRoles.TryGetValue(role.Id, out var team)) - { return team; - } - } return null; } From d65c3c3c12a340fc4fec71bb46e613fba97a2801 Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 15 Apr 2019 10:21:09 -0400 Subject: [PATCH 09/10] Revert spacing as much as I can. --- PoGo.DiscordBot/Configuration/TeamRoleColors.cs | 3 --- PoGo.DiscordBot/LogSeverityExtensions.cs | 6 ------ PoGo.DiscordBot/Services/GymLocationService.cs | 2 +- PoGo.DiscordBot/Services/RaidBossInfoService.cs | 4 ++-- PoGo.DiscordBot/Services/RaidStorageService.cs | 1 - PoGo.DiscordBot/Services/RoleService.cs | 1 - PoGo.DiscordBot/Services/UserService.cs | 1 + 7 files changed, 4 insertions(+), 14 deletions(-) diff --git a/PoGo.DiscordBot/Configuration/TeamRoleColors.cs b/PoGo.DiscordBot/Configuration/TeamRoleColors.cs index 45946df..9ecfd29 100644 --- a/PoGo.DiscordBot/Configuration/TeamRoleColors.cs +++ b/PoGo.DiscordBot/Configuration/TeamRoleColors.cs @@ -11,13 +11,10 @@ public static Color GetColor(PokemonTeam team) { case PokemonTeam.Mystic: return new Color(0x00, 0xb8, 0xff); - case PokemonTeam.Instinct: return new Color(0xff, 0xf5, 0x00); - case PokemonTeam.Valor: return new Color(0xff, 0x19, 0x05); - default: throw new Exception("Unknown team"); } diff --git a/PoGo.DiscordBot/LogSeverityExtensions.cs b/PoGo.DiscordBot/LogSeverityExtensions.cs index 61a582c..0c54eba 100644 --- a/PoGo.DiscordBot/LogSeverityExtensions.cs +++ b/PoGo.DiscordBot/LogSeverityExtensions.cs @@ -11,22 +11,16 @@ public static LogLevel ToLogLevel(this LogSeverity logSeverity) { case LogSeverity.Critical: return LogLevel.Critical; - case LogSeverity.Error: return LogLevel.Error; - case LogSeverity.Warning: return LogLevel.Warning; - case LogSeverity.Info: return LogLevel.Information; - case LogSeverity.Verbose: return LogLevel.Trace; - case LogSeverity.Debug: return LogLevel.Debug; - default: return LogLevel.Critical; } diff --git a/PoGo.DiscordBot/Services/GymLocationService.cs b/PoGo.DiscordBot/Services/GymLocationService.cs index ae3d916..c3a04d2 100644 --- a/PoGo.DiscordBot/Services/GymLocationService.cs +++ b/PoGo.DiscordBot/Services/GymLocationService.cs @@ -26,7 +26,7 @@ public GymLocationService(IOptions options) public IEnumerable Search(ulong guildId, string name) { if (!gymsInfos.TryGetValue(guildId, out var gyms)) - return default; + return null; var normalizedName = StringUtils.ToLowerWithoutDiacritics(name); return gyms diff --git a/PoGo.DiscordBot/Services/RaidBossInfoService.cs b/PoGo.DiscordBot/Services/RaidBossInfoService.cs index 3a89237..ece3ea2 100644 --- a/PoGo.DiscordBot/Services/RaidBossInfoService.cs +++ b/PoGo.DiscordBot/Services/RaidBossInfoService.cs @@ -25,8 +25,8 @@ public RaidBossInfoService(IOptions options) } public IEnumerable GetAllKnownBossNames() => raidBosses.Values - .Select(t => t.BossName) - .OrderBy(t => t); + .Select(t => t.BossName) + .OrderBy(t => t); public RaidBossDto GetBoss(string bossName) => raidBosses.TryGetValue(bossName.ToLower(), out var dto) ? dto : null; diff --git a/PoGo.DiscordBot/Services/RaidStorageService.cs b/PoGo.DiscordBot/Services/RaidStorageService.cs index b9bfe99..e65e2b0 100644 --- a/PoGo.DiscordBot/Services/RaidStorageService.cs +++ b/PoGo.DiscordBot/Services/RaidStorageService.cs @@ -50,7 +50,6 @@ public bool TryRemove(ulong guildId, ulong channelId, ulong messageId) => raidChannels.RaidChannels.TryGetValue(channelId, out var raidMessages) && raidMessages.RaidMessages.TryRemove(messageId, out _); - public IEnumerable<(int Index, RaidInfoDto Raid)> GetActiveRaidsWithIndexes(ulong guildId, ulong channelId) { if (raidGuilds.GuildRaids.TryGetValue(guildId, out var raidChannels) && diff --git a/PoGo.DiscordBot/Services/RoleService.cs b/PoGo.DiscordBot/Services/RoleService.cs index 49902af..eb26c40 100644 --- a/PoGo.DiscordBot/Services/RoleService.cs +++ b/PoGo.DiscordBot/Services/RoleService.cs @@ -6,6 +6,5 @@ namespace PoGo.DiscordBot.Services public class RoleService { public SocketRole GetRoleByName(SocketGuild guild, string name) => guild.Roles.FirstOrDefault(t => t.Name == name); - } } \ No newline at end of file diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index 8c2f6c0..c16458c 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -37,6 +37,7 @@ public UserService(ILogger logger, TeamService teamService) return null; } + public PokemonTeam? GetTeam(SocketGuildUser user) { var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; From 8d65a59f6acdf2967e3d74c397851b2a5022ad9e Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 15 Apr 2019 12:54:38 -0400 Subject: [PATCH 10/10] Use the DEBUG constant defined by Visual Studio if the environment variable is not found. Also try to create a nice text file for letting users know to contribute more languages. --- PoGo.DiscordBot/Localizing.txt | 8 ++++++++ PoGo.DiscordBot/PoGoBot.cs | 9 ++++++++- PoGo.DiscordBot/Program.cs | 5 +---- PoGo.DiscordBot/Services/RaidService.cs | 3 +-- PoGo.DiscordBot/Services/UserService.cs | 12 +++--------- PoGo.DiscordBot/TextFile1.txt | 1 + 6 files changed, 22 insertions(+), 16 deletions(-) create mode 100644 PoGo.DiscordBot/Localizing.txt create mode 100644 PoGo.DiscordBot/TextFile1.txt diff --git a/PoGo.DiscordBot/Localizing.txt b/PoGo.DiscordBot/Localizing.txt new file mode 100644 index 0000000..df0bacb --- /dev/null +++ b/PoGo.DiscordBot/Localizing.txt @@ -0,0 +1,8 @@ +If you wish to support the PoGo Discord bot in +your native language, create a pull request. +The easiest way to add a new .resx file is to +use the Zeta Resource Editor at +https://archive.codeplex.com/?p=ZetaResourceEditor and make a pull request. + + +Thank you for wanting to contribute additional languages. \ No newline at end of file diff --git a/PoGo.DiscordBot/PoGoBot.cs b/PoGo.DiscordBot/PoGoBot.cs index dbe3e99..0102fdf 100644 --- a/PoGo.DiscordBot/PoGoBot.cs +++ b/PoGo.DiscordBot/PoGoBot.cs @@ -35,7 +35,14 @@ public PoGoBot() { string environment = Environment.GetEnvironmentVariable("PoGoEnvironment"); if (string.IsNullOrEmpty(environment)) - throw new Exception($"Unknown environment '{environment}'"); + { +#if DEBUG + environment = "Development"; +#else + environment = "Production"; +#endif + } + //throw new Exception($"Unknown environment '{environment}'"); Console.WriteLine($"Environment: {environment}"); Configuration = new ConfigurationBuilder() diff --git a/PoGo.DiscordBot/Program.cs b/PoGo.DiscordBot/Program.cs index 8ac03a9..66b516c 100644 --- a/PoGo.DiscordBot/Program.cs +++ b/PoGo.DiscordBot/Program.cs @@ -1,7 +1,4 @@ -using PoGo.DiscordBot.Properties; -using System; -using System.Globalization; -using System.Threading; +using System.Threading; using System.Threading.Tasks; namespace PoGo.DiscordBot diff --git a/PoGo.DiscordBot/Services/RaidService.cs b/PoGo.DiscordBot/Services/RaidService.cs index ecd4e1f..79a7ccd 100644 --- a/PoGo.DiscordBot/Services/RaidService.cs +++ b/PoGo.DiscordBot/Services/RaidService.cs @@ -12,6 +12,7 @@ namespace PoGo.DiscordBot.Services public class RaidService { const ulong DefaultRaidChannelId = 348844165741936641; + static readonly RequestOptions retryOptions = new RequestOptions { RetryMode = RetryMode.AlwaysRetry, Timeout = 10000 }; readonly ILogger logger; readonly UserService userService; @@ -129,10 +130,8 @@ bool IsValidReactionEmote(string emote) => emote == UnicodeEmojis.ThumbsDown || UnicodeEmojis.KeycapDigits.Contains(emote); - int ExtraPlayerKeycapDigitToCount(string name) => Array.IndexOf(UnicodeEmojis.KeycapDigits, name) + 1; - public async Task OnReactionRemoved(Cacheable message, ISocketMessageChannel channel, SocketReaction reaction) { if (!(channel is SocketGuildChannel socketGuildChannel)) diff --git a/PoGo.DiscordBot/Services/UserService.cs b/PoGo.DiscordBot/Services/UserService.cs index c16458c..6b63aa9 100644 --- a/PoGo.DiscordBot/Services/UserService.cs +++ b/PoGo.DiscordBot/Services/UserService.cs @@ -27,17 +27,13 @@ public UserService(ILogger logger, TeamService teamService) var name = user.Nickname ?? user.Username; var result = Regex.Match(name, @"\(\d+\)"); var stringLevel = result.Captures.LastOrDefault()?.Value; - if (stringLevel != null - && int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out int level) - && level >= 1 && level <= 40) - { + if (stringLevel != null && + int.TryParse(stringLevel.Substring(1, stringLevel.Length - 2), out var level) && + level >= 1 && level <= 40) return level; - } - return null; } - public PokemonTeam? GetTeam(SocketGuildUser user) { var teamRoles = teamService.GuildTeamRoles[user.Guild.Id].RoleTeams; @@ -56,12 +52,10 @@ public UserService(ILogger logger, TeamService teamService) Level = GetPlayerLevel(user), }; - public IEnumerable GetPlayers(IEnumerable users) => users .Where(t => !t.IsBot) .Select(GetPlayer); - public async Task CheckTeam(SocketGuildUser user) { var team = GetTeam(user); diff --git a/PoGo.DiscordBot/TextFile1.txt b/PoGo.DiscordBot/TextFile1.txt new file mode 100644 index 0000000..5f28270 --- /dev/null +++ b/PoGo.DiscordBot/TextFile1.txt @@ -0,0 +1 @@ + \ No newline at end of file