diff --git a/src/FlawBOT.Core/Common/HelpFormatter.cs b/src/FlawBOT.Core/Common/HelpFormatter.cs index c2ea0491..bbcbac95 100644 --- a/src/FlawBOT.Core/Common/HelpFormatter.cs +++ b/src/FlawBOT.Core/Common/HelpFormatter.cs @@ -1,46 +1,46 @@ -using DSharpPlus; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Converters; using DSharpPlus.CommandsNext.Entities; using DSharpPlus.Entities; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace FlawBOT.Common { public sealed class HelpFormatter : BaseHelpFormatter { - private string name; - private string description; - private readonly DiscordEmbedBuilder output; + private readonly DiscordEmbedBuilder _output; + private string _description; + private string _name; public HelpFormatter(CommandContext ctx) : base(ctx) { - output = new DiscordEmbedBuilder() + _output = new DiscordEmbedBuilder() .WithColor(DiscordColor.Turquoise) .WithUrl(SharedData.GitHubLink + "wiki"); } public override CommandHelpMessage Build() { - string desc = $"Listing all commands and groups. Use {Formatter.InlineCode(".help ")} for more details."; - if (!string.IsNullOrWhiteSpace(name)) + var desc = $"Listing all commands and groups. Use {Formatter.InlineCode(".help ")} for more details."; + if (!string.IsNullOrWhiteSpace(_name)) { - output.WithTitle(name); - desc = description ?? "No description provided."; + _output.WithTitle(_name); + desc = _description ?? "No description provided."; } - output.WithDescription(desc); - return new CommandHelpMessage(embed: output); + + _output.WithDescription(desc); + return new CommandHelpMessage(embed: _output); } public override BaseHelpFormatter WithCommand(Command cmd) { - name = ((cmd is CommandGroup) ? "Group: " : "Command: ") + cmd.QualifiedName; - description = cmd.Description; + _name = (cmd is CommandGroup ? "Group: " : "Command: ") + cmd.QualifiedName; + _description = cmd.Description; if (cmd.Overloads?.Any() ?? false) - { foreach (var overload in cmd.Overloads.OrderByDescending(o => o.Priority)) { var args = new StringBuilder(); @@ -51,24 +51,29 @@ public override BaseHelpFormatter WithCommand(Command cmd) args.Append(arg.Description ?? "No description provided."); if (arg.IsOptional) { - args.Append(" (def: ").Append(Formatter.InlineCode(arg.DefaultValue is null ? "None" : arg.DefaultValue.ToString())).Append(")"); + args.Append(" (def: ") + .Append(Formatter.InlineCode(arg.DefaultValue is null + ? "None" + : arg.DefaultValue.ToString())).Append(")"); args.Append(" (optional)"); } + args.AppendLine(); } - output.AddField($"{(cmd.Overloads.Count > 1 ? $"Overload #{overload.Priority}" : "Arguments")}", args.ToString() ?? "No arguments."); + + _output.AddField($"{(cmd.Overloads.Count > 1 ? $"Overload #{overload.Priority}" : "Arguments")}", args.ToString() ?? "No arguments."); } - } if (cmd.Aliases?.Any() ?? false) - output.AddField("Aliases", string.Join(", ", cmd.Aliases.Select(a => Formatter.InlineCode(a))), inline: true); + _output.AddField("Aliases", string.Join(", ", cmd.Aliases.Select(Formatter.InlineCode)), true); return this; } public override BaseHelpFormatter WithSubcommands(IEnumerable subcommands) { - if (subcommands.Any()) - output.AddField((name is null) ? "Commands" : "Subcommands", string.Join(", ", subcommands.Select(c => Formatter.InlineCode(c.Name)))); + var enumerable = subcommands.ToList(); + if (enumerable.Any()) + _output.AddField(_name is null ? "Commands" : "Subcommands", string.Join(", ", enumerable.Select(c => Formatter.InlineCode(c.Name)))); return this; } } diff --git a/src/FlawBOT.Core/Common/SharedData.cs b/src/FlawBOT.Core/Common/SharedData.cs index 77591b83..db0aece8 100644 --- a/src/FlawBOT.Core/Common/SharedData.cs +++ b/src/FlawBOT.Core/Common/SharedData.cs @@ -7,7 +7,7 @@ namespace FlawBOT.Common public class SharedData { public static string Name { get; } = "FlawBOT"; - public static string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + public static string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version?.ToString(); public static string GitHubLink { get; set; } = "https://github.com/CriticalFlaw/FlawBOT/"; public static string InviteLink { get; } = "https://discordapp.com/oauth2/authorize?client_id=339833029013012483&scope=bot&permissions=66186303"; public static DiscordColor DefaultColor { get; set; } = new DiscordColor("#00FF7F"); diff --git a/src/FlawBOT.Core/FlawBOT.Core.csproj b/src/FlawBOT.Core/FlawBOT.Core.csproj index c3b4d67b..0e93eb3d 100644 --- a/src/FlawBOT.Core/FlawBOT.Core.csproj +++ b/src/FlawBOT.Core/FlawBOT.Core.csproj @@ -5,12 +5,12 @@ netcoreapp3.1 icon.ico FlawBOT.Program - true - 2.6.0 + false + 2.6.1 7.2 - 2.6.0.0 - 2.6.0.0 + 2.6.1.0 + 2.6.1.0 FlawBOT.Core FlawBOT.Core @@ -40,9 +40,9 @@ - - - + + + diff --git a/src/FlawBOT.Core/Modules/Games/PokemonModule.cs b/src/FlawBOT.Core/Modules/Games/PokemonModule.cs index 64b7023b..a868ed1a 100644 --- a/src/FlawBOT.Core/Modules/Games/PokemonModule.cs +++ b/src/FlawBOT.Core/Modules/Games/PokemonModule.cs @@ -1,12 +1,12 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -23,20 +23,22 @@ public async Task Pokemon(CommandContext ctx, { var results = await PokemonService.GetPokemonCardsAsync(query).ConfigureAwait(false); if (results.Cards.Count == 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { foreach (var dex in results.Cards) { - var card = PokemonService.GetExactPokemon(dex.ID); + var card = PokemonService.GetExactPokemon(dex.Id); var output = new DiscordEmbedBuilder() .WithTitle(card.Name + $" (#{card.NationalPokedexNumber})") .AddField("Series", card.Series ?? "Unknown", true) .AddField("Rarity", card.Rarity ?? "Unknown", true) .AddField("HP", card.Hp ?? "Unknown", true) - .AddField("Ability", (card.Ability != null) ? card.Ability.Name : "Unknown", true) + .AddField("Ability", card.Ability != null ? card.Ability.Name : "Unknown", true) .WithImageUrl(card.ImageUrlHiRes ?? card.ImageUrl) - .WithFooter(!card.Equals(results.Cards.Last()) ? "Type 'next' within 10 seconds for the next Pokémon" : "This is the last found Pokémon on the list.") + .WithFooter(!string.Equals(card.Id, results.Cards.Last().Id) + ? "Type 'next' within 10 seconds for the next Pokémon" + : "This is the last found Pokémon on the list.") .WithColor(DiscordColor.Gold); var types = new StringBuilder(); @@ -53,10 +55,9 @@ public async Task Pokemon(CommandContext ctx, if (results.Cards.Count == 1) continue; var interactivity = await BotServices.GetUserInteractivity(ctx, "next", 10).ConfigureAwait(false); if (interactivity.Result is null) break; - if (!card.Equals(results.Cards.Last())) + if (!string.Equals(card.Id, results.Cards.Last().Id)) await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false); } - } } #endregion COMMAND_POKEMON diff --git a/src/FlawBOT.Core/Modules/Games/SpeedrunModule.cs b/src/FlawBOT.Core/Modules/Games/SpeedrunModule.cs index e9413acc..3f1b5730 100644 --- a/src/FlawBOT.Core/Modules/Games/SpeedrunModule.cs +++ b/src/FlawBOT.Core/Modules/Games/SpeedrunModule.cs @@ -1,12 +1,12 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -24,9 +24,9 @@ public async Task Speedrun(CommandContext ctx, if (!BotServices.CheckUserInput(query)) return; var results = SpeedrunService.GetSpeedrunGameAsync(query).Result.Data; if (results is null || results.Count == 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { foreach (var game in results) { var output = new DiscordEmbedBuilder() @@ -35,19 +35,17 @@ public async Task Speedrun(CommandContext ctx, .AddField("Developers", SpeedrunService.GetSpeedrunExtraAsync(game.Developers, SpeedrunExtras.Developers).Result ?? "Unknown", true) .AddField("Publishers", SpeedrunService.GetSpeedrunExtraAsync(game.Publishers, SpeedrunExtras.Publishers).Result ?? "Unknown", true) .AddField("Platforms", SpeedrunService.GetSpeedrunExtraAsync(game.Platforms, SpeedrunExtras.Platforms).Result ?? "Unknown") - .WithFooter($"ID: {game.ID} - Abbreviation: {game.Abbreviation}") - .WithThumbnailUrl(game.Assets.CoverLarge.URL ?? game.Assets.Icon.URL) + .WithFooter($"ID: {game.Id} - Abbreviation: {game.Abbreviation}") + .WithThumbnail(game.Assets.CoverLarge.Url ?? game.Assets.Icon.Url) .WithUrl(game.WebLink) .WithColor(new DiscordColor("#0F7A4D")); - var link = game.Links.Where(x => x.REL == "categories").First().URL; + var link = game.Links.First(x => x.Rel == "categories").Url; var categories = SpeedrunService.GetSpeedrunCategoryAsync(link).Result.Data; var category = new StringBuilder(); if (categories != null || categories.Count > 0) - { foreach (var x in categories) category.Append($"[{x.Name}]({x.Weblink}) **|** "); - } output.AddField("Categories", category.ToString() ?? "Unknown", true); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); @@ -58,7 +56,6 @@ public async Task Speedrun(CommandContext ctx, if (!game.Equals(results.Last())) await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false); } - } } #endregion COMMAND_SPEEDRUN diff --git a/src/FlawBOT.Core/Modules/Games/SteamModule.cs b/src/FlawBOT.Core/Modules/Games/SteamModule.cs index d1e244c1..7157d0c4 100644 --- a/src/FlawBOT.Core/Modules/Games/SteamModule.cs +++ b/src/FlawBOT.Core/Modules/Games/SteamModule.cs @@ -1,15 +1,15 @@ -using DSharpPlus.CommandsNext; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; using Steam.Models.SteamCommunity; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using UserStatus = Steam.Models.SteamCommunity.UserStatus; namespace FlawBOT.Modules @@ -30,21 +30,28 @@ public async Task SteamGame(CommandContext ctx, { var app = SteamService.GetSteamAppAsync(query).Result; if (app is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() - .WithTitle(app.Name) - .WithDescription((Regex.Replace(app.DetailedDescription.Length <= 500 ? app.DetailedDescription : app.DetailedDescription.Substring(0, 250) + "...", "<[^>]*>", "")) ?? "Unknown") - .AddField("Release Date", app.ReleaseDate.Date ?? "Unknown", true) - .AddField("Developers", app.Developers[0] ?? "Unknown", true) - .AddField("Publisher", app.Publishers[0] ?? "Unknown", true) - .AddField("Price", app.IsFree ? "Free" : (app.PriceOverview.FinalFormatted ?? "Unknown"), true) - .AddField("Metacritic", (app.Metacritic != null) ? app.Metacritic.Score.ToString() : "Unknown", true) - .WithThumbnailUrl(app.HeaderImage) - .WithUrl("http://store.steampowered.com/app/" + app.SteamAppId.ToString()) - .WithFooter("App ID: " + app.SteamAppId.ToString()) - .WithColor(new DiscordColor("#1B2838")); + .WithTitle(app.Name) + .WithDescription( + Regex.Replace( + app.DetailedDescription.Length <= 500 + ? app.DetailedDescription + : app.DetailedDescription.Substring(0, 250) + "...", "<[^>]*>", "") ?? "Unknown") + .AddField("Release Date", app.ReleaseDate.Date ?? "Unknown", true) + .AddField("Developers", app.Developers[0] ?? "Unknown", true) + .AddField("Publisher", app.Publishers[0] ?? "Unknown", true) + .AddField("Price", app.IsFree ? "Free" : app.PriceOverview.FinalFormatted ?? "Unknown", true) + .AddField("Metacritic", app.Metacritic != null ? app.Metacritic.Score.ToString() : "Unknown", true) + .WithThumbnail(app.HeaderImage) + .WithUrl("http://store.steampowered.com/app/" + app.SteamAppId) + .WithFooter("App ID: " + app.SteamAppId) + .WithColor(new DiscordColor("#1B2838")); var genres = new StringBuilder(); foreach (var genre in app.Genres.Take(3)) @@ -74,18 +81,24 @@ public async Task SteamUser(CommandContext ctx, var profile = SteamService.GetSteamProfileAsync(query).Result; var summary = SteamService.GetSteamSummaryAsync(query).Result; if (profile is null && summary is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { if (summary.Data.ProfileVisibility != ProfileVisibility.Public) - await BotServices.SendEmbedAsync(ctx, "This profile is private...", EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, "This profile is private...", EmbedType.Warning) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() .WithTitle(summary.Data.Nickname) - .WithDescription(Regex.Replace(profile.Summary, "<[^>]*>", "") ?? string.Empty) + .WithDescription(Regex.Replace(profile?.Summary ?? string.Empty, "<[^>]*>", "") ?? string.Empty) .AddField("Member since", summary.Data.AccountCreatedDate.ToUniversalTime().ToString(CultureInfo.CurrentCulture), true) - .WithThumbnailUrl(profile.AvatarFull.ToString() ?? profile.Avatar.ToString()) + .WithThumbnail(profile?.AvatarFull.ToString() ?? profile.Avatar.ToString()) .WithColor(new DiscordColor("#1B2838")) .WithUrl("http://steamcommunity.com/profiles/" + profile.SteamID) .WithFooter("Steam ID: " + profile.SteamID); @@ -104,6 +117,7 @@ public async Task SteamUser(CommandContext ctx, output.AddField("Game Server IP", profile.InGameServerIP, true); output.WithImageUrl(profile.InGameInfo.GameLogoSmall); } + await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } } @@ -115,15 +129,17 @@ public async Task SteamUser(CommandContext ctx, [Command("connect")] [Aliases("link")] - [Description("Format a game connection string into a clickable link")] + [Description("Format a game connection string into a link")] public async Task SteamServerLink(CommandContext ctx, [Description("Connection string")] [RemainingText] string link) { var regex = new Regex(@"\s*(?'ip'\S+)\s*", RegexOptions.Compiled).Match(link); if (regex.Success) - await ctx.RespondAsync(string.Format($"steam://connect/{regex.Groups["ip"].Value}/{regex.Groups["pw"].Value}")).ConfigureAwait(false); + await ctx.RespondAsync(string.Format($"steam://connect/{regex.Groups["ip"].Value}/{regex.Groups["pw"].Value}")) + .ConfigureAwait(false); else - await BotServices.SendEmbedAsync(ctx, Resources.ERR_STEAM_CONNECT_FORMAT, EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.ERR_STEAM_CONNECT_FORMAT, EmbedType.Warning) + .ConfigureAwait(false); } #endregion COMMAND_CONNECT diff --git a/src/FlawBOT.Core/Modules/Games/TeamFortressModule.cs b/src/FlawBOT.Core/Modules/Games/TeamFortressModule.cs index 9fa535d8..163ca7aa 100644 --- a/src/FlawBOT.Core/Modules/Games/TeamFortressModule.cs +++ b/src/FlawBOT.Core/Modules/Games/TeamFortressModule.cs @@ -1,16 +1,17 @@ -using DSharpPlus.CommandsNext; -using DSharpPlus.CommandsNext.Attributes; -using DSharpPlus.Entities; -using FlawBOT.Core.Properties; -using FlawBOT.Framework.Models; -using FlawBOT.Framework.Services; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.CommandsNext.Attributes; +using DSharpPlus.Entities; +using FlawBOT.Core.Properties; +using FlawBOT.Framework.Models; +using FlawBOT.Framework.Services; +using TeamworkTF.Sharp; namespace FlawBOT.Modules { @@ -24,12 +25,15 @@ public class TeamFortressModule : BaseCommandModule [Command("item")] [Aliases("schema", "hat")] [Description("Retrieve an item from the latest TF2 item schema")] - public async Task TF2Item(CommandContext ctx, + public async Task Tf2Item(CommandContext ctx, [Description("Item to find in the TF2 schema")] [RemainingText] string query = "The Scattergun") { var item = TeamFortressService.GetSchemaItem(query); if (item is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { var textInfo = new CultureInfo("en-US", false).TextInfo; @@ -47,8 +51,8 @@ public async Task TF2Item(CommandContext ctx, output.AddField("Used by:", classes.ToString() ?? "Unknown", true); output.AddField("Item Slot:", textInfo.ToTitleCase(item.ItemSlot) ?? "Unknown", true); output.AddField("Item Type:", item.ItemTypeName ?? "Unknown", true); - output.AddField("Giftable:", (item.Capabilities.CanGiftWrap == true) ? "Yes" : "No", true); - output.AddField("Nameable:", (item.Capabilities.Nameable) ? "Yes" : "No", true); + output.AddField("Giftable:", item.Capabilities.CanGiftWrap == true ? "Yes" : "No", true); + output.AddField("Nameable:", item.Capabilities.Nameable ? "Yes" : "No", true); output.AddField("Restriction:", item.HolidayRestriction ?? "None", true); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } @@ -61,21 +65,24 @@ public async Task TF2Item(CommandContext ctx, [Command("map")] [Aliases("maps")] [Description("Retrieve map information from teamwork.tf")] - public async Task TF2Map(CommandContext ctx, + public async Task Tf2Map(CommandContext ctx, [Description("Normalized map name, like pl_upward")] string query) { if (!BotServices.CheckUserInput(query)) return; var results = await TeamFortressService.GetMapStatsAsync(query.ToLowerInvariant()).ConfigureAwait(false); if (results is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { - double.TryParse(results.AllTimeAvgPlayers, out var avg_players); + double.TryParse(results.AllTimeAvgPlayers, out var avgPlayers); var output = new DiscordEmbedBuilder() .WithTitle(results.MapName) .AddField("Highest Server Count", results.HighestServers.ToString() ?? "Unknown", true) .AddField("Highest Player Count", results.HighestPlayers.ToString() ?? "Unknown", true) - .AddField("Avg. Players", Math.Round(avg_players, 2).ToString() ?? "Unknown", true) + .AddField("Avg. Players", Math.Round(avgPlayers, 2).ToString(CultureInfo.InvariantCulture) ?? "Unknown", true) .WithFooter("Statistics retrieved from teamwork.tf - refreshed every 5 minutes") .WithImageUrl(results.Thumbnail) .WithUrl("https://wiki.teamfortress.com/wiki/" + results.MapName) @@ -107,6 +114,7 @@ public async Task TF2Map(CommandContext ctx, output.WithDescription(desc.Title + " - " + desc.Description); output.WithColor(new DiscordColor($"#{desc.Color}")); } + await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } } @@ -117,18 +125,22 @@ public async Task TF2Map(CommandContext ctx, [Command("news")] [Description("Retrieve the latest news article from teamwork.tf")] - public async Task TF2News(CommandContext ctx, - [Description("Page number from which to retrieve the news")] [RemainingText] int query = 0) + public async Task Tf2News(CommandContext ctx, + [Description("Page number from which to retrieve the news")] int query = 0) { - var results = await TeamFortressService.GetNewsOverviewAsync(page: query).ConfigureAwait(false); + var results = await TeamFortressService.GetNewsOverviewAsync(query).ConfigureAwait(false); if (results is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder().WithColor(new DiscordColor("#E7B53B")); foreach (var result in results.Take(5)) output.AddField(result.CreatedAt.Date.ToString(), $"{result.Type}: [{result.Title}]({result.Link.AbsoluteUri})"); - await ctx.RespondAsync("Latest news articles from teamwork.tf", embed: output.Build()).ConfigureAwait(false); + await ctx.RespondAsync("Latest news articles from teamwork.tf", embed: output.Build()) + .ConfigureAwait(false); } } @@ -139,26 +151,28 @@ public async Task TF2News(CommandContext ctx, [Command("creator")] [Aliases("creators", "youtuber")] [Description("Retrieve a community creator profile from teamwork.tf")] - public async Task TF2Creators(CommandContext ctx, + public async Task Tf2Creators(CommandContext ctx, [Description("Name of the community creator to find")] [RemainingText] string query) { if (!BotServices.CheckUserInput(query)) return; - var steamID = SteamService.GetSteamUserID(query).Result.Data; - var results = await TeamFortressService.GetCreatorByIDAsync(steamID).ConfigureAwait(false); + var steamId = SteamService.GetSteamUserId(query).Result.Data; + var results = await TeamFortressService.GetCreatorByIdAsync(steamId).ConfigureAwait(false); if (results is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { foreach (var creator in results) { var user = results.FirstOrDefault(); var output = new DiscordEmbedBuilder() - .WithTitle(user.Name) - .WithDescription("Main Class: " + user.Main.ToString().ToUpper()) - .WithThumbnailUrl(user.ThumbnailUrl) - .WithUrl(user.Link) + .WithTitle(user?.Name) + .WithDescription("Main Class: " + user?.Main.ToString()?.ToUpper()) + .WithThumbnail(user?.ThumbnailUrl) + .WithUrl(user?.Link) .WithColor(new DiscordColor("#E7B53B")) - .WithFooter(!creator.Equals(results.Last()) ? "Type 'next' within 10 seconds for the next creator" : "Data retrieved from teamwork.tf"); + .WithFooter(!creator.Equals(results.Last()) + ? "Type 'next' within 10 seconds for the next creator" + : "Data retrieved from teamwork.tf"); var links = new StringBuilder(); if (creator.DiscordGroup != null) @@ -183,7 +197,6 @@ public async Task TF2Creators(CommandContext ctx, if (!creator.Equals(results.Last())) await BotServices.RemoveMessage(message).ConfigureAwait(false); } - } } #endregion COMMAND_CREATORS @@ -193,13 +206,15 @@ public async Task TF2Creators(CommandContext ctx, [Command("server")] [Aliases("servers")] [Description("Retrieve a list of servers with given game-mode")] - public async Task TF2ServerByMode(CommandContext ctx, + public async Task Tf2ServerByMode(CommandContext ctx, [Description("Name of the game-mode, like payload")] [RemainingText] string query) { if (!BotServices.CheckUserInput(query)) return; - var results = await TeamFortressService.GetGameModeServerAsync(query.Trim().Replace(' ', '-')).ConfigureAwait(false); + var results = await TeamFortressService.GetGameModeServerAsync(query.Trim().Replace(' ', '-')) + .ConfigureAwait(false); if (results is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else await OutputServerInfo(ctx, results.OrderBy(_ => new Random().Next()).ToList()).ConfigureAwait(false); } @@ -207,7 +222,7 @@ public async Task TF2ServerByMode(CommandContext ctx, [Command("ip")] [Aliases("find")] [Description("Retrieve a game server with given ip address")] - public async Task TF2ServerByIP(CommandContext ctx, + public async Task Tf2ServerByIp(CommandContext ctx, [Description("Game server IP address, like 164.132.233.16")] string ip, [Description("Game server port, like 27022")] int port = 0) { @@ -216,21 +231,22 @@ public async Task TF2ServerByIP(CommandContext ctx, if (!regex.Success) return; var results = await TeamFortressService.GetGameServerInfoAsync(ip, port).ConfigureAwait(false); if (results is null || results.Count <= 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else await OutputServerInfo(ctx, results.OrderBy(_ => new Random().Next()).ToList()).ConfigureAwait(false); } - public async Task OutputServerInfo(CommandContext ctx, List results) + public async Task OutputServerInfo(CommandContext ctx, List results) { foreach (var server in results) { var output = new DiscordEmbedBuilder() .WithTitle(server.Name) .WithDescription("steam://connect/" + server.Ip + ":" + server.Port) - .AddField("Provider", (server.Provider != null) ? server.Provider.Name : "Unknown", true) + .AddField("Provider", server.Provider != null ? server.Provider.Name : "Unknown", true) .AddField("Player Count", (server.Players.ToString() ?? "Unknown") + "/" + (server.MaxPlayers.ToString() ?? "Unknown"), true) - .AddField("Password Lock", (server.HasPassword) ? "Yes" : "No", true) + .AddField("Password Lock", server.HasPassword ? "Yes" : "No", true) .AddField("Random Crits", server.HasRandomCrits == true ? "Yes" : "No", true) .AddField("Instant Respawn", server.HasNoRespawnTime ? "Yes" : "No", true) .AddField("All Talk", server.HasAllTalk ? "Yes" : "No", true) @@ -256,7 +272,7 @@ public async Task OutputServerInfo(CommandContext ctx, List new Random().Next()).ToList(); @@ -264,7 +280,11 @@ public async Task TF2ServerList(CommandContext ctx) { var output = new DiscordEmbedBuilder() .WithTitle(server.Name) - .WithDescription((Regex.Replace(server.DescriptionLarge.Length <= 500 ? server.DescriptionLarge : server.DescriptionLarge.Substring(0, 250) + "...", "<[^>]*>", "")) ?? "Unknown") + .WithDescription( + Regex.Replace( + server.DescriptionLarge.Length <= 500 + ? server.DescriptionLarge + : server.DescriptionLarge.Substring(0, 250) + "...", "<[^>]*>", "") ?? "Unknown") .AddField("Created by", server.Creator.Name ?? "Unknown", true) .AddField("Subscribers", server.Subscribed.ToString() ?? "Unknown", true) .WithUrl(Resources.URL_TEAMWORK_SERVERS + server.Id) diff --git a/src/FlawBOT.Core/Modules/Misc/MathModule.cs b/src/FlawBOT.Core/Modules/Misc/MathModule.cs index 5bf09556..fed1b726 100644 --- a/src/FlawBOT.Core/Modules/Misc/MathModule.cs +++ b/src/FlawBOT.Core/Modules/Misc/MathModule.cs @@ -1,11 +1,11 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -24,10 +24,10 @@ public async Task Math(CommandContext ctx, { try { - double result = 0; + double result; switch (operation) { - default: //case "+": + default: //case "+": result = num1 + num2; break; @@ -56,7 +56,8 @@ public async Task Math(CommandContext ctx, } catch { - await BotServices.SendEmbedAsync(ctx, Resources.ERR_MATH_EQUATION, EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.ERR_MATH_EQUATION, EmbedType.Warning) + .ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Misc/MiscModule.cs b/src/FlawBOT.Core/Modules/Misc/MiscModule.cs index 6a550890..2351cf59 100644 --- a/src/FlawBOT.Core/Modules/Misc/MiscModule.cs +++ b/src/FlawBOT.Core/Modules/Misc/MiscModule.cs @@ -1,4 +1,8 @@ -using DSharpPlus; +using System; +using System.Net; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; @@ -7,10 +11,6 @@ using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; using Newtonsoft.Json.Linq; -using System; -using System.Net; -using System.Text.RegularExpressions; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -59,7 +59,8 @@ public async Task CatPic(CommandContext ctx) { var results = CatService.GetCatPhotoAsync().Result; if (string.IsNullOrWhiteSpace(results)) - await BotServices.SendEmbedAsync(ctx, "Connection to random.cat failed!", EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Connection to random.cat failed!", EmbedType.Warning) + .ConfigureAwait(false); var output = new DiscordEmbedBuilder() .WithImageUrl(results) .WithColor(DiscordColor.Orange); @@ -94,7 +95,10 @@ public async Task GetColor(CommandContext ctx, { var regex = new Regex(@"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$", RegexOptions.Compiled).Match(color.ToString()); if (!regex.Success) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_COLOR_INVALID, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_COLOR_INVALID, EmbedType.Warning) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() @@ -133,7 +137,9 @@ public async Task DogPic(CommandContext ctx) { var results = DogService.GetDogPhotoAsync().Result; if (results.Status != "success") + { await BotServices.SendEmbedAsync(ctx, Resources.ERR_DOG_PHOTO, EmbedType.Warning).ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() @@ -154,9 +160,9 @@ public async Task Greet(CommandContext ctx, [Description("User to say hello to")] [RemainingText] DiscordMember member) { if (member is null) - await ctx.RespondAsync($":wave: Hello, " + ctx.User.Mention).ConfigureAwait(false); + await ctx.RespondAsync(":wave: Hello, " + ctx.User.Mention).ConfigureAwait(false); else - await ctx.RespondAsync($":wave: Welcome " + member.Mention + " to " + ctx.Guild.Name + ". Enjoy your stay!").ConfigureAwait(false); + await ctx.RespondAsync(":wave: Welcome " + member.Mention + " to " + ctx.Guild.Name + ". Enjoy your stay!").ConfigureAwait(false); } #endregion COMMAND_HELLO @@ -166,18 +172,21 @@ public async Task Greet(CommandContext ctx, [Command("ip")] [Aliases("ipstack", "track")] [Description("Retrieve IP address geolocation information")] - public async Task IPLocation(CommandContext ctx, + public async Task IpLocation(CommandContext ctx, [Description("IP Address")] string address) { - if (string.IsNullOrWhiteSpace(address) || !IPAddress.TryParse(address, out IPAddress ip)) return; - var results = GoogleService.GetIPLocationAsync(ip).Result; + if (string.IsNullOrWhiteSpace(address) || !IPAddress.TryParse(address, out var ip)) return; + var results = GoogleService.GetIpLocationAsync(ip).Result; if (results.Status != "success") - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Warning) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() .AddField("Location", $"{results.City}, {results.Region}, {results.Country}") - .AddField("ISP", results.ISP) + .AddField("ISP", results.Isp) .AddField("Coordinates", $"{results.Latitude}°N, {results.Longitude}°W") .WithFooter($"IP: {results.Query}") .WithColor(new DiscordColor("#4d2f63")); diff --git a/src/FlawBOT.Core/Modules/Misc/PollModule.cs b/src/FlawBOT.Core/Modules/Misc/PollModule.cs index 2a576a99..797b792b 100644 --- a/src/FlawBOT.Core/Modules/Misc/PollModule.cs +++ b/src/FlawBOT.Core/Modules/Misc/PollModule.cs @@ -1,14 +1,14 @@ -using DSharpPlus.CommandsNext; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using DSharpPlus.Interactivity; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -23,20 +23,26 @@ public async Task Poll(CommandContext ctx, [Description("Question to be polled")] [RemainingText] string question) { if (!BotServices.CheckUserInput(question)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_POLL_QUESTION, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_POLL_QUESTION, EmbedType.Warning) + .ConfigureAwait(false); + } else { var interactivity = ctx.Client.GetInteractivity(); - var pollOptions = new List(); - pollOptions.Add(DiscordEmoji.FromName(ctx.Client, ":thumbsup:")); - pollOptions.Add(DiscordEmoji.FromName(ctx.Client, ":thumbsdown:")); + var pollOptions = new List + { + DiscordEmoji.FromName(ctx.Client, ":thumbsup:"), + DiscordEmoji.FromName(ctx.Client, ":thumbsdown:") + }; var duration = new TimeSpan(0, 0, 3, 0, 0); var output = new DiscordEmbedBuilder().WithDescription(ctx.User.Mention + "asked: " + question + "\nThis poll ends in 3 minutes."); var message = await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); foreach (var react in pollOptions) await message.CreateReactionAsync(react).ConfigureAwait(false); var pollResult = await interactivity.CollectReactionsAsync(message, duration).ConfigureAwait(false); - var results = pollResult.Where(x => pollOptions.Contains(x.Emoji)).Select(x => $"{x.Emoji} wins the poll with **{x.Total}** votes"); + var results = pollResult.Where(x => pollOptions.Contains(x.Emoji)) + .Select(x => $"{x.Emoji} wins the poll with **{x.Total}** votes"); await ctx.RespondAsync(string.Join("\n", results)).ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Search/AmiiboModule.cs b/src/FlawBOT.Core/Modules/Search/AmiiboModule.cs index ef48c073..a86a6507 100644 --- a/src/FlawBOT.Core/Modules/Search/AmiiboModule.cs +++ b/src/FlawBOT.Core/Modules/Search/AmiiboModule.cs @@ -1,11 +1,11 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -23,9 +23,9 @@ public async Task GetAmiibo(CommandContext ctx, if (!BotServices.CheckUserInput(query)) return; var results = await AmiiboService.GetAmiiboDataAsync(query).ConfigureAwait(false); if (results is null) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { foreach (var amiibo in results.Amiibo) { var output = new DiscordEmbedBuilder() @@ -37,7 +37,9 @@ public async Task GetAmiibo(CommandContext ctx, .AddField(":flag_eu: Release:", amiibo.ReleaseDate.European, true) .AddField(":flag_au: Release:", amiibo.ReleaseDate.Australian, true) .WithImageUrl(amiibo.Image) - .WithFooter(!amiibo.Equals(results.Amiibo.Last()) ? "Type 'next' within 10 seconds for the next amiibo" : "This is the last found amiibo on the list.") + .WithFooter(!amiibo.Equals(results.Amiibo.Last()) + ? "Type 'next' within 10 seconds for the next amiibo" + : "This is the last found amiibo on the list.") .WithColor(new DiscordColor("#E70009")); var message = await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); @@ -48,7 +50,6 @@ public async Task GetAmiibo(CommandContext ctx, if (!amiibo.Equals(results.Amiibo.Last())) await BotServices.RemoveMessage(message).ConfigureAwait(false); } - } } #endregion COMMAND_AMIIBO diff --git a/src/FlawBOT.Core/Modules/Search/DictionaryModule.cs b/src/FlawBOT.Core/Modules/Search/DictionaryModule.cs index 0005b63e..50d28f40 100644 --- a/src/FlawBOT.Core/Modules/Search/DictionaryModule.cs +++ b/src/FlawBOT.Core/Modules/Search/DictionaryModule.cs @@ -1,12 +1,12 @@ -using DSharpPlus; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -24,20 +24,26 @@ public async Task UrbanDictionary(CommandContext ctx, if (!BotServices.CheckUserInput(query)) return; var results = await DictionaryService.GetDictionaryDefinitionAsync(query).ConfigureAwait(false); if (results.ResultType == "no_results" || results.List.Count == 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { foreach (var definition in results.List) { var output = new DiscordEmbedBuilder() .WithTitle("Urban Dictionary definition for " + Formatter.Bold(query)) - .WithDescription(!string.IsNullOrWhiteSpace(definition.Author) ? "Submitted by: " + definition.Author : string.Empty) - .AddField("Definition", definition.Definition.Length < 500 ? definition.Definition : definition.Definition.Take(500) + "...") + .WithDescription(!string.IsNullOrWhiteSpace(definition.Author) + ? "Submitted by: " + definition.Author + : string.Empty) + .AddField("Definition", definition.Definition.Length < 500 + ? definition.Definition + : definition.Definition.Take(500) + "...") .AddField("Example", definition.Example ?? "None") .AddField(":thumbsup:", definition.ThumbsUp.ToString(), true) .AddField(":thumbsdown:", definition.ThumbsDown.ToString(), true) .WithUrl(definition.Permalink) - .WithFooter(!definition.Equals(results.List.Last()) ? "Type 'next' within 10 seconds for the next definition" : "This is the last found definition on the list.") + .WithFooter(!definition.Equals(results.List.Last()) + ? "Type 'next' within 10 seconds for the next definition" + : "This is the last found definition on the list.") .WithColor(new DiscordColor("#1F2439")); var message = await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); @@ -48,7 +54,6 @@ public async Task UrbanDictionary(CommandContext ctx, if (!definition.Equals(results.List.Last())) await BotServices.RemoveMessage(message).ConfigureAwait(false); } - } } #endregion COMMAND_DICTIONARY diff --git a/src/FlawBOT.Core/Modules/Search/GoogleModule.cs b/src/FlawBOT.Core/Modules/Search/GoogleModule.cs index ea08a305..d2099998 100644 --- a/src/FlawBOT.Core/Modules/Search/GoogleModule.cs +++ b/src/FlawBOT.Core/Modules/Search/GoogleModule.cs @@ -1,4 +1,8 @@ -using DSharpPlus; +using System; +using System.Globalization; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; @@ -6,9 +10,6 @@ using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -25,13 +26,16 @@ public async Task GetTime(CommandContext ctx, { if (!BotServices.CheckUserInput(location)) return; var results = GoogleService.GetTimeDataAsync(location).Result; - if (results == null || results.status != "OK") - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + if (results == null || results.Status != "OK") + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() .WithTitle(":clock1: Current time in " + results.Results[0].FormattedAddress) - .WithDescription(Formatter.Bold(results.Time.ToShortTimeString()) + " " + results.Timezone.timeZoneName) + .WithDescription(Formatter.Bold(results.Time.ToShortTimeString()) + " " + results.Timezone.TimeZoneName) .WithColor(SharedData.DefaultColor); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } @@ -48,9 +52,9 @@ public async Task News(CommandContext ctx, { var results = await GoogleService.GetNewsDataAsync(query).ConfigureAwait(false); if (results.Status != "ok") - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); else - { while (results.Articles.Count > 0) { var output = new DiscordEmbedBuilder() @@ -59,10 +63,13 @@ public async Task News(CommandContext ctx, foreach (var result in results.Articles.Take(5)) { - output.AddField(result.PublishDate.ToString(), $"[{result.Title}]({result.Url})"); + output.AddField(result.PublishDate.ToString(CultureInfo.InvariantCulture), $"[{result.Title}]({result.Url})"); results.Articles.Remove(result); } - var message = await ctx.RespondAsync("Latest Google News articles from News API", embed: output.Build()).ConfigureAwait(false); + + var message = await ctx + .RespondAsync("Latest Google News articles from News API", embed: output.Build()) + .ConfigureAwait(false); if (results.Articles.Count == 5) continue; var interactivity = await BotServices.GetUserInteractivity(ctx, "next", 10).ConfigureAwait(false); @@ -70,7 +77,6 @@ public async Task News(CommandContext ctx, await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false); await BotServices.RemoveMessage(message).ConfigureAwait(false); } - } } #endregion COMMAND_NEWS @@ -84,8 +90,11 @@ public async Task Weather(CommandContext ctx, { if (!BotServices.CheckUserInput(query)) return; var results = await GoogleService.GetWeatherDataAsync(query).ConfigureAwait(false); - if (results == null || results.COD == 404) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Missing).ConfigureAwait(false); + if (results == null || results.Cod == 404) + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Missing) + .ConfigureAwait(false); + } else { Func format = GoogleService.CelsiusToFahrenheit; @@ -94,7 +103,7 @@ public async Task Weather(CommandContext ctx, .AddField("Temperature", $"{results.Main.Temperature:F1}°C / {format(results.Main.Temperature):F1}°F", true) .AddField("Humidity", $"{results.Main.Humidity}%", true) .AddField("Wind Speed", $"{results.Wind.Speed}m/s", true) - .WithUrl("https://openweathermap.org/city/" + results.ID) + .WithUrl("https://openweathermap.org/city/" + results.Id) .WithColor(SharedData.DefaultColor); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } diff --git a/src/FlawBOT.Core/Modules/Search/ImgurModule.cs b/src/FlawBOT.Core/Modules/Search/ImgurModule.cs index 7086f48c..37d070ba 100644 --- a/src/FlawBOT.Core/Modules/Search/ImgurModule.cs +++ b/src/FlawBOT.Core/Modules/Search/ImgurModule.cs @@ -1,11 +1,11 @@ -using DSharpPlus.CommandsNext; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; using Imgur.API.Models.Impl; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -16,27 +16,28 @@ public class ImgurModule : BaseCommandModule [Command("imgur")] [Aliases("image")] - [Description("Retrieve an imager from Imgur")] + [Description("Retrieve an image from Imgur")] public async Task Imgur(CommandContext ctx, [Description("Search query to pass to Imgur")] [RemainingText] string query) { var results = ImgurService.GetImgurGalleryAsync(query).Result; switch (results) { - case GalleryImage _: + case GalleryImage image: var output = new DiscordEmbedBuilder() - .WithImageUrl(((GalleryImage)results).Link) - .WithFooter(((GalleryImage)results).Title ?? string.Empty) + .WithImageUrl(image.Link) + .WithFooter(image.Title ?? string.Empty) .WithColor(new DiscordColor("#85BF25")); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); break; - case GalleryAlbum _: - await ctx.RespondAsync(((GalleryAlbum)results).Link).ConfigureAwait(false); + case GalleryAlbum album: + await ctx.RespondAsync(album.Link).ConfigureAwait(false); break; default: - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); break; } } diff --git a/src/FlawBOT.Core/Modules/Search/NASAModule.cs b/src/FlawBOT.Core/Modules/Search/NASAModule.cs index 8290599f..a6f99e89 100644 --- a/src/FlawBOT.Core/Modules/Search/NASAModule.cs +++ b/src/FlawBOT.Core/Modules/Search/NASAModule.cs @@ -1,31 +1,33 @@ -using DSharpPlus.CommandsNext; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Threading.Tasks; namespace FlawBOT.Modules { [Cooldown(3, 5, CooldownBucketType.Channel)] - public class NASAModule : BaseCommandModule + public class NasaModule : BaseCommandModule { #region COMMAND_NASA [Command("nasa")] [Aliases("apod", "space")] [Description("Retrieve NASA's Astronomy Picture of the Day")] - public async Task NASA(CommandContext ctx) + public async Task Nasa(CommandContext ctx) { - var results = await NASAService.GetNASAImageAsync().ConfigureAwait(false); + var results = await NasaService.GetNasaImageAsync().ConfigureAwait(false); if (results is null) + { await BotServices.SendEmbedAsync(ctx, Resources.ERR_NASA_API, EmbedType.Missing).ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() .WithDescription(results.Title) - .WithImageUrl(results.ImageHD ?? results.ImageSD) + .WithImageUrl(results.ImageHd ?? results.ImageSd) .WithFooter(results.Description) .WithColor(new DiscordColor("#0B3D91")); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); diff --git a/src/FlawBOT.Core/Modules/Search/OMDBModule.cs b/src/FlawBOT.Core/Modules/Search/OMDBModule.cs index 6b89f9c0..6a0c9532 100644 --- a/src/FlawBOT.Core/Modules/Search/OMDBModule.cs +++ b/src/FlawBOT.Core/Modules/Search/OMDBModule.cs @@ -1,29 +1,32 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { [Cooldown(3, 5, CooldownBucketType.Channel)] - public class OMDBModule : BaseCommandModule + public class OmdbModule : BaseCommandModule { #region COMMAND_OMDB [Command("omdb")] [Aliases("imdb", "movie")] [Description("Retrieve a movie or TV show from OMDB")] - public async Task OMDB(CommandContext ctx, + public async Task Omdb(CommandContext ctx, [Description("Movie or TV show to find on OMDB")] [RemainingText] string query) { if (!BotServices.CheckUserInput(query)) return; - var results = OMDBService.GetMovieDataAsync(query.Replace(" ", "+")).Result; + var results = OmdbService.GetMovieDataAsync(query.Replace(" ", "+")).Result; if (results.Response == "False") - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() @@ -36,7 +39,7 @@ public async Task OMDB(CommandContext ctx, .AddField("Country", results.Country, true) .AddField("Box Office", results.BoxOffice, true) .AddField("Production", results.Production, true) - .AddField("IMDB Rating", results.IMDbRating, true) + .AddField("IMDb Rating", results.IMDbRating, true) .AddField("Metacritic", results.Metascore, true) .AddField("Directors", results.Director) .AddField("Actors", results.Actors) diff --git a/src/FlawBOT.Core/Modules/Search/RedditModule.cs b/src/FlawBOT.Core/Modules/Search/RedditModule.cs index 60f3075c..9b484565 100644 --- a/src/FlawBOT.Core/Modules/Search/RedditModule.cs +++ b/src/FlawBOT.Core/Modules/Search/RedditModule.cs @@ -1,11 +1,11 @@ -using DSharpPlus.CommandsNext; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -19,27 +19,34 @@ public class RedditModule : BaseCommandModule [Command("hot")] [Description("Get hottest posts for a subreddit.")] public Task HowPost(CommandContext ctx, [Description("Subreddit.")] string query) - => RedditPost(ctx, query, RedditCategory.Hot); + { + return RedditPost(ctx, query, RedditCategory.Hot); + } [Command("new")] [Description("Get newest posts for a subreddit.")] [Aliases("newest", "latest")] public Task NewPost(CommandContext ctx, [Description("Subreddit.")] string query) - => RedditPost(ctx, query, RedditCategory.New); + { + return RedditPost(ctx, query, RedditCategory.New); + } [Command("top")] [Description("Get top posts for a subreddit.")] public Task TopPost(CommandContext ctx, [Description("Subreddit.")] string query) - => RedditPost(ctx, query, RedditCategory.Top); + { + return RedditPost(ctx, query, RedditCategory.Top); + } private async Task RedditPost(CommandContext ctx, string query, RedditCategory category) { if (!BotServices.CheckUserInput(query)) return; var results = RedditService.GetResults(query, category); if (results is null || results.Count == 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing) + .ConfigureAwait(false); - while (results.Count > 0) + while (results != null && results.Count > 0) { var output = new DiscordEmbedBuilder() .WithFooter("Type 'next' within 10 seconds for the next five posts.") @@ -50,7 +57,9 @@ private async Task RedditPost(CommandContext ctx, string query, RedditCategory c output.AddField(result.Authors[0].Name, $"[{(result.Title.Text.Length < 500 ? result.Title.Text : result.Title.Text.Take(500) + "...")}]({result.Links.First().Uri})"); results.Remove(result); } - var message = await ctx.RespondAsync("Search results for r/" + query, embed: output).ConfigureAwait(false); + + var message = await ctx.RespondAsync("Search results for r/" + query, embed: output) + .ConfigureAwait(false); if (results.Count == 5) continue; var interactivity = await BotServices.GetUserInteractivity(ctx, "next", 10).ConfigureAwait(false); diff --git a/src/FlawBOT.Core/Modules/Search/SimpsonsModule.cs b/src/FlawBOT.Core/Modules/Search/SimpsonsModule.cs index 265dc91b..a2f85ec5 100644 --- a/src/FlawBOT.Core/Modules/Search/SimpsonsModule.cs +++ b/src/FlawBOT.Core/Modules/Search/SimpsonsModule.cs @@ -1,9 +1,9 @@ -using DSharpPlus.CommandsNext; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Services; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -17,7 +17,8 @@ public class SimpsonsModule : BaseCommandModule [Description("Retrieve a random Simpsons screenshot and episode")] public async Task Simpsons(CommandContext ctx) { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Frinkiac).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Frinkiac) + .ConfigureAwait(false); await ctx.RespondAsync(embed: results.Build()).ConfigureAwait(false); } @@ -28,15 +29,19 @@ public async Task Simpsons(CommandContext ctx) [Command("simpsonsgif")] [Aliases("doh")] [Description("Retrieve a random Simpsons gif")] - public async Task SimpsonsGIF(CommandContext ctx, + public async Task SimpsonsGif(CommandContext ctx, [Description("Inputting anything will add episode information")] [RemainingText] string input) { - var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.Frinkiac).ConfigureAwait(false); + var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.Frinkiac) + .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(input)) + { await ctx.RespondAsync(output).ConfigureAwait(false); + } else // Include episode information if any kind of parameter is inputted { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Frinkiac).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Frinkiac) + .ConfigureAwait(false); results.WithFooter(Resources.SIMPSONS_GIF_WARNING); await ctx.RespondAsync(output, embed: results.Build()).ConfigureAwait(false); } @@ -51,7 +56,8 @@ public async Task SimpsonsGIF(CommandContext ctx, [Description("Retrieve a random Futurama screenshot and episode")] public async Task Futurama(CommandContext ctx) { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Morbotron).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Morbotron) + .ConfigureAwait(false); results.WithColor(new DiscordColor("#69E398")); await ctx.RespondAsync(embed: results.Build()).ConfigureAwait(false); } @@ -63,15 +69,19 @@ public async Task Futurama(CommandContext ctx) [Command("futuramagif")] [Aliases("neat")] [Description("Retrieve a random Futurama gif")] - public async Task FuturamaGIF(CommandContext ctx, + public async Task FuturamaGif(CommandContext ctx, [Description("Inputting anything will add episode information")] [RemainingText] string input) { - var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.Morbotron).ConfigureAwait(false); + var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.Morbotron) + .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(input)) + { await ctx.RespondAsync(output).ConfigureAwait(false); + } else // Include episode information if any kind of parameter is inputted { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Morbotron).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.Morbotron) + .ConfigureAwait(false); results.WithFooter(Resources.SIMPSONS_GIF_WARNING); results.WithColor(new DiscordColor("#69E398")); await ctx.RespondAsync(output, embed: results.Build()).ConfigureAwait(false); @@ -87,7 +97,8 @@ public async Task FuturamaGIF(CommandContext ctx, [Description("Retrieve a random Rick and Morty screenshot and episode")] public async Task RickMorty(CommandContext ctx) { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.MasterOfAllScience).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.MasterOfAllScience) + .ConfigureAwait(false); results.WithColor(new DiscordColor("#ABD5EC")); await ctx.RespondAsync(embed: results.Build()).ConfigureAwait(false); } @@ -102,12 +113,16 @@ public async Task RickMorty(CommandContext ctx) public async Task RickMortyGif(CommandContext ctx, [Description("Inputting anything will add episode information")] [RemainingText] string input) { - var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.MasterOfAllScience).ConfigureAwait(false); + var output = await SimpsonsService.GetSimpsonsGifAsync(SimpsonsService.SiteRoot.MasterOfAllScience) + .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(input)) + { await ctx.RespondAsync(output).ConfigureAwait(false); + } else // Include episode information if any kind of parameter is inputted { - var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.MasterOfAllScience).ConfigureAwait(false); + var results = await SimpsonsService.GetSimpsonsDataAsync(SimpsonsService.SiteRoot.MasterOfAllScience) + .ConfigureAwait(false); results.WithFooter(Resources.SIMPSONS_GIF_WARNING); results.WithColor(new DiscordColor("#ABD5EC")); await ctx.RespondAsync(output, embed: results.Build()).ConfigureAwait(false); diff --git a/src/FlawBOT.Core/Modules/Search/TwitchModule.cs b/src/FlawBOT.Core/Modules/Search/TwitchModule.cs index 22b3f128..3e99fcb2 100644 --- a/src/FlawBOT.Core/Modules/Search/TwitchModule.cs +++ b/src/FlawBOT.Core/Modules/Search/TwitchModule.cs @@ -1,10 +1,10 @@ -using DSharpPlus.CommandsNext; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -22,7 +22,10 @@ public async Task Twitch(CommandContext ctx, if (!BotServices.CheckUserInput(query)) return; var results = await TwitchService.GetTwitchDataAsync(query).ConfigureAwait(false); if (results.Stream.Count == 0) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_TWITCH, EmbedType.Missing).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_TWITCH, EmbedType.Missing) + .ConfigureAwait(false); + } else { var stream = results.Stream[0]; diff --git a/src/FlawBOT.Core/Modules/Search/WikipediaModule.cs b/src/FlawBOT.Core/Modules/Search/WikipediaModule.cs index 02b9815d..02e71de2 100644 --- a/src/FlawBOT.Core/Modules/Search/WikipediaModule.cs +++ b/src/FlawBOT.Core/Modules/Search/WikipediaModule.cs @@ -1,9 +1,9 @@ -using DSharpPlus.CommandsNext; +using System.Threading.Tasks; +using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -21,7 +21,8 @@ public async Task Wikipedia(CommandContext ctx, if (!BotServices.CheckUserInput(query)) return; var results = WikipediaService.GetWikipediaDataAsync(query).Result; if (results.Missing) - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_WIKIPEDIA, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_WIKIPEDIA, EmbedType.Missing) + .ConfigureAwait(false); else await ctx.Channel.SendMessageAsync(results.FullUrl).ConfigureAwait(false); } diff --git a/src/FlawBOT.Core/Modules/Search/YoutubeModule.cs b/src/FlawBOT.Core/Modules/Search/YoutubeModule.cs index a46ec442..2352763a 100644 --- a/src/FlawBOT.Core/Modules/Search/YoutubeModule.cs +++ b/src/FlawBOT.Core/Modules/Search/YoutubeModule.cs @@ -1,8 +1,8 @@ -using DSharpPlus; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using FlawBOT.Framework.Services; -using System.Threading.Tasks; namespace FlawBOT.Modules { diff --git a/src/FlawBOT.Core/Modules/Server/BotModule.cs b/src/FlawBOT.Core/Modules/Server/BotModule.cs index b26b67ad..3fd92414 100644 --- a/src/FlawBOT.Core/Modules/Server/BotModule.cs +++ b/src/FlawBOT.Core/Modules/Server/BotModule.cs @@ -1,4 +1,6 @@ -using DSharpPlus; +using System; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; @@ -6,8 +8,6 @@ using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -27,8 +27,8 @@ public async Task BotInfo(CommandContext ctx) var output = new DiscordEmbedBuilder() .WithTitle(SharedData.Name) .WithDescription("A multipurpose Discord bot written in C# with [DSharpPlus](https://github.com/DSharpPlus/DSharpPlus/).") - .AddField(":clock1: Uptime", $"{(int)uptime.TotalDays:00} days {uptime.Hours:00}:{uptime.Minutes:00}:{uptime.Seconds:00}", true) - .AddField(":link: Links", $"[Commands]({SharedData.GitHubLink}wiki) **|** [Invite]({SharedData.InviteLink}) **|** [GitHub]({SharedData.GitHubLink})", true) + .AddField(":clock1: Uptime",$"{(int) uptime.TotalDays:00} days {uptime.Hours:00}:{uptime.Minutes:00}:{uptime.Seconds:00}", true) + .AddField(":link: Links",$"[Commands]({SharedData.GitHubLink}wiki) **|** [Invite]({SharedData.InviteLink}) **|** [GitHub]({SharedData.GitHubLink})", true) .WithFooter("Thank you for using " + SharedData.Name + $" (v{SharedData.Version})") .WithUrl(SharedData.GitHubLink) .WithColor(SharedData.DefaultColor); @@ -44,11 +44,17 @@ public async Task BotInfo(CommandContext ctx) [RequireUserPermissions(Permissions.Administrator)] public async Task LeaveAsync(CommandContext ctx) { - await ctx.RespondAsync($"Are you sure you want {SharedData.Name} to leave this server?").ConfigureAwait(false); - var message = await ctx.RespondAsync("Respond with **yes** to proceed or wait 10 seconds to cancel this operation.").ConfigureAwait(false); + await ctx.RespondAsync($"Are you sure you want {SharedData.Name} to leave this server?") + .ConfigureAwait(false); + var message = await ctx + .RespondAsync("Respond with **yes** to proceed or wait 10 seconds to cancel this operation.") + .ConfigureAwait(false); var interactivity = await BotServices.GetUserInteractivity(ctx, "yes", 10).ConfigureAwait(false); if (interactivity.Result is null) - await message.ModifyAsync("~~" + message.Content + "~~ " + Resources.REQUEST_TIMEOUT).ConfigureAwait(false); + { + await message.ModifyAsync("~~" + message.Content + "~~ " + Resources.REQUEST_TIMEOUT) + .ConfigureAwait(false); + } else { await BotServices.SendEmbedAsync(ctx, "Thank you for using " + SharedData.Name).ConfigureAwait(false); @@ -65,28 +71,39 @@ public async Task LeaveAsync(CommandContext ctx) [Description("Ping the FlawBOT client")] public async Task Ping(CommandContext ctx) { - await BotServices.SendEmbedAsync(ctx, $":ping_pong: Pong! Ping: **{ctx.Client.Ping}**ms", EmbedType.Default).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, $":ping_pong: Pong! Ping: **{ctx.Client.Ping}**ms") + .ConfigureAwait(false); } #endregion COMMAND_PING #region COMMAND_REPORT - [Command("report"), Hidden] + [Command("report")] + [Hidden] [Aliases("issue")] [Description("Report a problem with FlawBOT to the developer. Please do not abuse.")] public async Task ReportIssue(CommandContext ctx, [Description("Detailed description of the issue")] [RemainingText] string report) { if (string.IsNullOrWhiteSpace(report) || report.Length < 50) + { await ctx.RespondAsync(Resources.ERR_REPORT_CHAR_LENGTH).ConfigureAwait(false); + } else { - await ctx.RespondAsync("The following information will be sent to the developer for investigation: User ID, Server ID, Server Name and Server Owner Name.").ConfigureAwait(false); - var message = await ctx.RespondAsync("Respond with **yes** to proceed or wait 10 seconds to cancel this operation.").ConfigureAwait(false); + await ctx.RespondAsync( + "The following information will be sent to the developer for investigation: User ID, Server ID, Server Name and Server Owner Name.") + .ConfigureAwait(false); + var message = await ctx + .RespondAsync("Respond with **yes** to proceed or wait 10 seconds to cancel this operation.") + .ConfigureAwait(false); var interactivity = await BotServices.GetUserInteractivity(ctx, "yes", 10).ConfigureAwait(false); if (interactivity.Result is null) - await message.ModifyAsync("~~" + message.Content + "~~ " + Resources.REQUEST_TIMEOUT).ConfigureAwait(false); + { + await message.ModifyAsync("~~" + message.Content + "~~ " + Resources.REQUEST_TIMEOUT) + .ConfigureAwait(false); + } else { var dm = await ctx.Member.CreateDmChannelAsync().ConfigureAwait(false); @@ -99,7 +116,8 @@ public async Task ReportIssue(CommandContext ctx, .AddField("Confirm", $"[Click here to add this issue to GitHub]({SharedData.GitHubLink}/issues/new)") .WithColor(SharedData.DefaultColor); await dm.SendMessageAsync(embed: output.Build()).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Thank You! Your report has been submitted.", EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Thank You! Your report has been submitted.", EmbedType.Good) + .ConfigureAwait(false); } } } @@ -108,7 +126,8 @@ public async Task ReportIssue(CommandContext ctx, #region COMMAND_SAY - [Command("say"), Hidden] + [Command("say")] + [Hidden] [Aliases("echo")] [Description("Make FlawBOT repeat a message")] public async Task Say(CommandContext ctx, @@ -126,12 +145,10 @@ public async Task Say(CommandContext ctx, [Aliases("talk")] [Description("Make FlawBOT repeat a message in text-to-speech")] [RequirePermissions(Permissions.SendTtsMessages)] - public Task SayTTS(CommandContext ctx, + public Task SayTts(CommandContext ctx, [Description("Message for the bot to convert to speech")] [RemainingText] string text) { - if (string.IsNullOrWhiteSpace(text)) - return ctx.RespondAsync("I need something to say..."); - return ctx.RespondAsync(Formatter.BlockCode(Formatter.Strip(text)), isTTS: true); + return string.IsNullOrWhiteSpace(text) ? ctx.RespondAsync("I need something to say...") : ctx.RespondAsync(Formatter.BlockCode(Formatter.Strip(text)), true); } #endregion COMMAND_TTS @@ -144,8 +161,10 @@ public Task SayTTS(CommandContext ctx, public async Task Uptime(CommandContext ctx) { var uptime = DateTime.Now - SharedData.ProcessStarted; - var days = (uptime.Days > 0) ? $"({uptime.Days:00} days)" : string.Empty; - await BotServices.SendEmbedAsync(ctx, $":clock1: {SharedData.Name} has been online for {uptime.Hours:00}:{uptime.Minutes:00}:{uptime.Seconds} {days}").ConfigureAwait(false); + var days = uptime.Days > 0 ? $"({uptime.Days:00} days)" : string.Empty; + await BotServices.SendEmbedAsync(ctx, + $":clock1: {SharedData.Name} has been online for {uptime.Hours:00}:{uptime.Minutes:00}:{uptime.Seconds} {days}") + .ConfigureAwait(false); } #endregion COMMAND_UPTIME @@ -155,7 +174,8 @@ public async Task Uptime(CommandContext ctx) #region COMMAND_ACTIVITY [RequireOwner] - [Command("activity"), Hidden] + [Command("activity")] + [Hidden] [Aliases("setactivity")] [Description("Set FlawBOT's activity")] public async Task SetBotActivity(CommandContext ctx, @@ -163,15 +183,18 @@ public async Task SetBotActivity(CommandContext ctx, { if (string.IsNullOrWhiteSpace(activity)) { - await ctx.Client.UpdateStatusAsync(activity: null).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " activity has been changed to Normal").ConfigureAwait(false); + await ctx.Client.UpdateStatusAsync().ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " activity has been changed to Normal") + .ConfigureAwait(false); } else { // TODO: Set the activity type var game = new DiscordActivity(activity); - await ctx.Client.UpdateStatusAsync(activity: game).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " activity has been changed to Playing " + game.Name, EmbedType.Good).ConfigureAwait(false); + await ctx.Client.UpdateStatusAsync(game).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + SharedData.Name + " activity has been changed to Playing " + game.Name, EmbedType.Good) + .ConfigureAwait(false); } } @@ -180,7 +203,8 @@ public async Task SetBotActivity(CommandContext ctx, #region COMMAND_AVATAR [RequireOwner] - [Command("avatar"), Hidden] + [Command("avatar")] + [Hidden] [Aliases("setavatar", "pfp", "photo")] [Description("Set FlawBOT's avatar")] public async Task SetBotAvatar(CommandContext ctx, @@ -189,7 +213,8 @@ public async Task SetBotAvatar(CommandContext ctx, var stream = BotServices.CheckImageInput(ctx, query).Result; if (stream.Length <= 0) return; await ctx.Client.UpdateCurrentUserAsync(avatar: stream).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " avatar has been updated!", EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " avatar has been updated!", EmbedType.Good) + .ConfigureAwait(false); } #endregion COMMAND_AVATAR @@ -197,7 +222,8 @@ public async Task SetBotAvatar(CommandContext ctx, #region COMMAND_STATUS [RequireOwner] - [Command("status"), Hidden] + [Command("status")] + [Hidden] [Aliases("setstatus", "state")] [Description("Set FlawBOT's status")] public async Task SetBotStatus(CommandContext ctx, @@ -209,28 +235,34 @@ public async Task SetBotStatus(CommandContext ctx, case "OFF": case "OFFLINE": await ctx.Client.UpdateStatusAsync(userStatus: UserStatus.Offline).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Offline").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Offline") + .ConfigureAwait(false); break; case "INVISIBLE": await ctx.Client.UpdateStatusAsync(userStatus: UserStatus.Invisible).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Invisible").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Invisible") + .ConfigureAwait(false); break; case "IDLE": await ctx.Client.UpdateStatusAsync(userStatus: UserStatus.Idle).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Idle").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Idle") + .ConfigureAwait(false); break; case "DND": case "DO NOT DISTURB": await ctx.Client.UpdateStatusAsync(userStatus: UserStatus.DoNotDisturb).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Do Not Disturb").ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Do Not Disturb") + .ConfigureAwait(false); break; default: await ctx.Client.UpdateStatusAsync(userStatus: UserStatus.Online).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Online").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, SharedData.Name + " status has been changed to Online") + .ConfigureAwait(false); break; } } @@ -240,14 +272,14 @@ public async Task SetBotStatus(CommandContext ctx, #region COMMAND_UPDATE [RequireOwner] - [Command("update"), Hidden] + [Command("update")] + [Hidden] [Aliases("refresh")] [Description("Update FlawBOT libraries")] public async Task Update(CommandContext ctx) { var message = await ctx.RespondAsync("Starting update...").ConfigureAwait(false); - await SteamService.UpdateSteamListAsync().ConfigureAwait(false); - await TeamFortressService.UpdateTF2SchemaAsync().ConfigureAwait(false); + await TeamFortressService.UpdateTf2SchemaAsync().ConfigureAwait(false); await PokemonService.UpdatePokemonListAsync().ConfigureAwait(false); await message.ModifyAsync("Starting update...done!").ConfigureAwait(false); } @@ -257,7 +289,8 @@ public async Task Update(CommandContext ctx) #region COMMAND_USERNAME [RequireOwner] - [Command("username"), Hidden] + [Command("username")] + [Hidden] [Aliases("setusername", "name", "setname", "nickname", "nick")] [Description("Set FlawBOT's username")] public async Task SetBotUsername(CommandContext ctx, @@ -266,13 +299,17 @@ public async Task SetBotUsername(CommandContext ctx, var oldUsername = ctx.Client.CurrentUser.Username; if (string.IsNullOrWhiteSpace(name)) { - await ctx.Client.UpdateCurrentUserAsync(username: SharedData.Name).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, oldUsername + " username has been changed to " + SharedData.Name).ConfigureAwait(false); + await ctx.Client.UpdateCurrentUserAsync(SharedData.Name).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, oldUsername + " username has been changed to " + SharedData.Name) + .ConfigureAwait(false); } else { - await ctx.Client.UpdateCurrentUserAsync(username: name).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, oldUsername + " username has been changed to " + ctx.Client.CurrentUser.Username, EmbedType.Good).ConfigureAwait(false); + await ctx.Client.UpdateCurrentUserAsync(name).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + oldUsername + " username has been changed to " + ctx.Client.CurrentUser.Username, + EmbedType.Good) + .ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Server/ChannelModule.cs b/src/FlawBOT.Core/Modules/Server/ChannelModule.cs index c05bf40c..82ea5725 100644 --- a/src/FlawBOT.Core/Modules/Server/ChannelModule.cs +++ b/src/FlawBOT.Core/Modules/Server/ChannelModule.cs @@ -1,17 +1,16 @@ -using DSharpPlus; +using System; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; -using DSharpPlus.Net.Models; using FlawBOT.Common; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -31,7 +30,10 @@ public async Task CreateChannelCategory(CommandContext ctx, [Description("New category name")] [RemainingText] string name) { if (!BotServices.CheckChannelName(name)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning) + .ConfigureAwait(false); + } else { var category = await ctx.Guild.CreateChannelCategoryAsync(name.Trim()).ConfigureAwait(false); @@ -52,7 +54,9 @@ public async Task Clean(CommandContext ctx, { var messages = await ctx.Channel.GetMessagesAsync(BotServices.LimitToRange(limit)).ConfigureAwait(false); await ctx.Channel.DeleteMessagesAsync(messages).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(messages.Count.ToString()) + " message(s) removed from #" + ctx.Channel.Name, EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + Formatter.Bold(messages.Count.ToString()) + " message(s) removed from #" + ctx.Channel.Name, + EmbedType.Good).ConfigureAwait(false); } #endregion CHANNEL_CLEAN @@ -69,15 +73,21 @@ public async Task RemoveTextChannel(CommandContext ctx, // Set the current channel for deletion if one isn't provided by the user channel = channel ?? ctx.Channel; - var prompt = await ctx.RespondAsync("You're about to delete the " + Formatter.Bold(channel.ToString()) + "\nRespond with **yes** if you want to proceed or wait 10 seconds to cancel the operation.").ConfigureAwait(false); + var prompt = await ctx + .RespondAsync("You're about to delete the " + Formatter.Bold(channel.ToString()) + "\nRespond with **yes** if you want to proceed or wait 10 seconds to cancel the operation.") + .ConfigureAwait(false); var interactivity = await BotServices.GetUserInteractivity(ctx, "yes", 10).ConfigureAwait(false); if (interactivity.Result is null) + { await ctx.RespondAsync(Resources.REQUEST_TIMEOUT).ConfigureAwait(false); + } else { await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false); await BotServices.RemoveMessage(prompt).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully deleted " + Formatter.Bold(channel.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Successfully deleted " + Formatter.Bold(channel.Name), EmbedType.Good) + .ConfigureAwait(false); await channel.DeleteAsync().ConfigureAwait(false); } } @@ -107,7 +117,7 @@ public Task GetChannel(CommandContext ctx, .AddField("Type", channel.Type.ToString(), true) .AddField("Private", channel.IsPrivate ? "Yes" : "No", true) .AddField("NSFW", channel.IsNSFW ? "Yes" : "No", true) - .WithThumbnailUrl(ctx.Guild.IconUrl) + .WithThumbnail(ctx.Guild.IconUrl) .WithFooter("Created on " + channel.CreationTimestamp.DateTime.ToString(CultureInfo.InvariantCulture)) .WithColor(SharedData.DefaultColor); @@ -115,17 +125,18 @@ public Task GetChannel(CommandContext ctx, switch (channel.Type) { case ChannelType.Voice: - output.AddField("Bitrate", channel.Bitrate.ToString() ?? "Unknown", true); - output.AddField("User limit", (channel.UserLimit > 0) ? channel.UserLimit.ToString() : "No limit.", true); + output.AddField("Bitrate", channel.Bitrate.ToString(), true); + output.AddField("User limit", channel.UserLimit > 0 ? channel.UserLimit.ToString() : "No limit.", true); break; case ChannelType.Category: var channels = new StringBuilder(); foreach (var chn in channel.Children) - channels.Append($"[`{chn.Name}`]"); - output.AddField("Channels", (channels.Length > 0) ? channels.ToString() : "None", true); + channels.Append($"[`{chn.Name}`]"); + output.AddField("Channels", channels.Length > 0 ? channels.ToString() : "None", true); break; } + return ctx.RespondAsync(embed: output.Build()); } @@ -142,7 +153,9 @@ public async Task Purge(CommandContext ctx, { var messages = await ctx.Channel.GetMessagesAsync(BotServices.LimitToRange(limit)).ConfigureAwait(false); await ctx.Channel.DeleteMessagesAsync(messages.Where(m => m.Author.Id == member.Id)).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, $"Purged **{limit}** messages by {member.Username}#{member.Discriminator} (ID:{member.Id})", EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + $"Purged **{limit}** messages by {member.Username}#{member.Discriminator} (ID:{member.Id})", + EmbedType.Good).ConfigureAwait(false); } #endregion CHANNEL_PURGE @@ -158,12 +171,17 @@ public async Task SetChannelName(CommandContext ctx, [Description("New channel name")] [RemainingText] string name) { if (!BotServices.CheckChannelName(name)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning) + .ConfigureAwait(false); + } else { - var old_name = channel.Name; - await channel.ModifyAsync(new Action(m => m.Name = name.Trim().Replace(" ", "-"))).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, $"Successfully renamed the channel " + Formatter.Bold(old_name) + " to " + Formatter.Bold(name), EmbedType.Good).ConfigureAwait(false); + var oldName = channel.Name; + await channel.ModifyAsync(m => m.Name = name.Trim().Replace(" ", "-")).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + "Successfully renamed the channel " + Formatter.Bold(oldName) + " to " + Formatter.Bold(name), + EmbedType.Good).ConfigureAwait(false); } } @@ -179,13 +197,22 @@ public async Task CreateTextChannel(CommandContext ctx, [Description("New text channel name")] [RemainingText] string name = "") { if (!BotServices.CheckChannelName(name)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning).ConfigureAwait(false); - else if (ctx.Guild.Channels.Any(chn => string.Compare(name, chn.Value.Name, true) == 0)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_EXISTS, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning) + .ConfigureAwait(false); + } + else if (ctx.Guild.Channels.Any(chn => string.Compare(name, chn.Value.Name, StringComparison.OrdinalIgnoreCase) == 0)) + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_EXISTS, EmbedType.Warning) + .ConfigureAwait(false); + } else { - var channel = await ctx.Guild.CreateTextChannelAsync(name.Trim().Replace(" ", "-")).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully created the text channel " + Formatter.Bold(channel.Name), EmbedType.Good).ConfigureAwait(false); + var channel = await ctx.Guild.CreateTextChannelAsync(name.Trim().Replace(" ", "-")) + .ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + "Successfully created the text channel " + Formatter.Bold(channel.Name), EmbedType.Good) + .ConfigureAwait(false); } } @@ -201,12 +228,17 @@ public async Task SetChannelTopic(CommandContext ctx, [Description("New channel topic")] [RemainingText] string topic = "") { if (topic.Length > 1024) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_TOPIC, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_TOPIC, EmbedType.Warning) + .ConfigureAwait(false); + } else { await ctx.Channel.ModifyAsync(chn => chn.Topic = topic).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(topic)) - await BotServices.SendEmbedAsync(ctx, "Successfully changed the channel topic to " + Formatter.Bold(topic), EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + "Successfully changed the channel topic to " + Formatter.Bold(topic), EmbedType.Good) + .ConfigureAwait(false); } } @@ -222,13 +254,22 @@ public async Task CreateVoiceChannel(CommandContext ctx, [Description("New voice channel name")] [RemainingText] string name = "") { if (!BotServices.CheckChannelName(name)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning).ConfigureAwait(false); - else if (ctx.Guild.Channels.Any(chn => string.Compare(name, chn.Value.Name, true) == 0)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_EXISTS, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_NAME, EmbedType.Warning) + .ConfigureAwait(false); + } + else if (ctx.Guild.Channels.Any(chn => string.Compare(name, chn.Value.Name, StringComparison.OrdinalIgnoreCase) == 0)) + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_CHANNEL_EXISTS, EmbedType.Warning) + .ConfigureAwait(false); + } else { - var channel = await ctx.Guild.CreateVoiceChannelAsync(name: name.Trim().Replace(" ", "-")).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully created the voice channel " + Formatter.Bold(channel.Name), EmbedType.Good).ConfigureAwait(false); + var channel = await ctx.Guild.CreateVoiceChannelAsync(name.Trim().Replace(" ", "-")) + .ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + "Successfully created the voice channel " + Formatter.Bold(channel.Name), EmbedType.Good) + .ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Server/EmojiModule.cs b/src/FlawBOT.Core/Modules/Server/EmojiModule.cs index 8cf36f36..3e2650f8 100644 --- a/src/FlawBOT.Core/Modules/Server/EmojiModule.cs +++ b/src/FlawBOT.Core/Modules/Server/EmojiModule.cs @@ -1,4 +1,9 @@ -using DSharpPlus; +using System; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; @@ -6,11 +11,6 @@ using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -33,24 +33,29 @@ public async Task AddAsync(CommandContext ctx, try { if (string.IsNullOrWhiteSpace(query) || query.Length < 2 || query.Length > 50) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NAME, EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NAME, EmbedType.Warning) + .ConfigureAwait(false); if (url is null) if (!ctx.Message.Attachments.Any() || !Uri.TryCreate(ctx.Message.Attachments.First().Url, UriKind.Absolute, out url)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_IMAGE, EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_IMAGE, EmbedType.Warning) + .ConfigureAwait(false); - var _handler = new HttpClientHandler { AllowAutoRedirect = false }; - var _http = new HttpClient(_handler, true); - var response = await _http.GetAsync(url).ConfigureAwait(false); + var handler = new HttpClientHandler {AllowAutoRedirect = false}; + var http = new HttpClient(handler, true); + var response = await http.GetAsync(url).ConfigureAwait(false); if (!response.Content.Headers.ContentType.MediaType.StartsWith("image/")) return; - using (response = await _http.GetAsync(url).ConfigureAwait(false)) + using (response = await http.GetAsync(url).ConfigureAwait(false)) using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { if (stream.Length >= 256000) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_SIZE, EmbedType.Warning).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_SIZE, EmbedType.Warning) + .ConfigureAwait(false); var emoji = await ctx.Guild.CreateEmojiAsync(query, stream).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully added " + Formatter.Bold(emoji.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Successfully added " + Formatter.Bold(emoji.Name), EmbedType.Good) + .ConfigureAwait(false); } } catch @@ -74,11 +79,14 @@ public async Task DeleteAsync(CommandContext ctx, { var emoji = await ctx.Guild.GetEmojiAsync(query.Id).ConfigureAwait(false); await ctx.Guild.DeleteEmojiAsync(emoji).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully deleted " + Formatter.Bold(emoji.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Successfully deleted " + Formatter.Bold(emoji.Name), EmbedType.Good) + .ConfigureAwait(false); } catch (NotFoundException) { - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_EMOJI, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_EMOJI, EmbedType.Missing) + .ConfigureAwait(false); } } @@ -97,17 +105,22 @@ public async Task ModifyAsync(CommandContext ctx, try { if (string.IsNullOrWhiteSpace(name)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_NAME, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_EMOJI_NAME, EmbedType.Warning) + .ConfigureAwait(false); + } else { var emoji = await ctx.Guild.GetEmojiAsync(query.Id).ConfigureAwait(false); - emoji = await ctx.Guild.ModifyEmojiAsync(emoji, name: name).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully renamed emoji to " + Formatter.Bold(emoji.Name), EmbedType.Good).ConfigureAwait(false); + emoji = await ctx.Guild.ModifyEmojiAsync(emoji, name).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Successfully renamed emoji to " + Formatter.Bold(emoji.Name), + EmbedType.Good).ConfigureAwait(false); } } catch (NotFoundException) { - await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_EMOJI, EmbedType.Missing).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_EMOJI, EmbedType.Missing) + .ConfigureAwait(false); } } @@ -124,12 +137,12 @@ public async Task GetEmoji(CommandContext ctx, var emoji = await ctx.Guild.GetEmojiAsync(query.Id).ConfigureAwait(false); var output = new DiscordEmbedBuilder() .WithTitle(emoji.Name) - .WithDescription("Created By" + ((emoji.User is null) ? "" : emoji.User.Username)) + .WithDescription("Created By" + (emoji.User is null ? "" : emoji.User.Username)) .AddField("Server", emoji.Guild.Name, true) .AddField("Creation Date", emoji.CreationTimestamp.ToString(), true) .WithColor(DiscordColor.PhthaloBlue) .WithUrl(emoji.Url) - .WithThumbnailUrl(emoji.Url); + .WithThumbnail(emoji.Url); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } @@ -144,12 +157,12 @@ public async Task GetEmojiList(CommandContext ctx) { var emojiList = new StringBuilder(); foreach (var emoji in ctx.Guild.Emojis.Values.OrderBy(e => e.Name)) - emojiList.Append(emoji.Name).Append(!emoji.Equals(ctx.Guild.Emojis.Last()) ? ", " : string.Empty); + emojiList.Append(emoji.Name).Append(!emoji.Equals(ctx.Guild.Emojis.Last().Value) ? ", " : string.Empty); var output = new DiscordEmbedBuilder() .WithTitle("Emojis available for " + ctx.Guild.Name) .WithDescription(emojiList.ToString()) - .WithThumbnailUrl(ctx.Guild.IconUrl) + .WithThumbnail(ctx.Guild.IconUrl) .WithColor(DiscordColor.PhthaloBlue); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } diff --git a/src/FlawBOT.Core/Modules/Server/RoleModule.cs b/src/FlawBOT.Core/Modules/Server/RoleModule.cs index f76c831f..2d727244 100644 --- a/src/FlawBOT.Core/Modules/Server/RoleModule.cs +++ b/src/FlawBOT.Core/Modules/Server/RoleModule.cs @@ -1,16 +1,16 @@ -using DSharpPlus; +using System; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -40,7 +40,9 @@ public async Task ColorRole(CommandContext ctx, await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } else + { await BotServices.SendEmbedAsync(ctx, "Invalid color code. Please enter a HEX color code like #E7B53B", EmbedType.Warning).ConfigureAwait(false); + } } #endregion COMMAND_COLOR @@ -55,11 +57,15 @@ public async Task CreateRole(CommandContext ctx, [Description("New role name")] [RemainingText] string role = "") { if (string.IsNullOrWhiteSpace(role)) + { await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NAME, EmbedType.Warning).ConfigureAwait(false); + } else { await ctx.Guild.CreateRoleAsync(role).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully created the server role " + Formatter.Bold(role), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Successfully created the server role " + Formatter.Bold(role), EmbedType.Good) + .ConfigureAwait(false); } } @@ -75,11 +81,15 @@ public async Task DeleteRole(CommandContext ctx, [Description("Server role to delete")] [RemainingText] DiscordRole role = null) { if (role is null) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning) + .ConfigureAwait(false); + } else { await role.DeleteAsync().ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully removed the server role " + Formatter.Bold(role.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Successfully removed the server role " + Formatter.Bold(role.Name), EmbedType.Good) + .ConfigureAwait(false); } } @@ -94,17 +104,20 @@ public async Task GetRole(CommandContext ctx, [Description("Server role information to retrieve")] [RemainingText] DiscordRole role = null) { if (role is null) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning) + .ConfigureAwait(false); + } else { var output = new DiscordEmbedBuilder() .WithTitle(role.Name) - .WithDescription("ID: " + role.Id.ToString()) + .WithDescription("ID: " + role.Id) .AddField("Creation Date", role.CreationTimestamp.DateTime.ToString(CultureInfo.InvariantCulture), true) .AddField("Hoisted", role.IsHoisted ? "Yes" : "No", true) .AddField("Mentionable", role.IsMentionable ? "Yes" : "No", true) .AddField("Permissions", role.Permissions.ToPermissionString()) - .WithThumbnailUrl(ctx.Guild.IconUrl) + .WithThumbnail(ctx.Guild.IconUrl) .WithFooter($"{ctx.Guild.Name} / #{ctx.Channel.Name} / {DateTime.Now}") .WithColor(role.Color); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); @@ -121,7 +134,10 @@ public async Task UsersInRole(CommandContext ctx, [Description("Server role")] [RemainingText] DiscordRole role = null) { if (role is null) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_EXISTING, EmbedType.Warning) + .ConfigureAwait(false); + } else { var userCount = 0; @@ -138,9 +154,12 @@ public async Task UsersInRole(CommandContext ctx, } if (usersList.Length == 0) - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " has no members").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " has no members") + .ConfigureAwait(false); else - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + $" has **{userCount}** member(s): {usersList}").ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, Formatter.Bold(role.Name) + $" has **{userCount}** member(s): {usersList}") + .ConfigureAwait(false); } } @@ -158,12 +177,14 @@ public async Task MentionRole(CommandContext ctx, if (role.IsMentionable) { await role.ModifyAsync(mentionable: false).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **not-mentionable**").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **not-mentionable**") + .ConfigureAwait(false); } else { await role.ModifyAsync(mentionable: true).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **mentionable**").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **mentionable**") + .ConfigureAwait(false); } } @@ -182,7 +203,9 @@ public async Task RemoveUserRole(CommandContext ctx, { member = member ?? ctx.Member; await member.RevokeRoleAsync(role).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(member.DisplayName) + " has been removed from the role " + Formatter.Bold(role.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, + Formatter.Bold(member.DisplayName) + " has been removed from the role " + Formatter.Bold(role.Name), + EmbedType.Good).ConfigureAwait(false); } } @@ -196,14 +219,21 @@ public async Task RemoveUserRole(CommandContext ctx, public async Task RemoveUserRoles(CommandContext ctx, [Description("Server user to get revoked")] DiscordMember member) { - if (member.Roles.Count() == 0) + if (!member.Roles.Any()) + { await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NONE, EmbedType.Warning).ConfigureAwait(false); + } else if (member.Roles.Max(r => r.Position) >= ctx.Member.Roles.Max(r => r.Position)) - await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NOT_ALLOWED, EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, Resources.ERR_ROLE_NOT_ALLOWED, EmbedType.Warning) + .ConfigureAwait(false); + } else { await member.ReplaceRolesAsync(Enumerable.Empty()).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Removed all roles from " + Formatter.Bold(member.DisplayName), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Removed all roles from " + Formatter.Bold(member.DisplayName), EmbedType.Good) + .ConfigureAwait(false); } } @@ -221,7 +251,8 @@ public async Task SetUserRole(CommandContext ctx, { member = member ?? ctx.Member; await member.GrantRoleAsync(role).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, member.DisplayName + " been granted the role " + Formatter.Bold(role.Name), EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, member.DisplayName + " been granted the role " + Formatter.Bold(role.Name), EmbedType.Good) + .ConfigureAwait(false); } #endregion COMMAND_SETROLE @@ -240,12 +271,14 @@ public async Task SidebarRole(CommandContext ctx, if (role.IsHoisted) { await role.ModifyAsync(hoist: false).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **hidden**").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **hidden**") + .ConfigureAwait(false); } else { await role.ModifyAsync(hoist: true).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **displayed**").ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, Formatter.Bold(role.Name) + " is now **displayed**") + .ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Server/ServerModule.cs b/src/FlawBOT.Core/Modules/Server/ServerModule.cs index 5bc252f3..98149998 100644 --- a/src/FlawBOT.Core/Modules/Server/ServerModule.cs +++ b/src/FlawBOT.Core/Modules/Server/ServerModule.cs @@ -1,14 +1,14 @@ -using DSharpPlus; +using System; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Globalization; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -31,11 +31,15 @@ public async Task SetServerAvatar(CommandContext ctx, { var stream = BotServices.CheckImageInput(ctx, query).Result; await ctx.Guild.ModifyAsync(chn => chn.Icon = stream).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, ctx.Guild.Name + " server avatar has been updated!", EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, ctx.Guild.Name + " server avatar has been updated!", EmbedType.Good) + .ConfigureAwait(false); } catch { - await BotServices.SendEmbedAsync(ctx, ctx.Guild.Name + " server avatar has not been updated!", EmbedType.Error).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, ctx.Guild.Name + " server avatar has not been updated!", EmbedType.Error) + .ConfigureAwait(false); } } @@ -51,7 +55,7 @@ public async Task GetServer(CommandContext ctx) var output = new DiscordEmbedBuilder() .WithAuthor($"Owner: {ctx.Guild.Owner.Username}#{ctx.Guild.Owner.Discriminator}", iconUrl: ctx.Guild.Owner.AvatarUrl ?? string.Empty) .WithTitle(ctx.Guild.Name) - .WithDescription("ID: " + ctx.Guild.Id.ToString()) + .WithDescription("ID: " + ctx.Guild.Id) .AddField("Created on", ctx.Guild.CreationTimestamp.DateTime.ToString(CultureInfo.InvariantCulture), true) .AddField("Member Count", ctx.Guild.MemberCount.ToString(), true) .AddField("Region", ctx.Guild.VoiceRegion.Name.ToUpperInvariant(), true) @@ -61,7 +65,7 @@ public async Task GetServer(CommandContext ctx) .WithFooter(ctx.Guild.Name + " / #" + ctx.Channel.Name + " / " + DateTime.Now) .WithColor(DiscordColor.Rose); if (!string.IsNullOrEmpty(ctx.Guild.IconHash)) - output.WithThumbnailUrl(ctx.Guild.IconUrl); + output.WithThumbnail(ctx.Guild.IconUrl); var roles = new StringBuilder(); foreach (var role in ctx.Guild.Roles) @@ -95,17 +99,21 @@ public async Task InviteAsync(CommandContext ctx) [Description("Prune inactive server members")] [RequirePermissions(Permissions.DeafenMembers)] public async Task PruneUsers(CommandContext ctx, - [Description("Number of days the user had to be inactive to get pruned")] [RemainingText] int days = 7) + [Description("Number of days the user had to be inactive to get pruned")] int days = 7) { if (days < 1 || days > 30) - await BotServices.SendEmbedAsync(ctx, "Number of days must be between 1 and 30", EmbedType.Warning).ConfigureAwait(false); - int count = await ctx.Guild.GetPruneCountAsync(days).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Number of days must be between 1 and 30", EmbedType.Warning) + .ConfigureAwait(false); + var count = await ctx.Guild.GetPruneCountAsync(days).ConfigureAwait(false); if (count == 0) { await ctx.RespondAsync("No inactive members found to prune").ConfigureAwait(false); return; } - var prompt = await ctx.RespondAsync($"Pruning will remove {Formatter.Bold(count.ToString())} member(s).\nRespond with **yes** to continue.").ConfigureAwait(false); + + var prompt = await ctx + .RespondAsync($"Pruning will remove {Formatter.Bold(count.ToString())} member(s).\nRespond with **yes** to continue.") + .ConfigureAwait(false); var interactivity = await BotServices.GetUserInteractivity(ctx, "yes", 10).ConfigureAwait(false); if (interactivity.Result is null) return; await BotServices.RemoveMessage(interactivity.Result).ConfigureAwait(false); @@ -124,12 +132,18 @@ public async Task PruneUsers(CommandContext ctx, public async Task SetServerName(CommandContext ctx, [Description("New server name")] [RemainingText] string name = "") { - if (string.IsNullOrWhiteSpace(name) || (name.Length > 100)) - await BotServices.SendEmbedAsync(ctx, "Server name cannot be blank or over 100 characters!", EmbedType.Warning).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(name) || name.Length > 100) + { + await BotServices + .SendEmbedAsync(ctx, "Server name cannot be blank or over 100 characters!", EmbedType.Warning) + .ConfigureAwait(false); + } else { await ctx.Guild.ModifyAsync(srv => srv.Name = name).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Server name has been changed to " + Formatter.Bold(name), EmbedType.Good).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(ctx, "Server name has been changed to " + Formatter.Bold(name), EmbedType.Good) + .ConfigureAwait(false); } } @@ -149,17 +163,21 @@ public async Task Warn(CommandContext ctx, .WithDescription(Formatter.Bold(ctx.Guild.Name) + " has issued you a server warning!") .AddField("Sender:", ctx.Member.Username + "#" + ctx.Member.Discriminator, true) .AddField("Server Owner:", ctx.Guild.Owner.Username + "#" + ctx.Guild.Owner.Discriminator, true) - .WithThumbnailUrl(ctx.Guild.IconUrl) + .WithThumbnail(ctx.Guild.IconUrl) .WithTimestamp(DateTime.Now) .WithColor(DiscordColor.Red); if (!string.IsNullOrWhiteSpace(reason)) output.AddField("Warning message:", reason); var dm = await member.CreateDmChannelAsync().ConfigureAwait(false); if (dm is null) - await BotServices.SendEmbedAsync(ctx, "Unable to direct message this user", EmbedType.Warning).ConfigureAwait(false); + { + await BotServices.SendEmbedAsync(ctx, "Unable to direct message this user", EmbedType.Warning) + .ConfigureAwait(false); + } else { await dm.SendMessageAsync(embed: output.Build()).ConfigureAwait(false); - await BotServices.SendEmbedAsync(ctx, "Successfully sent a warning to " + Formatter.Bold(member.Username), EmbedType.Good).ConfigureAwait(false); + await BotServices.SendEmbedAsync(ctx, "Successfully sent a warning to " + Formatter.Bold(member.Username), EmbedType.Good) + .ConfigureAwait(false); } } diff --git a/src/FlawBOT.Core/Modules/Server/UserModule.cs b/src/FlawBOT.Core/Modules/Server/UserModule.cs index 41a64325..a7140a12 100644 --- a/src/FlawBOT.Core/Modules/Server/UserModule.cs +++ b/src/FlawBOT.Core/Modules/Server/UserModule.cs @@ -1,13 +1,13 @@ -using DSharpPlus; +using System; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.Entities; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; -using System; -using System.Globalization; -using System.Text; -using System.Threading.Tasks; namespace FlawBOT.Modules { @@ -28,7 +28,7 @@ public async Task GetAvatar(CommandContext ctx, member = member ?? ctx.Member; var output = new DiscordEmbedBuilder() .WithImageUrl(member.AvatarUrl) - .WithUrl("https://images.google.com/searchbyimage?image_url=" + member.AvatarUrl) // UNUSED + .WithUrl("https://images.google.com/searchbyimage?image_url=" + member.AvatarUrl) // UNUSED .WithColor(DiscordColor.Lilac); await ctx.RespondAsync(embed: output.Build()).ConfigureAwait(false); } @@ -45,7 +45,9 @@ public async Task Ban(CommandContext ctx, [Description("Reason for the ban")] [RemainingText] string reason = null) { if (ctx.Member.Id == member.Id) + { await ctx.RespondAsync("You cannot ban yourself.").ConfigureAwait(false); + } else { await ctx.Guild.BanMemberAsync(member, 7, reason).ConfigureAwait(false); @@ -67,7 +69,10 @@ public async Task Deafen(CommandContext ctx, [Description("Reason for the deafen")] [RemainingText] string reason = null) { if (member.IsDeafened) - await ctx.RespondAsync($"{member.DisplayName}#{member.Discriminator} is already **deafened**.").ConfigureAwait(false); + { + await ctx.RespondAsync($"{member.DisplayName}#{member.Discriminator} is already **deafened**.") + .ConfigureAwait(false); + } else { await member.SetDeafAsync(true, reason).ConfigureAwait(false); @@ -92,13 +97,13 @@ public async Task GetUser(CommandContext ctx, var perms = permsobj.ToPermissionString(); var output = new DiscordEmbedBuilder() .WithTitle($"@{member.Username}#{member.Discriminator}") - .WithDescription("ID: " + member.Id.ToString()) + .WithDescription("ID: " + member.Id) .AddField("Registered on", member.CreationTimestamp.DateTime.ToString(CultureInfo.InvariantCulture), true) .AddField("Joined on", member.JoinedAt.DateTime.ToString(CultureInfo.InvariantCulture), true) .AddField("Nickname", member.Nickname ?? "None", true) .AddField("Muted?", member.IsMuted ? "Yes" : "No", true) .AddField("Deafened?", member.IsDeafened ? "Yes" : "No", true) - .WithThumbnailUrl(member.AvatarUrl) + .WithThumbnail(member.AvatarUrl) .WithFooter($"{ctx.Guild.Name} / #{ctx.Channel.Name} / {DateTime.Now}") .WithColor(member.Color); if (member.IsBot) @@ -129,7 +134,9 @@ public async Task Kick(CommandContext ctx, [Description("Reason for the kick")] [RemainingText] string reason = null) { if (ctx.Member.Id == member.Id) + { await ctx.RespondAsync("You cannot kick yourself.").ConfigureAwait(false); + } else { await member.RemoveAsync(reason).ConfigureAwait(false); @@ -151,7 +158,10 @@ public async Task Mute(CommandContext ctx, [Description("Reason for the mute")] [RemainingText] string reason = null) { if (member.IsMuted) - await ctx.RespondAsync($"{member.DisplayName}#{member.Discriminator} is already **muted**.").ConfigureAwait(false); + { + await ctx.RespondAsync($"{member.DisplayName}#{member.Discriminator} is already **muted**.") + .ConfigureAwait(false); + } else { await member.SetMuteAsync(true, reason).ConfigureAwait(false); @@ -175,7 +185,9 @@ public async Task SetUserName(CommandContext ctx, member = member ?? ctx.Member; var nickname = member.DisplayName; await member.ModifyAsync(usr => usr.Nickname = name).ConfigureAwait(false); - var response = (!string.IsNullOrWhiteSpace(name)) ? $"{nickname}'s nickname has been changed to **{name}**" : $"{nickname}'s nickname has been reset."; + var response = !string.IsNullOrWhiteSpace(name) + ? $"{nickname}'s nickname has been changed to **{name}**" + : $"{nickname}'s nickname has been reset."; await BotServices.SendEmbedAsync(ctx, response, EmbedType.Good).ConfigureAwait(false); } @@ -210,10 +222,10 @@ public async Task ListServerPermissions(CommandContext ctx, [Description("Unban server user")] [RequirePermissions(Permissions.BanMembers)] public async Task Remove(CommandContext ctx, - [Description("Discord user ID to unban from the server")] ulong userID, + [Description("Discord user ID to unban from the server")] ulong userId, [Description("Reason for the deafen")] [RemainingText] string reason = null) { - var member = await ctx.Client.GetUserAsync(userID).ConfigureAwait(false); + var member = await ctx.Client.GetUserAsync(userId).ConfigureAwait(false); await ctx.Guild.UnbanMemberAsync(member, reason ?? "No reason provided.").ConfigureAwait(false); await BotServices.RemoveMessage(ctx.Message).ConfigureAwait(false); await ctx.RespondAsync($"Unbanned Discord User #{member} from the server.").ConfigureAwait(false); diff --git a/src/FlawBOT.Core/NuGet.Config b/src/FlawBOT.Core/NuGet.Config index 07337814..a9c2d32f 100644 --- a/src/FlawBOT.Core/NuGet.Config +++ b/src/FlawBOT.Core/NuGet.Config @@ -1,4 +1,5 @@ + diff --git a/src/FlawBOT.Core/Program.cs b/src/FlawBOT.Core/Program.cs index 27e06e61..5e1c6bda 100644 --- a/src/FlawBOT.Core/Program.cs +++ b/src/FlawBOT.Core/Program.cs @@ -1,4 +1,9 @@ -using DSharpPlus; +using System; +using System.IO; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using DSharpPlus; using DSharpPlus.CommandsNext; using DSharpPlus.CommandsNext.Attributes; using DSharpPlus.CommandsNext.Exceptions; @@ -7,40 +12,37 @@ using DSharpPlus.Interactivity; using DSharpPlus.Interactivity.Enums; using FlawBOT.Common; +using FlawBOT.Core.Properties; using FlawBOT.Framework.Models; using FlawBOT.Framework.Services; using FlawBOT.Modules; -using System; -using System.IO; -using System.Net; -using System.Threading; -using System.Threading.Tasks; namespace FlawBOT { public class Program { + private static readonly object Lock = new object(); public DiscordClient Client { get; set; } public CommandsNextExtension Commands { get; private set; } - private static readonly object _lock = new object(); public static async Task Main(string[] args) { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls; - Program app = new Program(); + var app = new Program(); app.RunBotAsync().GetAwaiter().GetResult(); await Task.Delay(Timeout.Infinite).ConfigureAwait(false); } catch (Exception ex) { - Console.WriteLine($"\nException occurred: {ex.GetType()} :\n{ex.Message}"); + Console.WriteLine(Resources.ERR_EXCEPTION, ex.GetType(), ex.Message); if (!(ex.InnerException is null)) - Console.WriteLine($"Inner exception: {ex.InnerException.GetType()} :\n{ex.InnerException.Message}"); + Console.WriteLine(Resources.ERR_EXCEPTION_INNER, ex.InnerException.GetType(), ex.InnerException.Message); Console.ReadKey(); } - Console.WriteLine("\nShutting down..."); + + Console.WriteLine(Resources.INFO_SHUTDOWN); } public async Task RunBotAsync() @@ -72,7 +74,7 @@ public async Task RunBotAsync() PrefixResolver = PrefixResolverAsync, // Set the command prefix that will be used by the bot EnableDms = false, // Set the boolean for responding to direct messages EnableMentionPrefix = true, // Set the boolean for mentioning the bot as a command prefix - CaseSensitive = false, + CaseSensitive = false }); Commands.CommandExecuted += Commands_CommandExecuted; Commands.CommandErrored += Commands_CommandErrored; @@ -85,8 +87,8 @@ public async Task RunBotAsync() Commands.RegisterCommands(); Commands.RegisterCommands(); Commands.RegisterCommands(); - Commands.RegisterCommands(); - Commands.RegisterCommands(); + Commands.RegisterCommands(); + Commands.RegisterCommands(); Commands.RegisterCommands(); Commands.RegisterCommands(); Commands.RegisterCommands(); @@ -103,10 +105,9 @@ public async Task RunBotAsync() Commands.SetHelpFormatter(); // Start the uptime counter - Console.Title = SharedData.Name + $" ({SharedData.Version})"; + Console.Title = SharedData.Name + " - " + SharedData.Version; SharedData.ProcessStarted = DateTime.Now; - await SteamService.UpdateSteamListAsync().ConfigureAwait(false); - await TeamFortressService.UpdateTF2SchemaAsync().ConfigureAwait(false); + await TeamFortressService.UpdateTf2SchemaAsync().ConfigureAwait(false); await PokemonService.UpdatePokemonListAsync().ConfigureAwait(false); await Client.ConnectAsync().ConfigureAwait(false); // Connect and log into Discord await Task.Delay(-1).ConfigureAwait(false); // Prevent the console window from closing @@ -141,38 +142,52 @@ private static async Task Commands_CommandErrored(CommandErrorEventArgs e) return; default: - await BotServices.SendEmbedAsync(e.Context, $"Command **{e.Command.QualifiedName}** could not be executed.", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, + $"Command **{e.Command.QualifiedName}** could not be executed.", EmbedType.Error) + .ConfigureAwait(false); foreach (var check in cfe.FailedChecks) - { switch (check) { case RequirePermissionsAttribute perms: - await BotServices.SendEmbedAsync(e.Context, $"- One of us does not have the required permissions ({perms.Permissions.ToPermissionString()})!", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, + $"- One of us does not have the required permissions ({perms.Permissions.ToPermissionString()})!", + EmbedType.Error).ConfigureAwait(false); break; - case RequireUserPermissionsAttribute uperms: - await BotServices.SendEmbedAsync(e.Context, $"- You do not have sufficient permissions ({uperms.Permissions.ToPermissionString()})!", EmbedType.Error).ConfigureAwait(false); + case RequireUserPermissionsAttribute perms: + await BotServices.SendEmbedAsync(e.Context, + $"- You do not have sufficient permissions ({perms.Permissions.ToPermissionString()})!", + EmbedType.Error).ConfigureAwait(false); break; - case RequireBotPermissionsAttribute bperms: - await BotServices.SendEmbedAsync(e.Context, $"- I do not have sufficient permissions ({bperms.Permissions.ToPermissionString()})!", EmbedType.Error).ConfigureAwait(false); + case RequireBotPermissionsAttribute perms: + await BotServices.SendEmbedAsync(e.Context, + $"- I do not have sufficient permissions ({perms.Permissions.ToPermissionString()})!", + EmbedType.Error).ConfigureAwait(false); break; case RequireOwnerAttribute _: - await BotServices.SendEmbedAsync(e.Context, $"- This command is reserved only for the bot owner.", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, + "- This command is reserved only for the bot owner.", EmbedType.Error) + .ConfigureAwait(false); break; case RequirePrefixesAttribute pa: - await BotServices.SendEmbedAsync(e.Context, $"- This command can only be invoked with the following prefixes: {string.Join(" ", pa.Prefixes)}.", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, + $"- This command can only be invoked with the following prefixes: {string.Join(" ", pa.Prefixes)}.", + EmbedType.Error).ConfigureAwait(false); break; default: - await BotServices.SendEmbedAsync(e.Context, "Unknown check triggered. Please notify the developer using the command *.bot report*", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, + "Unknown check triggered. Please notify the developer using the command *.bot report*", + EmbedType.Error).ConfigureAwait(false); break; } - } + break; } + break; case CommandNotFoundException _: @@ -184,26 +199,36 @@ private static async Task Commands_CommandErrored(CommandErrorEventArgs e) break; case ArgumentNullException _: - await BotServices.SendEmbedAsync(e.Context, "Not enough arguments supplied to the command!", EmbedType.Error).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(e.Context, "Not enough arguments supplied to the command!", EmbedType.Error) + .ConfigureAwait(false); break; case ArgumentException _: if (e.Exception.Message.Contains("Not enough arguments supplied to the command")) - await BotServices.SendEmbedAsync(e.Context, "Not enough arguments supplied to the command!", EmbedType.Error).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(e.Context, "Not enough arguments supplied to the command!", EmbedType.Error) + .ConfigureAwait(false); break; case InvalidDataException _: if (e.Exception.Message.Contains("The data within the stream was not valid image data")) - await BotServices.SendEmbedAsync(e.Context, "Provided URL is not an image type!", EmbedType.Error).ConfigureAwait(false); + await BotServices + .SendEmbedAsync(e.Context, "Provided URL is not an image type!", EmbedType.Error) + .ConfigureAwait(false); break; default: if (e.Exception.Message.Contains("Given emote was not found")) - await BotServices.SendEmbedAsync(e.Context, "Suggested emote was not found!", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, "Suggested emote was not found!", EmbedType.Error) + .ConfigureAwait(false); if (e.Exception.Message.Contains("Unauthorized: 403")) - await BotServices.SendEmbedAsync(e.Context, "Insufficient Permissions", EmbedType.Error).ConfigureAwait(false); + await BotServices.SendEmbedAsync(e.Context, "Insufficient Permissions", EmbedType.Error) + .ConfigureAwait(false); else - e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, SharedData.Name, $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? ""}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? ""}", DateTime.Now); // DEBUG ONLY + e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, SharedData.Name, + $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? ""}' but it errored: {e.Exception.GetType()}: {e.Exception.Message}", + DateTime.Now); // DEBUG ONLY break; } } @@ -215,7 +240,7 @@ private static Task PrefixResolverAsync(DiscordMessage m) private static void Client_LogMessageHandler(object sender, DebugLogMessageEventArgs ea) { - lock (_lock) + lock (Lock) { Console.BackgroundColor = ConsoleColor.Black; @@ -225,33 +250,34 @@ private static void Client_LogMessageHandler(object sender, DebugLogMessageEvent Console.ForegroundColor = ConsoleColor.Gray; Console.Write("[{0}] ", ea.Application); - var ccfg = ConsoleColor.Gray; - var ccbg = ConsoleColor.Black; + var fgcolor = ConsoleColor.Gray; + var bgcolor = ConsoleColor.Black; switch (ea.Level) { case LogLevel.Critical: - ccfg = ConsoleColor.Black; - ccbg = ConsoleColor.Red; + fgcolor = ConsoleColor.Black; + bgcolor = ConsoleColor.Red; break; case LogLevel.Error: - ccfg = ConsoleColor.Red; + fgcolor = ConsoleColor.Red; break; case LogLevel.Warning: - ccfg = ConsoleColor.Yellow; + fgcolor = ConsoleColor.Yellow; break; case LogLevel.Info: - ccfg = ConsoleColor.Cyan; + fgcolor = ConsoleColor.Cyan; break; case LogLevel.Debug: - ccfg = ConsoleColor.Magenta; + fgcolor = ConsoleColor.Magenta; break; } - Console.ForegroundColor = ccfg; - Console.BackgroundColor = ccbg; + + Console.ForegroundColor = fgcolor; + Console.BackgroundColor = bgcolor; Console.Write("[{0}]", ea.Level.ToString()); Console.BackgroundColor = ConsoleColor.Black; diff --git a/src/FlawBOT.Core/Properties/Resources.Designer.cs b/src/FlawBOT.Core/Properties/Resources.Designer.cs index a346283b..58e4f504 100644 --- a/src/FlawBOT.Core/Properties/Resources.Designer.cs +++ b/src/FlawBOT.Core/Properties/Resources.Designer.cs @@ -141,6 +141,26 @@ internal static string ERR_EMOJI_SIZE { } } + /// + /// Looks up a localized string similar to Exception occurred: {0} : + ///{1}. + /// + internal static string ERR_EXCEPTION { + get { + return ResourceManager.GetString("ERR_EXCEPTION", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Inner exception: {0} : + ///{1}. + /// + internal static string ERR_EXCEPTION_INNER { + get { + return ResourceManager.GetString("ERR_EXCEPTION_INNER", resourceCulture); + } + } + /// /// Looks up a localized string similar to Error calculating math equation, make sure your values are integers and the operation is valid!. /// @@ -222,6 +242,15 @@ internal static string ERR_STEAM_CONNECT_FORMAT { } } + /// + /// Looks up a localized string similar to Shutting Down. + /// + internal static string INFO_SHUTDOWN { + get { + return ResourceManager.GetString("INFO_SHUTDOWN", resourceCulture); + } + } + /// /// Looks up a localized string similar to Emoji not found in the server list.. /// diff --git a/src/FlawBOT.Core/Properties/Resources.resx b/src/FlawBOT.Core/Properties/Resources.resx index 12a5767e..deef5198 100644 --- a/src/FlawBOT.Core/Properties/Resources.resx +++ b/src/FlawBOT.Core/Properties/Resources.resx @@ -219,4 +219,15 @@ https://www.youtube.com/channel/ + + Exception occurred: {0} : +{1} + + + Inner exception: {0} : +{1} + + + Shutting Down + \ No newline at end of file diff --git a/src/FlawBOT.Framework/FlawBOT.Framework.csproj b/src/FlawBOT.Framework/FlawBOT.Framework.csproj index fda94fe8..78c970e0 100644 --- a/src/FlawBOT.Framework/FlawBOT.Framework.csproj +++ b/src/FlawBOT.Framework/FlawBOT.Framework.csproj @@ -2,9 +2,9 @@ netcoreapp3.1 - 2.7.0.0 - 2.6.0 - 2.6.0.0 + 2.6.1.0 + 2.6.1 + 2.6.1.0 Igor Nikitin CriticalFlaw FlawBOT @@ -15,16 +15,16 @@ - - - - - + + + + + - + diff --git a/src/FlawBOT.Framework/Models/Games/PokemonData.cs b/src/FlawBOT.Framework/Models/Games/PokemonData.cs index 9fd7de32..c89955a7 100644 --- a/src/FlawBOT.Framework/Models/Games/PokemonData.cs +++ b/src/FlawBOT.Framework/Models/Games/PokemonData.cs @@ -12,7 +12,7 @@ public class PokemonCards public class Card { [JsonProperty("id")] - public string ID { get; set; } + public string Id { get; set; } } public class PokemonData diff --git a/src/FlawBOT.Framework/Models/Games/SpeedrunData.cs b/src/FlawBOT.Framework/Models/Games/SpeedrunData.cs index a27c1405..a63aef59 100644 --- a/src/FlawBOT.Framework/Models/Games/SpeedrunData.cs +++ b/src/FlawBOT.Framework/Models/Games/SpeedrunData.cs @@ -15,7 +15,7 @@ public class SpeedrunGame public class Data { [JsonProperty("id")] - public string ID { get; set; } + public string Id { get; set; } [JsonProperty("names")] public Names Names { get; set; } @@ -54,7 +54,7 @@ public class Data [JsonIgnore] [JsonProperty("romhack")] - public int ROMHack { get; set; } + public int RomHack { get; set; } [JsonIgnore] [JsonProperty("gametypes")] @@ -115,7 +115,7 @@ public class Assets public class Image { [JsonProperty("uri")] - public string URL { get; set; } + public string Url { get; set; } [JsonIgnore] [JsonProperty("width")] @@ -129,10 +129,10 @@ public class Image public class Link { [JsonProperty("rel")] - public string REL { get; set; } + public string Rel { get; set; } [JsonProperty("uri")] - public string URL { get; set; } + public string Url { get; set; } } #endregion GAME @@ -145,7 +145,7 @@ public class SpeedrunCategory public List Data { get; set; } } - public partial class CategoryData + public class CategoryData { [JsonProperty("id")] public string Id { get; set; } @@ -174,7 +174,7 @@ public partial class CategoryData public List Links { get; set; } } - public partial class Players + public class Players { [JsonProperty("type")] public string Type { get; set; } @@ -196,7 +196,7 @@ public class SpeedrunExtra public class ExtraData { [JsonProperty("id")] - public string ID { get; set; } + public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } diff --git a/src/FlawBOT.Framework/Models/Misc/MiscData.cs b/src/FlawBOT.Framework/Models/Misc/MiscData.cs index e7aad338..51018a4e 100644 --- a/src/FlawBOT.Framework/Models/Misc/MiscData.cs +++ b/src/FlawBOT.Framework/Models/Misc/MiscData.cs @@ -11,7 +11,7 @@ public class DogData public string Message { get; set; } } - public class IPLocationData + public class IpLocationData { [JsonProperty("@as")] public string Title { get; set; } @@ -26,7 +26,7 @@ public class IPLocationData public string CountryCode { get; set; } [JsonProperty("isp")] - public string ISP { get; set; } + public string Isp { get; set; } [JsonProperty("lat")] public double Latitude { get; set; } diff --git a/src/FlawBOT.Framework/Models/Search/GoogleData.cs b/src/FlawBOT.Framework/Models/Search/GoogleData.cs index 357870e8..a7631318 100644 --- a/src/FlawBOT.Framework/Models/Search/GoogleData.cs +++ b/src/FlawBOT.Framework/Models/Search/GoogleData.cs @@ -9,20 +9,17 @@ namespace FlawBOT.Framework.Models public class TimeData { [JsonProperty("results")] - private GeolocationModel[] results; + private GeolocationModel[] _results; [JsonProperty("timezone")] - private TimeZoneResult timeZone; - - [JsonProperty("time")] - private DateTime time; + private TimeZoneResult _timeZone; [JsonProperty("status")] - public string status { get; set; } + public string Status { get; set; } - public GeolocationModel[] Results { get => results; set => results = value; } - public TimeZoneResult Timezone { get => timeZone; set => timeZone = value; } - public DateTime Time { get => time; set => time = value; } + public GeolocationModel[] Results { get; } + public TimeZoneResult Timezone { get; set; } + public DateTime Time { get; set; } public class GeolocationModel { @@ -51,13 +48,13 @@ public class LocationModel public class TimeZoneResult { [JsonProperty("dstOffset")] - public double dstOffset { get; set; } + public double DstOffset { get; set; } [JsonProperty("rawOffset")] - public double rawOffset { get; set; } + public double RawOffset { get; set; } [JsonProperty("timeZoneName")] - public string timeZoneName { get; set; } + public string TimeZoneName { get; set; } } } @@ -105,7 +102,7 @@ public class Article public class WeatherData { [JsonProperty("id")] - public int ID { get; set; } + public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } @@ -123,7 +120,7 @@ public class WeatherData public List Weather { get; set; } [JsonProperty("cod")] - public int COD { get; set; } + public int Cod { get; set; } } public class Sys @@ -156,7 +153,7 @@ public class Wind public class Weather { [JsonProperty("id")] - public int ID { get; set; } + public int Id { get; set; } [JsonProperty("main")] public string Main { get; set; } diff --git a/src/FlawBOT.Framework/Models/Search/NASAData.cs b/src/FlawBOT.Framework/Models/Search/NASAData.cs index eb540623..defca0bd 100644 --- a/src/FlawBOT.Framework/Models/Search/NASAData.cs +++ b/src/FlawBOT.Framework/Models/Search/NASAData.cs @@ -2,7 +2,7 @@ namespace FlawBOT.Framework.Models { - public class NASAData + public class NasaData { [JsonProperty("copyright")] public string Copyright { get; set; } @@ -14,12 +14,12 @@ public class NASAData public string Description { get; set; } [JsonProperty("hdurl")] - public string ImageHD { get; set; } + public string ImageHd { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("url")] - public string ImageSD { get; set; } + public string ImageSd { get; set; } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Models/Search/SteamData.cs b/src/FlawBOT.Framework/Models/Search/SteamData.cs index a0623c40..0a35e31d 100644 --- a/src/FlawBOT.Framework/Models/Search/SteamData.cs +++ b/src/FlawBOT.Framework/Models/Search/SteamData.cs @@ -18,7 +18,7 @@ public class Applist public class App { [JsonProperty("appid")] - public int ID { get; set; } + public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } diff --git a/src/FlawBOT.Framework/Models/Search/TwitchData.cs b/src/FlawBOT.Framework/Models/Search/TwitchData.cs index 774f73a5..a9e66408 100644 --- a/src/FlawBOT.Framework/Models/Search/TwitchData.cs +++ b/src/FlawBOT.Framework/Models/Search/TwitchData.cs @@ -12,16 +12,16 @@ public class TwitchData public class Stream { [JsonProperty("id")] - public string ID { get; set; } + public string Id { get; set; } [JsonProperty("user_id")] - public int UserID { get; set; } + public int UserId { get; set; } [JsonProperty("user_name")] public string UserName { get; set; } [JsonProperty("game_id")] - public int GameID { get; set; } + public int GameId { get; set; } [JsonProperty("type")] public string Type { get; set; } @@ -45,7 +45,7 @@ public class Stream public class Streamer { [JsonProperty("id")] - public int ID { get; set; } + public int Id { get; set; } [JsonProperty("login")] public string Login { get; set; } diff --git a/src/FlawBOT.Framework/Models/Server/BotData.cs b/src/FlawBOT.Framework/Models/Server/BotData.cs index 0abddd3a..6bbda0fc 100644 --- a/src/FlawBOT.Framework/Models/Server/BotData.cs +++ b/src/FlawBOT.Framework/Models/Server/BotData.cs @@ -20,13 +20,13 @@ public class TokenData public string ImgurToken { get; private set; } [JsonProperty("omdb", NullValueHandling = NullValueHandling.Ignore)] - public string OMDBToken { get; private set; } + public string OmdbToken { get; private set; } [JsonProperty("twitch", NullValueHandling = NullValueHandling.Ignore)] public string TwitchToken { get; private set; } [JsonProperty("nasa", NullValueHandling = NullValueHandling.Ignore)] - public string NASAToken { get; private set; } + public string NasaToken { get; private set; } [JsonProperty("teamworktf", NullValueHandling = NullValueHandling.Ignore)] public string TeamworkToken { get; private set; } diff --git a/src/FlawBOT.Framework/Models/Server/BotHandlers.cs b/src/FlawBOT.Framework/Models/Server/BotHandlers.cs index a04f6e33..2c236c8a 100644 --- a/src/FlawBOT.Framework/Models/Server/BotHandlers.cs +++ b/src/FlawBOT.Framework/Models/Server/BotHandlers.cs @@ -4,8 +4,8 @@ namespace FlawBOT.Framework.Models { public abstract class HttpHandler { - protected static readonly HttpClientHandler _handler = new HttpClientHandler { AllowAutoRedirect = false }; - protected static readonly HttpClient _http = new HttpClient(_handler, true); + private static readonly HttpClientHandler Handler = new HttpClientHandler {AllowAutoRedirect = false}; + protected static readonly HttpClient Http = new HttpClient(Handler, true); } public class TokenHandler diff --git a/src/FlawBOT.Framework/Properties/Resources.Designer.cs b/src/FlawBOT.Framework/Properties/Resources.Designer.cs index 19381976..309fd57b 100644 --- a/src/FlawBOT.Framework/Properties/Resources.Designer.cs +++ b/src/FlawBOT.Framework/Properties/Resources.Designer.cs @@ -239,5 +239,41 @@ internal static string API_Wikipedia { return ResourceManager.GetString("API_Wikipedia", resourceCulture); } } + + /// + /// Looks up a localized string similar to Error updating the Pokémon list. {0}. + /// + internal static string ERR_POKEMON_LIST { + get { + return ResourceManager.GetString("ERR_POKEMON_LIST", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unknown Reddit category. + /// + internal static string ERR_REDDIT_UNKNOWN_CAT { + get { + return ResourceManager.GetString("ERR_REDDIT_UNKNOWN_CAT", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating Steam games list. {0}. + /// + internal static string ERR_STEAM_LIST { + get { + return ResourceManager.GetString("ERR_STEAM_LIST", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Error updating TF2 item schema. {0}. + /// + internal static string ERR_TF2_LIST { + get { + return ResourceManager.GetString("ERR_TF2_LIST", resourceCulture); + } + } } } diff --git a/src/FlawBOT.Framework/Properties/Resources.resx b/src/FlawBOT.Framework/Properties/Resources.resx index 3ad67977..adc78aca 100644 --- a/src/FlawBOT.Framework/Properties/Resources.resx +++ b/src/FlawBOT.Framework/Properties/Resources.resx @@ -177,4 +177,16 @@ https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url + + Error updating the Pokémon list. {0} + + + Unknown Reddit category + + + Error updating Steam games list. {0} + + + Error updating TF2 item schema. {0} + \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Games/PokemonService.cs b/src/FlawBOT.Framework/Services/Games/PokemonService.cs index 0a9ba56c..29fb8881 100644 --- a/src/FlawBOT.Framework/Services/Games/PokemonService.cs +++ b/src/FlawBOT.Framework/Services/Games/PokemonService.cs @@ -1,32 +1,35 @@ -using FlawBOT.Framework.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; using PokemonTcgSdk; using PokemonTcgSdk.Models; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using Card = PokemonTcgSdk.Card; namespace FlawBOT.Framework.Services { public class PokemonService : HttpHandler { - public static List PokemonList { get; set; } = new List(); + private static List PokemonList { get; set; } = new List(); public static async Task GetPokemonCardsAsync(string query = "") { query ??= GetRandomPokemon(); - var results = await _http.GetStringAsync(Resources.API_PokemonTCG + "?name=" + query.ToLowerInvariant().Trim()).ConfigureAwait(false); + var results = await Http + .GetStringAsync(Resources.API_PokemonTCG + "?name=" + query.ToLowerInvariant().Trim()) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } - public static PokemonCard GetExactPokemon(string cardID) + public static PokemonCard GetExactPokemon(string cardId) { - return PokemonTcgSdk.Card.Find(cardID).Card; + return Card.Find(cardId).Card; } - public static string GetRandomPokemon() + private static string GetRandomPokemon() { var random = new Random(); return PokemonList[random.Next(0, PokemonList.Count)]; @@ -36,18 +39,17 @@ public static async Task UpdatePokemonListAsync() { try { - var list = await _http.GetStringAsync(Resources.API_Pokemon).ConfigureAwait(false); + var list = await Http.GetStringAsync(Resources.API_Pokemon).ConfigureAwait(false); var results = JsonConvert.DeserializeObject(list).Results; PokemonList.Clear(); - foreach (var pokemon in results) - if (!string.IsNullOrWhiteSpace(pokemon.Name)) - PokemonList.Add(pokemon.Name); + foreach (var pokemon in results.Where(pokemon => !string.IsNullOrWhiteSpace(pokemon.Name))) + PokemonList.Add(pokemon.Name); PokemonList = PokemonList.Distinct().ToList(); return true; } catch (Exception ex) { - Console.WriteLine("Error updating the Pokémon list. " + ex.Message); + Console.WriteLine(Resources.ERR_POKEMON_LIST, ex.Message); return false; } } diff --git a/src/FlawBOT.Framework/Services/Games/SpeedrunService.cs b/src/FlawBOT.Framework/Services/Games/SpeedrunService.cs index 994cd559..6ddcd1d8 100644 --- a/src/FlawBOT.Framework/Services/Games/SpeedrunService.cs +++ b/src/FlawBOT.Framework/Services/Games/SpeedrunService.cs @@ -1,25 +1,27 @@ -using FlawBOT.Framework.Models; -using FlawBOT.Framework.Properties; -using Newtonsoft.Json; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using FlawBOT.Framework.Models; +using FlawBOT.Framework.Properties; +using Newtonsoft.Json; namespace FlawBOT.Framework.Services { public class SpeedrunService : HttpHandler { /// - /// Retrieve game speedrun data + /// Retrieve game speedrun data /// /// Name of the game public static async Task GetSpeedrunGameAsync(string query) { try { - var results = await _http.GetStringAsync(Resources.API_Speedrun + "games?name=" + Uri.EscapeUriString(query.Trim())).ConfigureAwait(false); + var results = await Http + .GetStringAsync(Resources.API_Speedrun + "games?name=" + Uri.EscapeUriString(query.Trim())) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } catch @@ -29,14 +31,14 @@ public static async Task GetSpeedrunGameAsync(string query) } /// - /// Retrieve category speedrun data + /// Retrieve category speedrun data /// /// Name of the game public static async Task GetSpeedrunCategoryAsync(string query) { try { - var results = await _http.GetStringAsync(query).ConfigureAwait(false); + var results = await Http.GetStringAsync(query).ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } catch @@ -46,14 +48,16 @@ public static async Task GetSpeedrunCategoryAsync(string query } /// - /// Retrieve game's identification key for Speedrun.com + /// Retrieve game's identification key for Speedrun.com /// - public static async Task GetSpeedrunGameIDAsync(string query) + public static async Task GetSpeedrunGameIdAsync(string query) { try { - var results = await _http.GetStringAsync(Resources.API_Speedrun + "games?name=" + Uri.EscapeUriString(query.Trim())).ConfigureAwait(false); - return JsonConvert.DeserializeObject(results).Data.First().ID; + var results = await Http + .GetStringAsync(Resources.API_Speedrun + "games?name=" + Uri.EscapeUriString(query.Trim())) + .ConfigureAwait(false); + return JsonConvert.DeserializeObject(results).Data.First().Id; } catch { @@ -62,9 +66,10 @@ public static async Task GetSpeedrunGameIDAsync(string query) } /// - /// Retrieve the speedrun game's platforms, genres, developers or publishers. + /// Retrieve the speedrun game's platforms, genres, developers or publishers. /// - /// Developer IDs + /// Speedrun extra identifier + /// Speedrun extra category public static async Task GetSpeedrunExtraAsync(List queryList, SpeedrunExtras search) { try @@ -73,10 +78,13 @@ public static async Task GetSpeedrunExtraAsync(List queryList, S var results = new StringBuilder(); foreach (var query in queryList.Take(3)) { - var output = await _http.GetStringAsync(Resources.API_Speedrun + search.ToString().ToLowerInvariant() + "/" + query).ConfigureAwait(false); + var output = await Http + .GetStringAsync(Resources.API_Speedrun + search.ToString().ToLowerInvariant() + "/" + query) + .ConfigureAwait(false); var name = JsonConvert.DeserializeObject(output).Data.Name; results.Append(name).Append(!query.Equals(queryList.Take(3).Last()) ? ", " : string.Empty); } + return results.ToString(); } catch diff --git a/src/FlawBOT.Framework/Services/Games/SteamService.cs b/src/FlawBOT.Framework/Services/Games/SteamService.cs index 8ffc691f..ccaff151 100644 --- a/src/FlawBOT.Framework/Services/Games/SteamService.cs +++ b/src/FlawBOT.Framework/Services/Games/SteamService.cs @@ -1,35 +1,33 @@ -using FlawBOT.Framework.Models; +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using Microsoft.Extensions.Options; using Steam.Models.SteamCommunity; using Steam.Models.SteamStore; using SteamWebAPI2.Interfaces; using SteamWebAPI2.Utilities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { public class SteamService : HttpHandler { - public static Dictionary SteamAppList { get; set; } = new Dictionary(); - public static SteamWebInterfaceFactory SteamInterface; + private static SteamWebInterfaceFactory _steamInterface; /// https://github.com/babelshift/SteamWebAPI2/issues/81 public static async Task GetSteamAppAsync(string query) { try { - SteamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); - SteamWebInterfaceFactoryOptions factoryOptions = new SteamWebInterfaceFactoryOptions() + _steamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); + var factoryOptions = new SteamWebInterfaceFactoryOptions { SteamWebApiKey = TokenHandler.Tokens.SteamToken }; var store = new SteamWebInterfaceFactory(Options.Create(factoryOptions)).CreateSteamStoreInterface(); - var list = await SteamInterface.CreateSteamWebInterface(new HttpClient()).GetAppListAsync(); - var appId = list.Data.Where(n => string.Equals(n.Name, query, StringComparison.InvariantCultureIgnoreCase)).First().AppId; + var list = await _steamInterface.CreateSteamWebInterface(new HttpClient()).GetAppListAsync(); + var appId = list.Data.First(n => string.Equals(n.Name, query, StringComparison.InvariantCultureIgnoreCase)).AppId; return await store.GetStoreAppDetailsAsync(appId).ConfigureAwait(false); } catch @@ -42,12 +40,11 @@ public static async Task GetSteamProfileAsync(string { try { - SteamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); - var steam = SteamInterface.CreateSteamWebInterface(new HttpClient()); + _steamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); + var steam = _steamInterface.CreateSteamWebInterface(new HttpClient()); if (ulong.TryParse(query, out var steamId)) return await steam.GetCommunityProfileAsync(steamId).ConfigureAwait(false); - else - return await steam.GetCommunityProfileAsync(GetSteamUserID(query).Result.Data).ConfigureAwait(false); + return await steam.GetCommunityProfileAsync(GetSteamUserId(query).Result.Data).ConfigureAwait(false); } catch { @@ -59,12 +56,11 @@ public static async Task> GetSteamSummaryA { try { - SteamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); - var steam = SteamInterface.CreateSteamWebInterface(new HttpClient()); + _steamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); + var steam = _steamInterface.CreateSteamWebInterface(new HttpClient()); if (ulong.TryParse(query, out var steamId)) - return await steam.GetPlayerSummaryAsync(ulong.Parse(query)).ConfigureAwait(false); - else - return await steam.GetPlayerSummaryAsync(GetSteamUserID(query).Result.Data).ConfigureAwait(false); + return await steam.GetPlayerSummaryAsync(steamId).ConfigureAwait(false); + return await steam.GetPlayerSummaryAsync(GetSteamUserId(query).Result.Data).ConfigureAwait(false); } catch { @@ -72,31 +68,11 @@ public static async Task> GetSteamSummaryA } } - public static async Task UpdateSteamListAsync() - { - try - { - SteamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); - var steam = SteamInterface.CreateSteamWebInterface(new HttpClient()); - var games = (await steam.GetAppListAsync().ConfigureAwait(false)).Data; - SteamAppList.Clear(); - foreach (var game in games) - if (!string.IsNullOrWhiteSpace(game.Name)) - SteamAppList.Add(Convert.ToUInt32(game.AppId), game.Name); - return true; - } - catch (Exception ex) - { - Console.WriteLine("Error updating Steam games list. " + ex.Message); - return false; - } - } - - public static async Task> GetSteamUserID(string query) + public static async Task> GetSteamUserId(string query) { try { - var steam = SteamInterface.CreateSteamWebInterface(new HttpClient()); + var steam = _steamInterface.CreateSteamWebInterface(new HttpClient()); return await steam.ResolveVanityUrlAsync(query).ConfigureAwait(false); } catch diff --git a/src/FlawBOT.Framework/Services/Games/TeamFortressService.cs b/src/FlawBOT.Framework/Services/Games/TeamFortressService.cs index 4c7bb3e0..262d3a3c 100644 --- a/src/FlawBOT.Framework/Services/Games/TeamFortressService.cs +++ b/src/FlawBOT.Framework/Services/Games/TeamFortressService.cs @@ -1,34 +1,65 @@ -using FlawBOT.Framework.Models; -using SteamWebAPI2.Interfaces; -using SteamWebAPI2.Models.GameEconomy; -using SteamWebAPI2.Utilities; -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; +using FlawBOT.Framework.Models; +using FlawBOT.Framework.Properties; +using SteamWebAPI2.Interfaces; +using SteamWebAPI2.Models.GameEconomy; +using SteamWebAPI2.Utilities; using TeamworkTF.Sharp; namespace FlawBOT.Framework.Services { public class TeamFortressService : HttpHandler { - public static List ItemSchemaList { get; set; } = new List(); - public static SteamWebInterfaceFactory SteamInterface; + private static SteamWebInterfaceFactory _steamInterface; + private static List ItemSchemaList { get; set; } = new List(); + + #region NEWS + + public static async Task> GetNewsOverviewAsync(int page = 0, string provider = "") + { + List results; + if (page > 0) + results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsByPageAsync(page) + .ConfigureAwait(false); + else if (provider != string.Empty) + results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsByProviderAsync(provider) + .ConfigureAwait(false); + else + results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsOverviewAsync() + .ConfigureAwait(false); + return results.Where(x => x.Type != "tf2-notification").ToList(); + } + + #endregion NEWS + + #region CREATORS + + public static async Task> GetCreatorByIdAsync(ulong query) + { + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetCreatorByIDAsync(query.ToString()) + .ConfigureAwait(false); + } + + #endregion CREATORS #region SCHEMA public static SchemaItem GetSchemaItem(string query) { - return ItemSchemaList.FirstOrDefault(n => n.ItemName.Contains(query, StringComparison.InvariantCultureIgnoreCase)); + return ItemSchemaList.FirstOrDefault(n => + n.ItemName.Contains(query, StringComparison.InvariantCultureIgnoreCase)); } - public static async Task UpdateTF2SchemaAsync() + public static async Task UpdateTf2SchemaAsync() { try { - SteamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); - var steam = SteamInterface.CreateSteamWebInterface(AppId.TeamFortress2, new HttpClient()); + _steamInterface = new SteamWebInterfaceFactory(TokenHandler.Tokens.SteamToken); + var steam = _steamInterface.CreateSteamWebInterface(AppId.TeamFortress2, new HttpClient()); var games = await steam.GetSchemaItemsForTF2Async().ConfigureAwait(false); ItemSchemaList.Clear(); foreach (var game in games.Data.Result.Items) @@ -38,7 +69,7 @@ public static async Task UpdateTF2SchemaAsync() } catch (Exception ex) { - Console.WriteLine("Error updating TF2 item schema. " + ex.Message); + Console.WriteLine(Resources.ERR_TF2_LIST, ex.Message); return false; } } @@ -47,74 +78,57 @@ public static async Task UpdateTF2SchemaAsync() #region MAPS - public static async Task> GetMapsBySearchAsync(string query) + private static async Task> GetMapsBySearchAsync(string query) { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapsBySearchAsync(query).ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapsBySearchAsync(query) + .ConfigureAwait(false); } public static async Task GetMapStatsAsync(string query) { - var map = GetMapsBySearchAsync(query).Result.FirstOrDefault().Name; - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapStatsAsync(map).ConfigureAwait(false); + var map = GetMapsBySearchAsync(query).Result.FirstOrDefault()?.Name; + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapStatsAsync(map) + .ConfigureAwait(false); } public static async Task GetMapThumbnailAsync(string query) { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapThumbnailAsync(query).ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetMapThumbnailAsync(query) + .ConfigureAwait(false); } #endregion MAPS - #region NEWS - - public static async Task> GetNewsOverviewAsync(int page = 0, string provider = "") - { - var results = new List(); - if (page > 0) - results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsByPageAsync(page).ConfigureAwait(false); - else if (provider != string.Empty) - results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsByProviderAsync(provider).ConfigureAwait(false); - else - results = await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetNewsOverviewAsync().ConfigureAwait(false); - return results.Where(x => x.Type != "tf2-notification").ToList(); - } - - #endregion NEWS - - #region CREATORS - - public static async Task> GetCreatorByIDAsync(ulong query) - { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetCreatorByIDAsync(query.ToString()).ConfigureAwait(false); - } - - #endregion CREATORS - #region SERVERS public static async Task GetGameModeAsync(string query) { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeAsync(query).ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeAsync(query) + .ConfigureAwait(false); } public static async Task GetGameModeListAsync() { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeListAsync().ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeListAsync() + .ConfigureAwait(false); } public static async Task> GetGameModeServerAsync(string query) { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeServerAsync(query).ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameModeServerAsync(query) + .ConfigureAwait(false); } public static async Task> GetGameServerInfoAsync(string ip, int port) { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameServerInfoAsync(ip, port).ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetGameServerInfoAsync(ip, port) + .ConfigureAwait(false); } public static async Task> GetCustomServerListsAsync() { - return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetCustomServerListsAsync().ConfigureAwait(false); + return await new TeamworkClient(TokenHandler.Tokens.TeamworkToken).GetCustomServerListsAsync() + .ConfigureAwait(false); } #endregion SERVERS diff --git a/src/FlawBOT.Framework/Services/Misc/MiscService.cs b/src/FlawBOT.Framework/Services/Misc/MiscService.cs index 8fe5ff91..170c1322 100644 --- a/src/FlawBOT.Framework/Services/Misc/MiscService.cs +++ b/src/FlawBOT.Framework/Services/Misc/MiscService.cs @@ -1,22 +1,16 @@ -using FlawBOT.Framework.Models; +using System; +using System.Collections.Immutable; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using System; -using System.Collections.Immutable; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { public static class EightBallService { - public static string GetRandomAnswer() - { - var random = new Random(); - return Answers[random.Next(Answers.Length)]; - } - - private static ImmutableArray Answers = new[] + private static ImmutableArray _answers = new[] { "It is certain", "It is decidedly so", @@ -39,19 +33,25 @@ public static string GetRandomAnswer() "Outlook not so good", "Very doubtful" }.ToImmutableArray(); + + public static string GetRandomAnswer() + { + var random = new Random(); + return _answers[random.Next(_answers.Length)]; + } } public class CatService : HttpHandler { public static async Task GetCatFactAsync() { - return await _http.GetStringAsync(Resources.API_CatFacts).ConfigureAwait(false); + return await Http.GetStringAsync(Resources.API_CatFacts).ConfigureAwait(false); } public static async Task GetCatPhotoAsync() { - var results = await _http.GetStringAsync(Resources.API_CatPhoto).ConfigureAwait(false); - return JObject.Parse(results)["file"].ToString(); + var results = await Http.GetStringAsync(Resources.API_CatPhoto).ConfigureAwait(false); + return JObject.Parse(results)["file"]?.ToString(); } } @@ -59,7 +59,7 @@ public class DogService : HttpHandler { public static async Task GetDogPhotoAsync() { - var results = await _http.GetStringAsync(Resources.API_DogPhoto).ConfigureAwait(false); + var results = await Http.GetStringAsync(Resources.API_DogPhoto).ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } } diff --git a/src/FlawBOT.Framework/Services/Search/AmiiboService.cs b/src/FlawBOT.Framework/Services/Search/AmiiboService.cs index a3cbcba6..69c58908 100644 --- a/src/FlawBOT.Framework/Services/Search/AmiiboService.cs +++ b/src/FlawBOT.Framework/Services/Search/AmiiboService.cs @@ -1,7 +1,7 @@ -using FlawBOT.Framework.Models; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { @@ -11,7 +11,8 @@ public static async Task GetAmiiboDataAsync(string query) { try { - var results = await _http.GetStringAsync(Resources.API_Amiibo + "?name=" + query.ToLowerInvariant()).ConfigureAwait(false); + var results = await Http.GetStringAsync(Resources.API_Amiibo + "?name=" + query.ToLowerInvariant()) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } catch diff --git a/src/FlawBOT.Framework/Services/Search/BookService.cs b/src/FlawBOT.Framework/Services/Search/BookService.cs index 5351be1b..a18972c1 100644 --- a/src/FlawBOT.Framework/Services/Search/BookService.cs +++ b/src/FlawBOT.Framework/Services/Search/BookService.cs @@ -6,11 +6,9 @@ namespace FlawBOT.Framework.Services { public class BookService : HttpHandler { - private BooksService Books { get; } - public BookService() { - Books = new BooksService(new BaseClientService.Initializer + var booksService = new BooksService(new BaseClientService.Initializer { ApiKey = TokenHandler.Tokens.GoogleToken, ApplicationName = "FlawBOT" diff --git a/src/FlawBOT.Framework/Services/Search/DictionaryService.cs b/src/FlawBOT.Framework/Services/Search/DictionaryService.cs index 995884f7..50892cca 100644 --- a/src/FlawBOT.Framework/Services/Search/DictionaryService.cs +++ b/src/FlawBOT.Framework/Services/Search/DictionaryService.cs @@ -1,8 +1,8 @@ -using FlawBOT.Framework.Models; +using System.Net; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; -using System.Net; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { @@ -10,7 +10,9 @@ public class DictionaryService : HttpHandler { public static async Task GetDictionaryDefinitionAsync(string query) { - var results = await _http.GetStringAsync(Resources.API_Dictionary + "?term=" + WebUtility.UrlEncode(query.Trim())).ConfigureAwait(false); + var results = await Http + .GetStringAsync(Resources.API_Dictionary + "?term=" + WebUtility.UrlEncode(query.Trim())) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } } diff --git a/src/FlawBOT.Framework/Services/Search/GoogleService.cs b/src/FlawBOT.Framework/Services/Search/GoogleService.cs index b70c7975..79a94efd 100644 --- a/src/FlawBOT.Framework/Services/Search/GoogleService.cs +++ b/src/FlawBOT.Framework/Services/Search/GoogleService.cs @@ -1,9 +1,9 @@ -using FlawBOT.Framework.Models; -using FlawBOT.Framework.Properties; -using Newtonsoft.Json; -using System; +using System; using System.Net; using System.Threading.Tasks; +using FlawBOT.Framework.Models; +using FlawBOT.Framework.Properties; +using Newtonsoft.Json; namespace FlawBOT.Framework.Services { @@ -17,10 +17,12 @@ public static async Task GetTimeDataAsync(string query) if (results is null) return null; var latitude = results.Results[0].Geometry.Location.Latitude; var longitude = results.Results[0].Geometry.Location.Longitude; - var currentSeconds = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; - var timeResource = await _http.GetStringAsync(Resources.API_Google_Time + "?location=" + latitude + "," + longitude + "×tamp=" + currentSeconds + "&key=" + TokenHandler.Tokens.GoogleToken).ConfigureAwait(false); + var currentSeconds = (int) DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; + var timeResource = await Http + .GetStringAsync(Resources.API_Google_Time + "?location=" + latitude + "," + longitude + "×tamp=" + currentSeconds + "&key=" + TokenHandler.Tokens.GoogleToken) + .ConfigureAwait(false); results.Timezone = JsonConvert.DeserializeObject(timeResource); - results.Time = DateTime.UtcNow.AddSeconds(results.Timezone.dstOffset + results.Timezone.rawOffset); + results.Time = DateTime.UtcNow.AddSeconds(results.Timezone.DstOffset + results.Timezone.RawOffset); return results; } catch @@ -33,7 +35,8 @@ public static async Task GetWeatherDataAsync(string query) { try { - var results = await _http.GetStringAsync(Resources.API_Google_Weather + "?q=" + query + "&appid=42cd627dd60debf25a5739e50a217d74&units=metric").ConfigureAwait(false); + var results = await Http + .GetStringAsync(Resources.API_Google_Weather + "?q=" + query + "&appid=42cd627dd60debf25a5739e50a217d74&units=metric").ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } catch @@ -42,29 +45,32 @@ public static async Task GetWeatherDataAsync(string query) } } - public async static Task GetLocationGeoData(string query) + private static async Task GetLocationGeoData(string query) { - _http.DefaultRequestHeaders.Clear(); - var result = await _http.GetStringAsync(Resources.API_Google_Geo + "?address=" + query + "&key=" + TokenHandler.Tokens.GoogleToken).ConfigureAwait(false); + Http.DefaultRequestHeaders.Clear(); + var result = await Http + .GetStringAsync(Resources.API_Google_Geo + "?address=" + query + "&key=" + TokenHandler.Tokens.GoogleToken).ConfigureAwait(false); var results = JsonConvert.DeserializeObject(result); - return (results.status == "OK") ? results : null; + return results.Status == "OK" ? results : null; } - public static async Task GetIPLocationAsync(IPAddress query) + public static async Task GetIpLocationAsync(IPAddress query) { - var result = await _http.GetStringAsync(Resources.API_IPLocation + query.ToString()).ConfigureAwait(false); - return JsonConvert.DeserializeObject(result); + var result = await Http.GetStringAsync(Resources.API_IPLocation + query).ConfigureAwait(false); + return JsonConvert.DeserializeObject(result); } public static async Task GetNewsDataAsync(string query = "") { - var results = await _http.GetStringAsync(Resources.API_News + "&q=" + query + "&apiKey=" + TokenHandler.Tokens.NewsToken).ConfigureAwait(false); + var results = await Http + .GetStringAsync(Resources.API_News + "&q=" + query + "&apiKey=" + TokenHandler.Tokens.NewsToken) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results); } public static double CelsiusToFahrenheit(double cel) { - return (cel * 1.8f) + 32; + return cel * 1.8f + 32; } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Search/ImgurService.cs b/src/FlawBOT.Framework/Services/Search/ImgurService.cs index 9eaa5fd7..55446994 100644 --- a/src/FlawBOT.Framework/Services/Search/ImgurService.cs +++ b/src/FlawBOT.Framework/Services/Search/ImgurService.cs @@ -1,11 +1,11 @@ -using FlawBOT.Framework.Models; +using System; +using System.Linq; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using Imgur.API.Authentication.Impl; using Imgur.API.Endpoints.Impl; using Imgur.API.Enums; using Imgur.API.Models; -using System; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { @@ -16,8 +16,10 @@ public static async Task GetImgurGalleryAsync(string query, Galler var random = new Random(); var imgur = new ImgurClient(TokenHandler.Tokens.ImgurToken); var endpoint = new GalleryEndpoint(imgur); - var gallery = string.IsNullOrWhiteSpace(query) ? (await endpoint.GetRandomGalleryAsync().ConfigureAwait(false)).ToList() : (await endpoint.SearchGalleryAsync(query, order, time).ConfigureAwait(false)).ToList(); - return (gallery.Count > 0) ? gallery[random.Next(0, gallery.Count)] : null; + var gallery = string.IsNullOrWhiteSpace(query) + ? (await endpoint.GetRandomGalleryAsync().ConfigureAwait(false)).ToList() + : (await endpoint.SearchGalleryAsync(query, order, time).ConfigureAwait(false)).ToList(); + return gallery.Count > 0 ? gallery[random.Next(0, gallery.Count)] : null; } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Search/NASAService.cs b/src/FlawBOT.Framework/Services/Search/NASAService.cs index 06af8989..b659b94d 100644 --- a/src/FlawBOT.Framework/Services/Search/NASAService.cs +++ b/src/FlawBOT.Framework/Services/Search/NASAService.cs @@ -1,16 +1,17 @@ -using FlawBOT.Framework.Models; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { - public class NASAService : HttpHandler + public class NasaService : HttpHandler { - public static async Task GetNASAImageAsync() + public static async Task GetNasaImageAsync() { - var results = await _http.GetStringAsync(Resources.API_NASA + "?api_key=" + TokenHandler.Tokens.NASAToken).ConfigureAwait(false); - return JsonConvert.DeserializeObject(results); + var results = await Http.GetStringAsync(Resources.API_NASA + "?api_key=" + TokenHandler.Tokens.NasaToken) + .ConfigureAwait(false); + return JsonConvert.DeserializeObject(results); } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Search/OMDBService.cs b/src/FlawBOT.Framework/Services/Search/OMDBService.cs index 9f1a0902..ac8e9829 100644 --- a/src/FlawBOT.Framework/Services/Search/OMDBService.cs +++ b/src/FlawBOT.Framework/Services/Search/OMDBService.cs @@ -1,14 +1,16 @@ -using FlawBOT.Framework.Models; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using OMDbSharp; -using System.Threading.Tasks; +using OMDbSharp.Objects; namespace FlawBOT.Framework.Services { - public static class OMDBService + public static class OmdbService { - public static async Task GetMovieDataAsync(string query) + public static async Task GetMovieDataAsync(string query) { - return await new OMDbClient(TokenHandler.Tokens.OMDBToken, false).GetItemByTitle(query.ToLowerInvariant().Replace("&", "%26")).ConfigureAwait(false); + return await new OMDbClient(TokenHandler.Tokens.OmdbToken, false) + .GetItemByTitle(query.ToLowerInvariant().Replace("&", "%26")).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Search/RedditService.cs b/src/FlawBOT.Framework/Services/Search/RedditService.cs index 684e989a..2b79da14 100644 --- a/src/FlawBOT.Framework/Services/Search/RedditService.cs +++ b/src/FlawBOT.Framework/Services/Search/RedditService.cs @@ -3,6 +3,7 @@ using System.Linq; using System.ServiceModel.Syndication; using System.Xml; +using FlawBOT.Framework.Properties; namespace FlawBOT.Framework.Services { @@ -22,15 +23,15 @@ public static List GetResults(string query, RedditCategory cate } } - public static string GetPostCategory(this RedditCategory category) + private static string GetPostCategory(this RedditCategory category) { - switch (category) + return category switch { - case RedditCategory.Hot: return "hot"; - case RedditCategory.New: return "new"; - case RedditCategory.Top: return "top"; - } - throw new ArgumentException("Unknown reddit category", nameof(category)); + RedditCategory.Hot => "hot", + RedditCategory.New => "new", + RedditCategory.Top => "top", + _ => throw new ArgumentException(Resources.ERR_REDDIT_UNKNOWN_CAT, nameof(category)) + }; } } diff --git a/src/FlawBOT.Framework/Services/Search/SimpsonsService.cs b/src/FlawBOT.Framework/Services/Search/SimpsonsService.cs index 3abc4789..48ef18b0 100644 --- a/src/FlawBOT.Framework/Services/Search/SimpsonsService.cs +++ b/src/FlawBOT.Framework/Services/Search/SimpsonsService.cs @@ -1,50 +1,52 @@ -using DSharpPlus.Entities; +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; using FlawBOT.Framework.Models; using Newtonsoft.Json; -using System.Collections.Generic; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { public class SimpsonsService : HttpHandler { + public enum SiteRoot + { + Frinkiac, + Morbotron, + MasterOfAllScience + } + public static async Task GetSimpsonsDataAsync(SiteRoot site) { - var output = await _http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false); + var output = await Http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false); var results = JsonConvert.DeserializeObject(output); return EmbedSimpsonsEpisode(results, site); } public static async Task GetSimpsonsGifAsync(SiteRoot site) { - var result = await _http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false); + var result = await Http.GetStringAsync($"https://{site}.com/api/random").ConfigureAwait(false); var content = JsonConvert.DeserializeObject(result); - var frames_result = await _http.GetStringAsync($"https://{site}.com/api/frames/{content.Episode.Key}/{content.Frame.Timestamp}/3000/4000").ConfigureAwait(false); - var frames = JsonConvert.DeserializeObject>(frames_result); + var framesResult = await Http + .GetStringAsync($"https://{site}.com/api/frames/{content.Episode.Key}/{content.Frame.Timestamp}/3000/4000") + .ConfigureAwait(false); + var frames = JsonConvert.DeserializeObject>(framesResult); var start = frames[0].Timestamp; - var end = frames[frames.Count - 1].Timestamp; + var end = frames[^1].Timestamp; return $"https://{site}.com/gif/{content.Episode.Key}/{start}/{end}.gif"; } - public static DiscordEmbedBuilder EmbedSimpsonsEpisode(SimpsonsData data, SiteRoot site) + private static DiscordEmbedBuilder EmbedSimpsonsEpisode(SimpsonsData data, SiteRoot site) { var output = new DiscordEmbedBuilder() .WithTitle(data.Episode.Title) .AddField("Season/Episode", data.Episode.Key, true) - .AddField("Writer", (!string.IsNullOrWhiteSpace(data.Episode.Writer)) ? data.Episode.Writer : "Unknown", true) - .AddField("Director", (!string.IsNullOrWhiteSpace(data.Episode.Director)) ? data.Episode.Director : "Unknown", true) + .AddField("Writer", !string.IsNullOrWhiteSpace(data.Episode.Writer) ? data.Episode.Writer : "Unknown",true) + .AddField("Director", !string.IsNullOrWhiteSpace(data.Episode.Director) ? data.Episode.Director : "Unknown", true) .WithFooter("Original Air Date: " + data.Episode.OriginalAirDate) .WithImageUrl($"https://{site}.com/img/{data.Frame.Episode}/{data.Frame.Timestamp}.jpg") .WithColor(new DiscordColor("#FFBB22")) .WithUrl(data.Episode.WikiLink); return output; } - - public enum SiteRoot - { - Frinkiac, - Morbotron, - MasterOfAllScience - } } } \ No newline at end of file diff --git a/src/FlawBOT.Framework/Services/Search/TwitchService.cs b/src/FlawBOT.Framework/Services/Search/TwitchService.cs index 707d2afd..7c7b0ba2 100644 --- a/src/FlawBOT.Framework/Services/Search/TwitchService.cs +++ b/src/FlawBOT.Framework/Services/Search/TwitchService.cs @@ -1,8 +1,8 @@ -using FlawBOT.Framework.Models; +using System.Net.Http; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; -using System.Net.Http; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { @@ -12,7 +12,7 @@ public static async Task GetTwitchDataAsync(string query) { using var request = new HttpRequestMessage(new HttpMethod("GET"), Resources.API_Twitch + "streams?user_login=" + query); request.Headers.TryAddWithoutValidation("Client-ID", TokenHandler.Tokens.TwitchToken); - var response = await _http.SendAsync(request).ConfigureAwait(false); + var response = await Http.SendAsync(request).ConfigureAwait(false); response.EnsureSuccessStatusCode(); var results = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return JsonConvert.DeserializeObject(results); diff --git a/src/FlawBOT.Framework/Services/Search/WikipediaService.cs b/src/FlawBOT.Framework/Services/Search/WikipediaService.cs index 2379fc00..51a42b80 100644 --- a/src/FlawBOT.Framework/Services/Search/WikipediaService.cs +++ b/src/FlawBOT.Framework/Services/Search/WikipediaService.cs @@ -1,8 +1,8 @@ -using FlawBOT.Framework.Models; +using System; +using System.Threading.Tasks; +using FlawBOT.Framework.Models; using FlawBOT.Framework.Properties; using Newtonsoft.Json; -using System; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { @@ -10,7 +10,8 @@ public class WikipediaService : HttpHandler { public static async Task GetWikipediaDataAsync(string query) { - var results = await _http.GetStringAsync(Resources.API_Wikipedia + "&titles=" + Uri.EscapeDataString(query)).ConfigureAwait(false); + var results = await Http.GetStringAsync(Resources.API_Wikipedia + "&titles=" + Uri.EscapeDataString(query)) + .ConfigureAwait(false); return JsonConvert.DeserializeObject(results).Query.Pages[0]; } } diff --git a/src/FlawBOT.Framework/Services/Search/YouTubeService.cs b/src/FlawBOT.Framework/Services/Search/YouTubeService.cs index aa366c6b..f45caada 100644 --- a/src/FlawBOT.Framework/Services/Search/YouTubeService.cs +++ b/src/FlawBOT.Framework/Services/Search/YouTubeService.cs @@ -1,18 +1,16 @@ -using DSharpPlus.Entities; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.Entities; using FlawBOT.Framework.Models; using Google.Apis.Services; using Google.Apis.YouTube.v3; using Google.Apis.YouTube.v3.Data; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace FlawBOT.Framework.Services { public class YoutubeService { - private YouTubeService YouTube { get; } - public YoutubeService() { YouTube = new YouTubeService(new BaseClientService.Initializer @@ -22,6 +20,8 @@ public YoutubeService() }); } + private YouTubeService YouTube { get; } + public async Task GetFirstVideoResultAsync(string query) { var results = await GetResultsAsync(query, 1, "video").ConfigureAwait(false); @@ -38,8 +38,8 @@ public async Task GetEmbeddedResults(string query, int amount, str Description = ":warning: No results found!", Color = DiscordColor.Red }; - results = (results.Count > 25) ? results.Take(25).ToList() : results; - var output = new DiscordEmbedBuilder { Color = DiscordColor.Red }; + results = results.Count > 25 ? results.Take(25).ToList() : results; + var output = new DiscordEmbedBuilder {Color = DiscordColor.Red}; foreach (var result in results) switch (result.Id.Kind) { @@ -58,6 +58,7 @@ public async Task GetEmbeddedResults(string query, int amount, str default: return null; } + return output.Build(); } diff --git a/src/FlawBOT.Framework/Services/Server/BotService.cs b/src/FlawBOT.Framework/Services/Server/BotService.cs index 8c7d3d05..87241adf 100644 --- a/src/FlawBOT.Framework/Services/Server/BotService.cs +++ b/src/FlawBOT.Framework/Services/Server/BotService.cs @@ -1,13 +1,13 @@ -using DSharpPlus.CommandsNext; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using FlawBOT.Framework.Models; -using Newtonsoft.Json; -using System; +using System; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; +using DSharpPlus.CommandsNext; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using FlawBOT.Framework.Models; +using Newtonsoft.Json; namespace FlawBOT.Framework.Services { @@ -42,6 +42,7 @@ public static async Task SendEmbedAsync(CommandContext ctx, string message, Embe color = new DiscordColor("#00FF7F"); break; } + var output = new DiscordEmbedBuilder() .WithDescription(prefix + message) .WithColor(color); @@ -58,53 +59,48 @@ public static async Task SendUserStateChangeAsync(CommandContext ctx, UserStateC public static bool CheckUserInput(string input) { - return (string.IsNullOrWhiteSpace(input)) ? false : true; + return !string.IsNullOrWhiteSpace(input); } public static bool CheckChannelName(string input) { - return (string.IsNullOrWhiteSpace(input) || input.Length > 100) ? false : true; + return !string.IsNullOrWhiteSpace(input) && input.Length <= 100; } public static async Task> GetUserInteractivity(CommandContext ctx, string keyword, int seconds) { - return await ctx.Client.GetInteractivity().WaitForMessageAsync(m => m.Channel.Id == ctx.Channel.Id && string.Equals(m.Content, keyword, StringComparison.InvariantCultureIgnoreCase), TimeSpan.FromSeconds(seconds)).ConfigureAwait(false); + return await ctx.Client.GetInteractivity() + .WaitForMessageAsync( + m => m.Channel.Id == ctx.Channel.Id && string.Equals(m.Content, keyword, StringComparison.InvariantCultureIgnoreCase), + TimeSpan.FromSeconds(seconds)).ConfigureAwait(false); } public static int LimitToRange(int value, int min = 1, int max = 100) { - if (value <= min) { return min; } - if (value >= max) { return max; } - return value; + if (value <= min) return min; + return value >= max ? max : value; } - public static async Task RemoveMessage(DiscordMessage message) + public static async Task RemoveMessage(DiscordMessage message) { - try - { - await message.DeleteAsync().ConfigureAwait(false); - return true; - } - catch - { - return false; - } + await message.DeleteAsync().ConfigureAwait(false); } public static async Task CheckImageInput(CommandContext ctx, string input) { var stream = new MemoryStream(); - if (!Uri.TryCreate(input, UriKind.Absolute, out _) && (!input.EndsWith(".img") || !input.EndsWith(".png") || !input.EndsWith(".jpg"))) - await SendEmbedAsync(ctx, "An image URL ending with .img, .png or .jpg is required!", EmbedType.Warning).ConfigureAwait(false); + if (!Uri.TryCreate(input, UriKind.Absolute, out _) && + (!input.EndsWith(".img") || !input.EndsWith(".png") || !input.EndsWith(".jpg"))) + await SendEmbedAsync(ctx, "An image URL ending with .img, .png or .jpg is required!", EmbedType.Warning) + .ConfigureAwait(false); else { - using (var client = new WebClient()) - { - var results = client.DownloadData(input); - stream.Write(results, 0, results.Length); - stream.Position = 0; - } + using var client = new WebClient(); + var results = client.DownloadData(input); + stream.Write(results, 0, results.Length); + stream.Position = 0; } + return stream; } diff --git a/src/FlawBOT.Test/FlawBOT.Test.csproj b/src/FlawBOT.Test/FlawBOT.Test.csproj index 724f01e8..562d606e 100644 --- a/src/FlawBOT.Test/FlawBOT.Test.csproj +++ b/src/FlawBOT.Test/FlawBOT.Test.csproj @@ -3,9 +3,9 @@ netcoreapp3.1 false - 2.5.0.0 - 2.5.0.0 - 2.6.0 + 2.6.1.0 + 2.6.1.0 + 2.6.1 Igor Nikitin CriticalFlaw FlawBOT @@ -17,7 +17,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/FlawBOT.Test/Games/SteamTests.cs b/src/FlawBOT.Test/Games/SteamTests.cs index d35a94af..f930bbf0 100644 --- a/src/FlawBOT.Test/Games/SteamTests.cs +++ b/src/FlawBOT.Test/Games/SteamTests.cs @@ -1,6 +1,6 @@ -using FlawBOT.Framework.Services; +using System.Text.RegularExpressions; +using FlawBOT.Framework.Services; using NUnit.Framework; -using System.Text.RegularExpressions; namespace GamesModule { @@ -22,11 +22,5 @@ public void GetSteamProfile() Assert.IsNull(SteamService.GetSteamProfileAsync("99999999999999999").Result); Assert.IsNull(SteamService.GetSteamSummaryAsync("99999999999999999").Result); } - - [Test] - public void UpdateSteamList() - { - Assert.IsTrue(SteamService.UpdateSteamListAsync().Result); - } } } \ No newline at end of file diff --git a/src/FlawBOT.Test/Games/TeamFortressTests.cs b/src/FlawBOT.Test/Games/TeamFortressTests.cs index 99dde5f1..069e4f61 100644 --- a/src/FlawBOT.Test/Games/TeamFortressTests.cs +++ b/src/FlawBOT.Test/Games/TeamFortressTests.cs @@ -11,7 +11,7 @@ public void GetMapStats() { Assert.IsNotNull(TeamFortressService.GetMapStatsAsync("pl_upward").Result); Assert.IsNotNull(TeamFortressService.GetMapStatsAsync("upward").Result); - Assert.IsNull(TeamFortressService.GetMapStatsAsync("onpward").Result); + Assert.IsNull(TeamFortressService.GetMapStatsAsync("bonewards").Result); } [Test] @@ -20,7 +20,8 @@ public void GetNewsOverview() Assert.IsNotNull(TeamFortressService.GetNewsOverviewAsync().Result); } - [Test, Order(2)] + [Test] + [Order(2)] public void GetSchemaItem() { Assert.IsNotNull(TeamFortressService.GetSchemaItem("scattergun")); @@ -34,10 +35,11 @@ public void GetServers() Assert.IsNull(TeamFortressService.GetGameModeServerAsync("payloader").Result); } - [Test, Order(1)] - public void UpdateTF2Schema() + [Test] + [Order(1)] + public void UpdateTf2Schema() { - Assert.IsTrue(TeamFortressService.UpdateTF2SchemaAsync().Result); + Assert.IsTrue(TeamFortressService.UpdateTf2SchemaAsync().Result); } } } \ No newline at end of file diff --git a/src/FlawBOT.Test/Misc/MiscTests.cs b/src/FlawBOT.Test/Misc/MiscTests.cs index 40c02940..b39cade3 100644 --- a/src/FlawBOT.Test/Misc/MiscTests.cs +++ b/src/FlawBOT.Test/Misc/MiscTests.cs @@ -1,6 +1,6 @@ -using FlawBOT.Framework.Services; +using System.Net; +using FlawBOT.Framework.Services; using NUnit.Framework; -using System.Net; namespace MiscModule { @@ -20,9 +20,9 @@ public void GetDogPhoto() } [Test] - public void GetIPLocation() + public void GetIpLocation() { - Assert.IsTrue(GoogleService.GetIPLocationAsync(IPAddress.Parse("123.123.123.123")).Result.Status == "success"); + Assert.IsTrue(GoogleService.GetIpLocationAsync(IPAddress.Parse("123.123.123.123")).Result.Status == "success"); } [Test] diff --git a/src/FlawBOT.Test/Search/GoogleTests.cs b/src/FlawBOT.Test/Search/GoogleTests.cs index a84817e4..dfae428d 100644 --- a/src/FlawBOT.Test/Search/GoogleTests.cs +++ b/src/FlawBOT.Test/Search/GoogleTests.cs @@ -16,7 +16,7 @@ public void GetNewsData() [Test] public void GetTimeData() { - Assert.IsNotNull(GoogleService.GetTimeDataAsync("Ottawa").Result.status); + Assert.IsNotNull(GoogleService.GetTimeDataAsync("Ottawa").Result.Status); Assert.IsNull(GoogleService.GetTimeDataAsync("Ottura").Result); } diff --git a/src/FlawBOT.Test/Search/ImgurTests.cs b/src/FlawBOT.Test/Search/ImgurTests.cs index 5eedcda9..439ff309 100644 --- a/src/FlawBOT.Test/Search/ImgurTests.cs +++ b/src/FlawBOT.Test/Search/ImgurTests.cs @@ -1,7 +1,6 @@ -using FlawBOT.Framework.Services; -using Imgur.API.Enums; +using System.Threading.Tasks; +using FlawBOT.Framework.Services; using NUnit.Framework; -using System.Threading.Tasks; namespace SearchModule { @@ -11,10 +10,10 @@ internal class ImgurTests [Test] public async Task GetImgurGalleryData() { - var results = await ImgurService.GetImgurGalleryAsync("cats", GallerySortOrder.Top, TimeWindow.All).ConfigureAwait(false); + var results = await ImgurService.GetImgurGalleryAsync("cats").ConfigureAwait(false); Assert.IsNotNull(results); - results = await ImgurService.GetImgurGalleryAsync("dogs", GallerySortOrder.Top, TimeWindow.All).ConfigureAwait(false); + results = await ImgurService.GetImgurGalleryAsync("dogs").ConfigureAwait(false); Assert.IsNotNull(results); } } diff --git a/src/FlawBOT.Test/Search/NASATests.cs b/src/FlawBOT.Test/Search/NASATests.cs index e4fcd16f..91aab286 100644 --- a/src/FlawBOT.Test/Search/NASATests.cs +++ b/src/FlawBOT.Test/Search/NASATests.cs @@ -4,12 +4,12 @@ namespace SearchModule { [TestFixture] - internal class NASATests + internal class NasaTests { [Test] - public void GetNASAData() + public void GetNasaData() { - Assert.IsNotNull(NASAService.GetNASAImageAsync().Result); + Assert.IsNotNull(NasaService.GetNasaImageAsync().Result); } } } \ No newline at end of file diff --git a/src/FlawBOT.Test/Search/OMDBTests.cs b/src/FlawBOT.Test/Search/OMDBTests.cs index bdd79d12..432f7d24 100644 --- a/src/FlawBOT.Test/Search/OMDBTests.cs +++ b/src/FlawBOT.Test/Search/OMDBTests.cs @@ -4,12 +4,12 @@ namespace SearchModule { [TestFixture] - internal class OMDBTests + internal class OmdbTests { [Test] public void GetMovieData() { - Assert.IsNotNull(OMDBService.GetMovieDataAsync("office+space").Result); + Assert.IsNotNull(OmdbService.GetMovieDataAsync("office+space").Result); } } } \ No newline at end of file diff --git a/src/FlawBOT.Test/TestSetup.cs b/src/FlawBOT.Test/TestSetup.cs index 54cc52c0..37ba0800 100644 --- a/src/FlawBOT.Test/TestSetup.cs +++ b/src/FlawBOT.Test/TestSetup.cs @@ -1,8 +1,8 @@ -using FlawBOT.Framework.Models; +using System.IO; +using System.Text; +using FlawBOT.Framework.Models; using Newtonsoft.Json; using NUnit.Framework; -using System.IO; -using System.Text; namespace GamesModule {