diff --git a/Geekbot.net/Commands/Admin.cs b/Geekbot.net/Commands/Admin.cs index 4e94673..481eab1 100644 --- a/Geekbot.net/Commands/Admin.cs +++ b/Geekbot.net/Commands/Admin.cs @@ -40,7 +40,7 @@ namespace Geekbot.net.Commands [Command("modchannel", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Set a channel for moderation purposes")] - public async Task selectModChannel([Summary("#Channel")] ISocketMessageChannel channel) + public async Task SelectModChannel([Summary("#Channel")] ISocketMessageChannel channel) { try { @@ -61,7 +61,7 @@ namespace Geekbot.net.Commands [Command("showleave", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Notify modchannel when someone leaves")] - public async Task showLeave([Summary("true/false")] bool enabled) + public async Task ShowLeave([Summary("true/false")] bool enabled) { var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel")); try @@ -88,7 +88,7 @@ namespace Geekbot.net.Commands [Command("showdel", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Notify modchannel when someone deletes a message")] - public async Task showDelete([Summary("true/false")] bool enabled) + public async Task ShowDelete([Summary("true/false")] bool enabled) { var modChannelId = ulong.Parse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ModChannel")); try @@ -117,7 +117,7 @@ namespace Geekbot.net.Commands [Command("setlang", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Change the bots language")] - public async Task setLanguage([Summary("language")] string languageRaw) + public async Task SetLanguage([Summary("language")] string languageRaw) { try { @@ -142,7 +142,7 @@ namespace Geekbot.net.Commands [Command("wiki", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Change the wikipedia instance (use lang code in xx.wikipedia.org)")] - public async Task setWikiLanguage([Summary("language")] string languageRaw) + public async Task SetWikiLanguage([Summary("language")] string languageRaw) { try { @@ -160,7 +160,7 @@ namespace Geekbot.net.Commands [Command("lang", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Change the bots language")] - public async Task getLanguage() + public async Task GetLanguage() { try { @@ -176,12 +176,12 @@ namespace Geekbot.net.Commands [Command("ping", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Enable the ping reply.")] - public async Task togglePing() + public async Task TogglePing() { try { bool.TryParse(_redis.HashGet($"{Context.Guild.Id}:Settings", "ping"), out var current); - _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ping", current ? "false" : "true"), }); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ping", current ? "false" : "true") }); await ReplyAsync(!current ? "i will reply to ping now" : "No more pongs..."); } catch (Exception e) diff --git a/Geekbot.net/Commands/AvatarGetter.cs b/Geekbot.net/Commands/AvatarGetter.cs index 9e31b6b..d8a04e9 100644 --- a/Geekbot.net/Commands/AvatarGetter.cs +++ b/Geekbot.net/Commands/AvatarGetter.cs @@ -18,7 +18,7 @@ namespace Geekbot.net.Commands [Command("avatar", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Get someones avatar")] - public async Task getAvatar([Remainder] [Summary("user")] IUser user = null) + public async Task GetAvatar([Remainder] [Summary("user")] IUser user = null) { try { diff --git a/Geekbot.net/Commands/BattleTag.cs b/Geekbot.net/Commands/BattleTag.cs index cbc5ecc..eb6fca1 100644 --- a/Geekbot.net/Commands/BattleTag.cs +++ b/Geekbot.net/Commands/BattleTag.cs @@ -24,7 +24,7 @@ namespace Geekbot.net.Commands { try { - var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag"); + var tag = _userRepository.GetUserSetting(Context.User.Id, "BattleTag"); if (!string.IsNullOrEmpty(tag)) await ReplyAsync($"Your BattleTag is {tag}"); else @@ -43,9 +43,9 @@ namespace Geekbot.net.Commands { try { - if (isValidTag(tag)) + if (IsValidTag(tag)) { - _userRepository.saveUserSetting(Context.User.Id, "BattleTag", tag); + _userRepository.SaveUserSetting(Context.User.Id, "BattleTag", tag); await ReplyAsync("Saved!"); } else @@ -59,13 +59,12 @@ namespace Geekbot.net.Commands } } - public static bool isValidTag(string tag) + public static bool IsValidTag(string tag) { var splited = tag.Split("#"); if (splited.Length != 2) return false; if (!int.TryParse(splited[1], out var discriminator)) return false; - if (splited[1].Length == 4 || splited[1].Length == 5) return true; - return false; + return splited[1].Length == 4 || splited[1].Length == 5; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Cat.cs b/Geekbot.net/Commands/Cat.cs index 1f97d5a..0545894 100644 --- a/Geekbot.net/Commands/Cat.cs +++ b/Geekbot.net/Commands/Cat.cs @@ -35,7 +35,7 @@ namespace Geekbot.net.Commands var stringResponse = await response.Content.ReadAsStringAsync(); var catFile = JsonConvert.DeserializeObject(stringResponse); var eb = new EmbedBuilder(); - eb.ImageUrl = catFile.file; + eb.ImageUrl = catFile.File; await ReplyAsync("", false, eb.Build()); } catch @@ -52,7 +52,7 @@ namespace Geekbot.net.Commands private class CatResponse { - public string file { get; set; } + public string File { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Changelog.cs b/Geekbot.net/Commands/Changelog.cs index e060152..70c4c17 100644 --- a/Geekbot.net/Commands/Changelog.cs +++ b/Geekbot.net/Commands/Changelog.cs @@ -27,7 +27,7 @@ namespace Geekbot.net.Commands [Alias("updates")] [Remarks(CommandCategories.Helpers)] [Summary("Show the latest 5 updates")] - public async Task getChangelog() + public async Task GetChangelog() { try { @@ -40,7 +40,7 @@ namespace Geekbot.net.Commands response.EnsureSuccessStatusCode(); var stringResponse = await response.Content.ReadAsStringAsync(); - var commits = JsonConvert.DeserializeObject>(stringResponse); + var commits = JsonConvert.DeserializeObject>(stringResponse); var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 165, 102)); eb.WithAuthor(new EmbedAuthorBuilder @@ -51,7 +51,7 @@ namespace Geekbot.net.Commands }); var sb = new StringBuilder(); foreach (var commit in commits.Take(10)) - sb.AppendLine($"- {commit.commit.message} ({commit.commit.author.date:yyyy-MM-dd})"); + sb.AppendLine($"- {commit.Commit.Message} ({commit.Commit.Author.Date:yyyy-MM-dd})"); eb.Description = sb.ToString(); eb.WithFooter(new EmbedFooterBuilder { @@ -66,24 +66,20 @@ namespace Geekbot.net.Commands } } - private class Commit + private class CommitDto { - public string sha { get; set; } - public CommitInfo commit { get; set; } - public Uri html_url { get; set; } + public CommitInfo Commit { get; set; } } private class CommitInfo { - public commitAuthor author { get; set; } - public string message { get; set; } + public CommitAuthor Author { get; set; } + public string Message { get; set; } } - private class commitAuthor + private class CommitAuthor { - public string name { get; set; } - public string email { get; set; } - public DateTimeOffset date { get; set; } + public DateTimeOffset Date { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/CheckEm.cs b/Geekbot.net/Commands/CheckEm.cs index 61de091..67df682 100644 --- a/Geekbot.net/Commands/CheckEm.cs +++ b/Geekbot.net/Commands/CheckEm.cs @@ -46,7 +46,7 @@ namespace Geekbot.net.Commands sb.AppendLine($"**{number}**"); if (!string.IsNullOrEmpty(dubtriqua)) sb.AppendLine($":tada: {dubtriqua} :tada:"); - sb.AppendLine(_checkEmImages.getCheckem()); + sb.AppendLine(_checkEmImages.GetCheckem()); await ReplyAsync(sb.ToString()); } diff --git a/Geekbot.net/Commands/ChuckNorrisJokes.cs b/Geekbot.net/Commands/ChuckNorrisJokes.cs index 1ac6c4d..1c3b009 100644 --- a/Geekbot.net/Commands/ChuckNorrisJokes.cs +++ b/Geekbot.net/Commands/ChuckNorrisJokes.cs @@ -35,7 +35,7 @@ namespace Geekbot.net.Commands var stringResponse = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.value); + await ReplyAsync(data.Value); } catch (HttpRequestException) { @@ -51,11 +51,7 @@ namespace Geekbot.net.Commands private class ChuckNorrisJokeResponse { - public string category { get; set; } - public string icon_url { get; set; } - public string id { get; set; } - public string url { get; set; } - public string value { get; set; } + public string Value { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/DadJokes.cs b/Geekbot.net/Commands/DadJokes.cs index 615f3d5..897c3e0 100644 --- a/Geekbot.net/Commands/DadJokes.cs +++ b/Geekbot.net/Commands/DadJokes.cs @@ -2,7 +2,6 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; -using Discord; using Discord.Commands; using Geekbot.net.Lib; using Newtonsoft.Json; @@ -36,7 +35,7 @@ namespace Geekbot.net.Commands var stringResponse = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(stringResponse); - await ReplyAsync(data.joke); + await ReplyAsync(data.Joke); } catch (HttpRequestException) { @@ -52,9 +51,7 @@ namespace Geekbot.net.Commands private class DadJokeResponse { - public string id { get; set; } - public string joke { get; set; } - public string status { get; set; } + public string Joke { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Dice.cs b/Geekbot.net/Commands/Dice.cs index 774f8b9..89b3a11 100644 --- a/Geekbot.net/Commands/Dice.cs +++ b/Geekbot.net/Commands/Dice.cs @@ -20,12 +20,12 @@ namespace Geekbot.net.Commands var mod = 0; foreach (var i in splitedDices) { - var dice = toDice(i); - if (dice.sides != 0 && dice.times != 0) + var dice = ToDice(i); + if (dice.Sides != 0 && dice.Times != 0) { dices.Add(dice); } - else if (dice.mod != 0) + else if (dice.Mod != 0) { if (mod != 0) { @@ -33,7 +33,7 @@ namespace Geekbot.net.Commands return; } - mod = dice.mod; + mod = dice.Mod; } } @@ -45,13 +45,13 @@ namespace Geekbot.net.Commands } - if (dices.Any(d => d.times > 20)) + if (dices.Any(d => d.Times > 20)) { await ReplyAsync("You can't throw more than 20 dices"); return; } - if (dices.Any(d => d.sides > 120)) + if (dices.Any(d => d.Sides > 120)) { await ReplyAsync("A dice can't have more than 120 sides"); return; @@ -66,16 +66,16 @@ namespace Geekbot.net.Commands foreach (var dice in dices) { var results = new List(); - for (var i = 0; i < dice.times; i++) + for (var i = 0; i < dice.Times; i++) { - var roll = new Random().Next(1, dice.sides); + var roll = new Random().Next(1, dice.Sides); total += roll; results.Add(roll); - if (roll == dice.sides) extraText = "**Critical Hit!**"; + if (roll == dice.Sides) extraText = "**Critical Hit!**"; if (roll == 1) extraText = "**Critical Fail!**"; } - resultStrings.Add($"{dice.diceType} ({string.Join(",", results)})"); + resultStrings.Add($"{dice.DiceType} ({string.Join(",", results)})"); } rep.Append(string.Join(" + ", resultStrings)); @@ -91,7 +91,7 @@ namespace Geekbot.net.Commands await ReplyAsync(rep.ToString()); } - private DiceTypeDto toDice(string dice) + private DiceTypeDto ToDice(string dice) { var diceParts = dice.Split('d'); if (diceParts.Length == 2 @@ -99,15 +99,15 @@ namespace Geekbot.net.Commands && int.TryParse(diceParts[1], out var max)) return new DiceTypeDto { - diceType = dice, - times = times, - sides = max + DiceType = dice, + Times = times, + Sides = max }; if (dice.Length == 1 && int.TryParse(diceParts[0], out var mod)) return new DiceTypeDto { - mod = mod + Mod = mod }; return new DiceTypeDto(); } @@ -115,9 +115,9 @@ namespace Geekbot.net.Commands internal class DiceTypeDto { - public string diceType { get; set; } - public int times { get; set; } - public int sides { get; set; } - public int mod { get; set; } + public string DiceType { get; set; } + public int Times { get; set; } + public int Sides { get; set; } + public int Mod { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Dog.cs b/Geekbot.net/Commands/Dog.cs index 485b7f0..30c0301 100644 --- a/Geekbot.net/Commands/Dog.cs +++ b/Geekbot.net/Commands/Dog.cs @@ -35,7 +35,7 @@ namespace Geekbot.net.Commands var stringResponse = await response.Content.ReadAsStringAsync(); var dogFile = JsonConvert.DeserializeObject(stringResponse); var eb = new EmbedBuilder(); - eb.ImageUrl = dogFile.url; + eb.ImageUrl = dogFile.Url; await ReplyAsync("", false, eb.Build()); } catch (HttpRequestException e) @@ -52,7 +52,7 @@ namespace Geekbot.net.Commands private class DogResponse { - public string url { get; set; } + public string Url { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Emojify.cs b/Geekbot.net/Commands/Emojify.cs index 7bdbf8a..739a4dc 100644 --- a/Geekbot.net/Commands/Emojify.cs +++ b/Geekbot.net/Commands/Emojify.cs @@ -23,7 +23,7 @@ namespace Geekbot.net.Commands { try { - var emojis = _emojiConverter.textToEmoji(text); + var emojis = _emojiConverter.TextToEmoji(text); if (emojis.Length > 1999) { await ReplyAsync("I can't take that much at once!"); diff --git a/Geekbot.net/Commands/Gdq.cs b/Geekbot.net/Commands/Gdq.cs index b191d6c..fef1c96 100644 --- a/Geekbot.net/Commands/Gdq.cs +++ b/Geekbot.net/Commands/Gdq.cs @@ -1,8 +1,6 @@ using System; -using System.Linq; using System.Net; using System.Threading.Tasks; -using Discord; using Discord.Commands; using Geekbot.net.Lib; @@ -20,7 +18,7 @@ namespace Geekbot.net.Commands [Command("gdq", RunMode = RunMode.Async)] [Remarks(CommandCategories.Games)] [Summary("Get a quote from the GDQ donation generator.")] - public async Task getQuote() + public async Task GetQuote() { try { diff --git a/Geekbot.net/Commands/Google.cs b/Geekbot.net/Commands/Google.cs index b10bc02..19d3efb 100644 --- a/Geekbot.net/Commands/Google.cs +++ b/Geekbot.net/Commands/Google.cs @@ -2,14 +2,12 @@ using System.Collections.Generic; using System.Linq; using System.Net; -using System.Net.Http; using System.Threading.Tasks; using Discord; using Discord.Commands; -using Discord.Net; using Geekbot.net.Lib; -using Newtonsoft.Json; using StackExchange.Redis; +using Utf8Json; namespace Geekbot.net.Commands { @@ -27,7 +25,7 @@ namespace Geekbot.net.Commands [Command("google", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Google Something.")] - public async Task askGoogle([Remainder, Summary("SearchText")] string searchText) + public async Task AskGoogle([Remainder, Summary("SearchText")] string searchText) { try { @@ -42,21 +40,21 @@ namespace Geekbot.net.Commands var url = new Uri($"https://kgsearch.googleapis.com/v1/entities:search?languages=en&limit=1&query={searchText}&key={apiKey}"); var responseString = client.DownloadString(url); - var response = Utf8Json.JsonSerializer.Deserialize(responseString); + var response = JsonSerializer.Deserialize(responseString); - if (!response.itemListElement.Any()) + if (!response.ItemListElement.Any()) { await ReplyAsync("No results were found..."); return; } - var data = response.itemListElement.First().result; + var data = response.ItemListElement.First().Result; var eb = new EmbedBuilder(); - eb.Title = data.name; - if(!string.IsNullOrEmpty(data.description)) eb.WithDescription(data.description); - if(!string.IsNullOrEmpty(data.detailedDescription?.url)) eb.WithUrl(data.detailedDescription.url); - if(!string.IsNullOrEmpty(data.detailedDescription?.articleBody)) eb.AddField("Details", data.detailedDescription.articleBody); - if(!string.IsNullOrEmpty(data.image?.contentUrl)) eb.WithThumbnailUrl(data.image.contentUrl); + eb.Title = data.Name; + if(!string.IsNullOrEmpty(data.Description)) eb.WithDescription(data.Description); + if(!string.IsNullOrEmpty(data.DetailedDescription?.Url)) eb.WithUrl(data.DetailedDescription.Url); + if(!string.IsNullOrEmpty(data.DetailedDescription?.ArticleBody)) eb.AddField("Details", data.DetailedDescription.ArticleBody); + if(!string.IsNullOrEmpty(data.Image?.ContentUrl)) eb.WithThumbnailUrl(data.Image.ContentUrl); await ReplyAsync("", false, eb.Build()); } @@ -67,35 +65,35 @@ namespace Geekbot.net.Commands } } - public class GoogleKGApiResponse + public class GoogleKgApiResponse { - public List itemListElement { get; set; } + public List ItemListElement { get; set; } - public class GoogleKGApiElement + public class GoogleKgApiElement { - public GoogleKGApiResult result { get; set; } - public double resultScore { get; set; } + public GoogleKgApiResult Result { get; set; } + public double ResultScore { get; set; } } - public class GoogleKGApiResult + public class GoogleKgApiResult { - public string name { get; set; } - public string description { get; set; } - public GoogleKGApiImage image { get; set; } - public GoogleKGApiDetailed detailedDescription { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public GoogleKgApiImage Image { get; set; } + public GoogleKgApiDetailed DetailedDescription { get; set; } } - public class GoogleKGApiImage + public class GoogleKgApiImage { - public string contentUrl { get; set; } - public string url { get; set; } + public string ContentUrl { get; set; } + public string Url { get; set; } } - public class GoogleKGApiDetailed + public class GoogleKgApiDetailed { - public string articleBody { get; set; } - public string url { get; set; } - public string license { get; set; } + public string ArticleBody { get; set; } + public string Url { get; set; } + public string License { get; set; } } } } diff --git a/Geekbot.net/Commands/GuildInfo.cs b/Geekbot.net/Commands/GuildInfo.cs index 2ca76c6..62e0fd1 100644 --- a/Geekbot.net/Commands/GuildInfo.cs +++ b/Geekbot.net/Commands/GuildInfo.cs @@ -24,7 +24,7 @@ namespace Geekbot.net.Commands [Command("serverstats", RunMode = RunMode.Async)] [Remarks(CommandCategories.Statistics)] [Summary("Show some info about the bot.")] - public async Task getInfo() + public async Task GetInfo() { try { diff --git a/Geekbot.net/Commands/Karma.cs b/Geekbot.net/Commands/Karma.cs index 1affa82..d379b06 100644 --- a/Geekbot.net/Commands/Karma.cs +++ b/Geekbot.net/Commands/Karma.cs @@ -110,9 +110,7 @@ namespace Geekbot.net.Commands private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString) { - if (string.IsNullOrEmpty(dateTimeOffsetString)) - return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)); - return DateTimeOffset.Parse(dateTimeOffsetString); + return string.IsNullOrEmpty(dateTimeOffsetString) ? DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)) : DateTimeOffset.Parse(dateTimeOffsetString); } private bool TimeoutFinished(DateTimeOffset lastKarma) diff --git a/Geekbot.net/Commands/MagicTheGathering.cs b/Geekbot.net/Commands/MagicTheGathering.cs index 044c287..9c7379f 100644 --- a/Geekbot.net/Commands/MagicTheGathering.cs +++ b/Geekbot.net/Commands/MagicTheGathering.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord; using Discord.Commands; @@ -24,7 +23,7 @@ namespace Geekbot.net.Commands [Command("mtg", RunMode = RunMode.Async)] [Remarks(CommandCategories.Games)] [Summary("Find a Magic The Gathering Card.")] - public async Task getCard([Remainder] [Summary("name")] string cardName) + public async Task GetCard([Remainder] [Summary("name")] string cardName) { try { diff --git a/Geekbot.net/Commands/Mod.cs b/Geekbot.net/Commands/Mod.cs index c927b0d..e8751f6 100644 --- a/Geekbot.net/Commands/Mod.cs +++ b/Geekbot.net/Commands/Mod.cs @@ -32,7 +32,7 @@ namespace Geekbot.net.Commands [Command("namehistory", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("See past usernames of an user")] - public async Task usernameHistory([Summary("@user")] IUser user) + public async Task UsernameHistory([Summary("@user")] IUser user) { try { @@ -52,7 +52,7 @@ namespace Geekbot.net.Commands [Command("kick", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Ban a user")] - public async Task kick([Summary("@user")] IUser userNormal, + public async Task Kick([Summary("@user")] IUser userNormal, [Summary("reason")] [Remainder] string reason = "none") { try diff --git a/Geekbot.net/Commands/Overwatch.cs b/Geekbot.net/Commands/Overwatch.cs index fbb9699..0a39662 100644 --- a/Geekbot.net/Commands/Overwatch.cs +++ b/Geekbot.net/Commands/Overwatch.cs @@ -5,7 +5,6 @@ using Discord.Commands; using Geekbot.net.Lib; using OverwatchAPI; using OverwatchAPI.Config; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Commands @@ -16,7 +15,7 @@ namespace Geekbot.net.Commands private readonly IErrorHandler _errorHandler; private readonly IUserRepository _userRepository; - public Overwatch(IErrorHandler errorHandler, IDatabase redis, IUserRepository userRepository) + public Overwatch(IErrorHandler errorHandler, IUserRepository userRepository) { _errorHandler = errorHandler; _userRepository = userRepository; @@ -25,18 +24,18 @@ namespace Geekbot.net.Commands [Command("profile", RunMode = RunMode.Async)] [Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")] [Remarks(CommandCategories.Games)] - public async Task owProfile() + public async Task OwProfile() { try { - var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag"); + var tag = _userRepository.GetUserSetting(Context.User.Id, "BattleTag"); if (string.IsNullOrEmpty(tag)) { await ReplyAsync("You have no battle Tag saved, use `!battletag`"); return; } - var profile = await createProfile(tag); + var profile = await CreateProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); @@ -54,17 +53,17 @@ namespace Geekbot.net.Commands [Command("profile", RunMode = RunMode.Async)] [Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")] [Remarks(CommandCategories.Games)] - public async Task owProfile([Summary("BattleTag")] string tag) + public async Task OwProfile([Summary("BattleTag")] string tag) { try { - if (!BattleTag.isValidTag(tag)) + if (!BattleTag.IsValidTag(tag)) { await ReplyAsync("That doesn't seem to be a valid battletag..."); return; } - var profile = await createProfile(tag); + var profile = await CreateProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); @@ -82,18 +81,18 @@ namespace Geekbot.net.Commands [Command("profile", RunMode = RunMode.Async)] [Summary("Get someones overwatch profile. EU on PC only.")] [Remarks(CommandCategories.Games)] - public async Task owProfile([Summary("@someone")] IUser user) + public async Task OwProfile([Summary("@someone")] IUser user) { try { - var tag = _userRepository.getUserSetting(user.Id, "BattleTag"); + var tag = _userRepository.GetUserSetting(user.Id, "BattleTag"); if (string.IsNullOrEmpty(tag)) { await ReplyAsync("This user didn't set a battletag"); return; } - var profile = await createProfile(tag); + var profile = await CreateProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); @@ -108,7 +107,7 @@ namespace Geekbot.net.Commands } } - private async Task createProfile(string battletag) + private async Task CreateProfile(string battletag) { var owConfig = new OverwatchConfig.Builder().WithPlatforms(Platform.Pc); using (var owClient = new OverwatchClient(owConfig)) diff --git a/Geekbot.net/Commands/Owner.cs b/Geekbot.net/Commands/Owner.cs index c4adb25..b73797f 100644 --- a/Geekbot.net/Commands/Owner.cs +++ b/Geekbot.net/Commands/Owner.cs @@ -4,7 +4,6 @@ using Discord; using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Lib; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Commands @@ -68,7 +67,7 @@ namespace Geekbot.net.Commands [Command("popuserrepo", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Populate user cache")] - public async Task popUserRepoCommand() + public async Task PopUserRepoCommand() { try { @@ -82,8 +81,7 @@ namespace Geekbot.net.Commands } catch (Exception) { - await ReplyAsync( - $"Sorry, only the botowner can do this"); + await ReplyAsync("Sorry, only the botowner can do this"); return; } diff --git a/Geekbot.net/Commands/Pokedex.cs b/Geekbot.net/Commands/Pokedex.cs index 2b43693..fa8746f 100644 --- a/Geekbot.net/Commands/Pokedex.cs +++ b/Geekbot.net/Commands/Pokedex.cs @@ -36,7 +36,7 @@ namespace Geekbot.net.Commands return; } - var embed = await pokemonEmbedBuilder(pokemon); + var embed = await PokemonEmbedBuilder(pokemon); await ReplyAsync("", false, embed.Build()); } catch (Exception e) @@ -45,29 +45,29 @@ namespace Geekbot.net.Commands } } - private async Task pokemonEmbedBuilder(Pokemon pokemon) + private async Task PokemonEmbedBuilder(Pokemon pokemon) { var eb = new EmbedBuilder(); var species = await DataFetcher.GetApiObject(pokemon.ID); - eb.Title = $"#{pokemon.ID} {toUpper(pokemon.Name)}"; + eb.Title = $"#{pokemon.ID} {ToUpper(pokemon.Name)}"; eb.Description = species.FlavorTexts[1].FlavorText; eb.ThumbnailUrl = pokemon.Sprites.FrontMale ?? pokemon.Sprites.FrontFemale; - eb.AddInlineField(getSingularOrPlural(pokemon.Types.Length, "Type"), - string.Join(", ", pokemon.Types.Select(t => toUpper(t.Type.Name)))); - eb.AddInlineField(getSingularOrPlural(pokemon.Abilities.Length, "Ability"), - string.Join(", ", pokemon.Abilities.Select(t => toUpper(t.Ability.Name)))); + eb.AddInlineField(GetSingularOrPlural(pokemon.Types.Length, "Type"), + string.Join(", ", pokemon.Types.Select(t => ToUpper(t.Type.Name)))); + eb.AddInlineField(GetSingularOrPlural(pokemon.Abilities.Length, "Ability"), + string.Join(", ", pokemon.Abilities.Select(t => ToUpper(t.Ability.Name)))); eb.AddInlineField("Height", pokemon.Height); eb.AddInlineField("Weight", pokemon.Mass); return eb; } - private string getSingularOrPlural(int lenght, string word) + private string GetSingularOrPlural(int lenght, string word) { if (lenght == 1) return word; return word.EndsWith("y") ? $"{word.Remove(word.Length - 1)}ies" : $"{word}s"; } - private string toUpper(string s) + private string ToUpper(string s) { if (string.IsNullOrEmpty(s)) return string.Empty; return char.ToUpper(s[0]) + s.Substring(1); diff --git a/Geekbot.net/Commands/Poll.cs b/Geekbot.net/Commands/Poll.cs index 51b6742..cf80835 100644 --- a/Geekbot.net/Commands/Poll.cs +++ b/Geekbot.net/Commands/Poll.cs @@ -82,14 +82,14 @@ namespace Geekbot.net.Commands var i = 1; pollList.ForEach(option => { - eb.AddInlineField($"Option {_emojiConverter.numberToEmoji(i)}", option); + eb.AddInlineField($"Option {_emojiConverter.NumberToEmoji(i)}", option); i++; }); var pollMessage = await ReplyAsync("", false, eb.Build()); i = 1; pollList.ForEach(option => { - pollMessage.AddReactionAsync(new Emoji(_emojiConverter.numberToEmoji(i))); + pollMessage.AddReactionAsync(new Emoji(_emojiConverter.NumberToEmoji(i))); i++; }); var poll = new PollData @@ -123,7 +123,7 @@ namespace Geekbot.net.Commands return; } - var results = await getPollResults(currentPoll); + var results = await GetPollResults(currentPoll); var sb = new StringBuilder(); sb.AppendLine("**Poll Results**"); sb.AppendLine(currentPoll.Question); @@ -152,7 +152,7 @@ namespace Geekbot.net.Commands } } - private async Task> getPollResults(PollData poll) + private async Task> GetPollResults(PollData poll) { var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId); var results = new List(); diff --git a/Geekbot.net/Commands/Quote.cs b/Geekbot.net/Commands/Quote.cs index fc4e2ce..4b4cfc3 100644 --- a/Geekbot.net/Commands/Quote.cs +++ b/Geekbot.net/Commands/Quote.cs @@ -24,7 +24,7 @@ namespace Geekbot.net.Commands [Command] [Remarks(CommandCategories.Quotes)] [Summary("Return a random quoute from the database")] - public async Task getRandomQuote() + public async Task GetRandomQuote() { try { @@ -32,7 +32,7 @@ namespace Geekbot.net.Commands var randomNumber = new Random().Next(randomQuotes.Length - 1); var randomQuote = randomQuotes[randomNumber]; var quote = JsonConvert.DeserializeObject(randomQuote); - var embed = quoteBuilder(quote, randomNumber + 1); + var embed = QuoteBuilder(quote, randomNumber + 1); await ReplyAsync("", false, embed.Build()); } catch (Exception e) @@ -44,7 +44,7 @@ namespace Geekbot.net.Commands [Command("save")] [Remarks(CommandCategories.Quotes)] [Summary("Save a quote from the last sent message by @user")] - public async Task saveQuote([Summary("@user")] IUser user) + public async Task SaveQuote([Summary("@user")] IUser user) { try { @@ -60,11 +60,11 @@ namespace Geekbot.net.Commands return; } - var lastMessage = await getLastMessageByUser(user); - var quote = createQuoteObject(lastMessage); + var lastMessage = await GetLastMessageByUser(user); + var quote = CreateQuoteObject(lastMessage); var quoteStore = JsonConvert.SerializeObject(quote); _redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore); - var embed = quoteBuilder(quote); + var embed = QuoteBuilder(quote); await ReplyAsync("**Quote Added**", false, embed.Build()); } catch (Exception e) @@ -77,7 +77,7 @@ namespace Geekbot.net.Commands [Command("save")] [Remarks(CommandCategories.Quotes)] [Summary("Save a quote from a message id")] - public async Task saveQuote([Summary("messageId")] ulong messageId) + public async Task SaveQuote([Summary("messageId")] ulong messageId) { try { @@ -94,10 +94,10 @@ namespace Geekbot.net.Commands return; } - var quote = createQuoteObject(message); + var quote = CreateQuoteObject(message); var quoteStore = JsonConvert.SerializeObject(quote); _redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore); - var embed = quoteBuilder(quote); + var embed = QuoteBuilder(quote); await ReplyAsync("**Quote Added**", false, embed.Build()); } catch (Exception e) @@ -110,13 +110,13 @@ namespace Geekbot.net.Commands [Command("make")] [Remarks(CommandCategories.Quotes)] [Summary("Create a quote from the last sent message by @user")] - public async Task returnSpecifiedQuote([Summary("@user")] IUser user) + public async Task ReturnSpecifiedQuote([Summary("@user")] IUser user) { try { - var lastMessage = await getLastMessageByUser(user); - var quote = createQuoteObject(lastMessage); - var embed = quoteBuilder(quote); + var lastMessage = await GetLastMessageByUser(user); + var quote = CreateQuoteObject(lastMessage); + var embed = QuoteBuilder(quote); await ReplyAsync("", false, embed.Build()); } catch (Exception e) @@ -129,13 +129,13 @@ namespace Geekbot.net.Commands [Command("make")] [Remarks(CommandCategories.Quotes)] [Summary("Create a quote from a message id")] - public async Task returnSpecifiedQuote([Summary("messageId")] ulong messageId) + public async Task ReturnSpecifiedQuote([Summary("messageId")] ulong messageId) { try { var message = await Context.Channel.GetMessageAsync(messageId); - var quote = createQuoteObject(message); - var embed = quoteBuilder(quote); + var quote = CreateQuoteObject(message); + var embed = QuoteBuilder(quote); await ReplyAsync("", false, embed.Build()); } catch (Exception e) @@ -151,7 +151,7 @@ namespace Geekbot.net.Commands [RequireUserPermission(GuildPermission.ManageRoles)] [Remarks(CommandCategories.Quotes)] [Summary("Remove a quote (required mod permissions)")] - public async Task removeQuote([Summary("quoteId")] int id) + public async Task RemoveQuote([Summary("quoteId")] int id) { try { @@ -160,12 +160,12 @@ namespace Geekbot.net.Commands if (success) { var quote = JsonConvert.DeserializeObject(quotes[id - 1]); - var embed = quoteBuilder(quote); + var embed = QuoteBuilder(quote); await ReplyAsync($"**Removed #{id}**", false, embed.Build()); } else { - await ReplyAsync($"I couldn't find a quote with that id :disappointed:"); + await ReplyAsync("I couldn't find a quote with that id :disappointed:"); } } catch (Exception e) @@ -175,7 +175,7 @@ namespace Geekbot.net.Commands } } - private async Task getLastMessageByUser(IUser user) + private async Task GetLastMessageByUser(IUser user) { var list = Context.Channel.GetMessagesAsync().Flatten(); await list; @@ -186,20 +186,20 @@ namespace Geekbot.net.Commands && !msg.Content.ToLower().StartsWith("!")); } - private EmbedBuilder quoteBuilder(QuoteObject quote, int id = 0) + private EmbedBuilder QuoteBuilder(QuoteObject quote, int id = 0) { - var user = Context.Client.GetUserAsync(quote.userId).Result; + var user = Context.Client.GetUserAsync(quote.UserId).Result; var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 167, 232)); eb.Title = id == 0 ? "" : $"#{id} | "; - eb.Title += $"{user.Username} @ {quote.time.Day}.{quote.time.Month}.{quote.time.Year}"; - eb.Description = quote.quote; + eb.Title += $"{user.Username} @ {quote.Time.Day}.{quote.Time.Month}.{quote.Time.Year}"; + eb.Description = quote.Quote; eb.ThumbnailUrl = user.GetAvatarUrl(); - if (quote.image != null) eb.ImageUrl = quote.image; + if (quote.Image != null) eb.ImageUrl = quote.Image; return eb; } - private QuoteObject createQuoteObject(IMessage message) + private QuoteObject CreateQuoteObject(IMessage message) { string image; try @@ -213,19 +213,19 @@ namespace Geekbot.net.Commands return new QuoteObject { - userId = message.Author.Id, - time = message.Timestamp.DateTime, - quote = message.Content, - image = image + UserId = message.Author.Id, + Time = message.Timestamp.DateTime, + Quote = message.Content, + Image = image }; } } public class QuoteObject { - public ulong userId { get; set; } - public string quote { get; set; } - public DateTime time { get; set; } - public string image { get; set; } + public ulong UserId { get; set; } + public string Quote { get; set; } + public DateTime Time { get; set; } + public string Image { get; set; } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/RandomAnimals.cs b/Geekbot.net/Commands/RandomAnimals.cs index f9dead9..2101c33 100644 --- a/Geekbot.net/Commands/RandomAnimals.cs +++ b/Geekbot.net/Commands/RandomAnimals.cs @@ -18,62 +18,62 @@ namespace Geekbot.net.Commands [Command("panda", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random panda image")] - public async Task panda() + public async Task Panda() { - await ReplyAsync("", false, eb(_mediaProvider.getPanda())); + await ReplyAsync("", false, Eb(_mediaProvider.GetPanda())); } [Command("croissant", RunMode = RunMode.Async)] [Alias("gipfeli")] [Remarks(CommandCategories.Randomness)] [Summary("Get a random croissant image")] - public async Task croissant() + public async Task Croissant() { - await ReplyAsync("", false, eb(_mediaProvider.getCrossant())); + await ReplyAsync("", false, Eb(_mediaProvider.GetCrossant())); } [Command("pumpkin", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random pumpkin image")] - public async Task pumpkin() + public async Task Pumpkin() { - await ReplyAsync("", false, eb(_mediaProvider.getPumpkin())); + await ReplyAsync("", false, Eb(_mediaProvider.GetPumpkin())); } [Command("squirrel", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random squirrel image")] - public async Task squirrel() + public async Task Squirrel() { - await ReplyAsync("", false, eb(_mediaProvider.getSquirrel())); + await ReplyAsync("", false, Eb(_mediaProvider.GetSquirrel())); } [Command("turtle", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random turtle image")] - public async Task turtle() + public async Task Turtle() { - await ReplyAsync("", false, eb(_mediaProvider.getTurtle())); + await ReplyAsync("", false, Eb(_mediaProvider.GetTurtle())); } [Command("pinguin", RunMode = RunMode.Async)] [Alias("pingu")] [Remarks(CommandCategories.Randomness)] [Summary("Get a random turtle image")] - public async Task pinguin() + public async Task Pinguin() { - await ReplyAsync("", false, eb(_mediaProvider.getPinguin())); + await ReplyAsync("", false, Eb(_mediaProvider.GetPinguin())); } [Command("fox", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random turtle image")] - public async Task fox() + public async Task Fox() { - await ReplyAsync("", false, eb(_mediaProvider.getFox())); + await ReplyAsync("", false, Eb(_mediaProvider.GetFox())); } - private EmbedBuilder eb(string image) + private EmbedBuilder Eb(string image) { var eb = new EmbedBuilder(); eb.ImageUrl = image; diff --git a/Geekbot.net/Commands/Rank.cs b/Geekbot.net/Commands/Rank.cs index 8c11171..92f78bd 100644 --- a/Geekbot.net/Commands/Rank.cs +++ b/Geekbot.net/Commands/Rank.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Lib; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Commands @@ -110,7 +109,7 @@ namespace Geekbot.net.Commands foreach (var user in highscoreUsers) { replyBuilder.Append(highscorePlace < 11 - ? $"{_emojiConverter.numberToEmoji(highscorePlace)} " + ? $"{_emojiConverter.NumberToEmoji(highscorePlace)} " : $"`{highscorePlace}.` "); replyBuilder.Append(user.Key.Username != null diff --git a/Geekbot.net/Commands/Role.cs b/Geekbot.net/Commands/Role.cs index 1de55ab..eb67bbf 100644 --- a/Geekbot.net/Commands/Role.cs +++ b/Geekbot.net/Commands/Role.cs @@ -27,7 +27,7 @@ namespace Geekbot.net.Commands [Command(RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Get a list of all available roles.")] - public async Task getAllRoles() + public async Task GetAllRoles() { try { @@ -53,7 +53,7 @@ namespace Geekbot.net.Commands [Command(RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Get a role by mentioning it.")] - public async Task giveRole([Summary("roleNickname")] string roleNameRaw) + public async Task GiveRole([Summary("roleNickname")] string roleNameRaw) { try { @@ -97,7 +97,7 @@ namespace Geekbot.net.Commands [Command("add", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Add a role to the whitelist.")] - public async Task addRole([Summary("@role")] IRole role, [Summary("alias")] string roleName) + public async Task AddRole([Summary("@role")] IRole role, [Summary("alias")] string roleName) { try { @@ -132,7 +132,7 @@ namespace Geekbot.net.Commands [Command("remove", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Remove a role from the whitelist.")] - public async Task removeRole([Summary("roleNickname")] string roleName) + public async Task RemoveRole([Summary("roleNickname")] string roleName) { try { @@ -166,7 +166,7 @@ namespace Geekbot.net.Commands if (!emoji.StartsWith('<')) { var emo = new Emoji(emoji); - emote = (IEmote) emo; + emote = emo; } else { diff --git a/Geekbot.net/Commands/Ship.cs b/Geekbot.net/Commands/Ship.cs index 4727bc8..d7dfd0e 100644 --- a/Geekbot.net/Commands/Ship.cs +++ b/Geekbot.net/Commands/Ship.cs @@ -64,9 +64,7 @@ namespace Geekbot.net.Commands return "There might be a chance"; if (rate >= 60 && rate < 80) return "Almost a match, but could work"; - if (rate >= 80) - return "It's a match"; - return "a"; + return rate >= 80 ? "It's a match" : "a"; } private string BlockCounter(int rate) diff --git a/Geekbot.net/Commands/Slap.cs b/Geekbot.net/Commands/Slap.cs index 09a6c15..668d33e 100644 --- a/Geekbot.net/Commands/Slap.cs +++ b/Geekbot.net/Commands/Slap.cs @@ -32,7 +32,7 @@ namespace Geekbot.net.Commands return; } - var things = new List() + var things = new List { "thing", "rubber chicken", diff --git a/Geekbot.net/Commands/UrbanDictionary.cs b/Geekbot.net/Commands/UrbanDictionary.cs index 573b289..a951cb8 100644 --- a/Geekbot.net/Commands/UrbanDictionary.cs +++ b/Geekbot.net/Commands/UrbanDictionary.cs @@ -22,7 +22,7 @@ namespace Geekbot.net.Commands [Command("urban", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Lookup something on urban dictionary")] - public async Task urbanDefine([Remainder] [Summary("word")] string word) + public async Task UrbanDefine([Remainder] [Summary("word")] string word) { try { @@ -34,26 +34,26 @@ namespace Geekbot.net.Commands var stringResponse = await response.Content.ReadAsStringAsync(); var definitions = JsonConvert.DeserializeObject(stringResponse); - if (definitions.list.Count == 0) + if (definitions.List.Count == 0) { await ReplyAsync("That word hasn't been defined..."); return; } - var definition = definitions.list.First(e => !string.IsNullOrWhiteSpace(e.example)); + var definition = definitions.List.First(e => !string.IsNullOrWhiteSpace(e.Example)); var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder { - Name = definition.word, - Url = definition.permalink + Name = definition.Word, + Url = definition.Permalink }); eb.WithColor(new Color(239, 255, 0)); - eb.Description = definition.definition; - eb.AddField("Example", definition.example ?? "(no example given...)"); - eb.AddInlineField("Upvotes", definition.thumbs_up); - eb.AddInlineField("Downvotes", definition.thumbs_down); - if (definitions.tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.tags)); + eb.Description = definition.Definition; + eb.AddField("Example", definition.Example ?? "(no example given...)"); + eb.AddInlineField("Upvotes", definition.ThumbsUp); + eb.AddInlineField("Downvotes", definition.ThumbsDown); + if (definitions.Tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.Tags)); await ReplyAsync("", false, eb.Build()); } @@ -66,22 +66,18 @@ namespace Geekbot.net.Commands private class UrbanResponse { - public string[] tags { get; set; } - public string result_type { get; set; } - public List list { get; set; } + public string[] Tags { get; set; } + public List List { get; set; } } private class UrbanListItem { - public string definition { get; set; } - public string permalink { get; set; } - public string thumbs_up { get; set; } - public string author { get; set; } - public string word { get; set; } - public string defid { get; set; } - public string current_vote { get; set; } - public string example { get; set; } - public string thumbs_down { get; set; } + public string Definition { get; set; } + public string Permalink { get; set; } + public string ThumbsUp { get; set; } + public string Word { get; set; } + public string Example { get; set; } + public string ThumbsDown { get; set; } } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Wikipedia.cs b/Geekbot.net/Commands/Wikipedia.cs index 77fb41d..05b21a6 100644 --- a/Geekbot.net/Commands/Wikipedia.cs +++ b/Geekbot.net/Commands/Wikipedia.cs @@ -78,7 +78,7 @@ namespace Geekbot.net.Commands }; eb.AddField("Description", article.Extract); - if (article.Coordinates != null) eb.AddField("Coordinates", $"{article.Coordinates.lat} Lat {article.Coordinates.lon} Lon"); + if (article.Coordinates != null) eb.AddField("Coordinates", $"{article.Coordinates.Lat} Lat {article.Coordinates.Lon} Lon"); await ReplyAsync("", false, eb.Build()); } catch (HttpRequestException) diff --git a/Geekbot.net/Commands/mal.cs b/Geekbot.net/Commands/mal.cs index 22b3d4a..8c16936 100644 --- a/Geekbot.net/Commands/mal.cs +++ b/Geekbot.net/Commands/mal.cs @@ -7,12 +7,12 @@ using Geekbot.net.Lib; namespace Geekbot.net.Commands { - public class mal : ModuleBase + public class Mal : ModuleBase { private readonly IErrorHandler _errorHandler; private readonly IMalClient _malClient; - public mal(IMalClient malClient, IErrorHandler errorHandler) + public Mal(IMalClient malClient, IErrorHandler errorHandler) { _malClient = malClient; _errorHandler = errorHandler; @@ -21,13 +21,13 @@ namespace Geekbot.net.Commands [Command("anime", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Show Info about an Anime.")] - public async Task searchAnime([Remainder] [Summary("AnimeName")] string animeName) + public async Task SearchAnime([Remainder] [Summary("AnimeName")] string animeName) { try { - if (_malClient.isLoggedIn()) + if (_malClient.IsLoggedIn()) { - var anime = await _malClient.getAnime(animeName); + var anime = await _malClient.GetAnime(animeName); if (anime != null) { var eb = new EmbedBuilder(); @@ -70,13 +70,13 @@ namespace Geekbot.net.Commands [Command("manga", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Show Info about a Manga.")] - public async Task searchManga([Remainder] [Summary("MangaName")] string mangaName) + public async Task SearchManga([Remainder] [Summary("MangaName")] string mangaName) { try { - if (_malClient.isLoggedIn()) + if (_malClient.IsLoggedIn()) { - var manga = await _malClient.getManga(mangaName); + var manga = await _malClient.GetManga(mangaName); if (manga != null) { var eb = new EmbedBuilder(); diff --git a/Geekbot.net/Handlers.cs b/Geekbot.net/Handlers.cs index c1e0ee3..31608b2 100644 --- a/Geekbot.net/Handlers.cs +++ b/Geekbot.net/Handlers.cs @@ -1,12 +1,10 @@ using System; -using System.Collections; using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using Geekbot.net.Lib; -using Serilog; using StackExchange.Redis; namespace Geekbot.net diff --git a/Geekbot.net/Lib/AudioClientCache.cs b/Geekbot.net/Lib/AudioClientCache.cs deleted file mode 100644 index d43b98a..0000000 --- a/Geekbot.net/Lib/AudioClientCache.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Security.Cryptography; -using Discord.Audio; -using Discord.Net; - -namespace Geekbot.net.Lib -{ - public class AudioUtils : IAudioUtils - { - private string _tempFolderPath; - private Dictionary _audioClients; - - public AudioUtils() - { - _audioClients = new Dictionary(); - _tempFolderPath = Path.GetFullPath("./tmp/"); - if (Directory.Exists(_tempFolderPath)) - { - Directory.Delete(_tempFolderPath, true); - } - Directory.CreateDirectory(_tempFolderPath); - } - - public IAudioClient GetAudioClient(ulong guildId) - { - return _audioClients[guildId]; - } - - public void StoreAudioClient(ulong guildId, IAudioClient client) - { - _audioClients[guildId] = client; - } - - public Process CreateStreamFromFile(string path) - { - var ffmpeg = new ProcessStartInfo - { - FileName = "ffmpeg", - Arguments = $"-i {path} -ac 2 -f s16le -ar 48000 pipe:1", - UseShellExecute = false, - RedirectStandardOutput = true, - }; - return Process.Start(ffmpeg); - } - - public Process CreateStreamFromYoutube(string url, ulong guildId) - { - var ytdlMediaUrl = GetYoutubeMediaUrl(url); - DownloadMediaUrl(ytdlMediaUrl, guildId); - return CreateStreamFromFile($"{_tempFolderPath}{guildId}"); - } - - public void Cleanup(ulong guildId) - { - File.Delete($"{_tempFolderPath}{guildId}"); - } - - private string GetYoutubeMediaUrl(string url) - { - var ytdl = new ProcessStartInfo() - { - FileName = "youtube-dl", - Arguments = $"-f bestaudio -g {url}", - UseShellExecute = false, - RedirectStandardOutput = true - }; - var output = Process.Start(ytdl).StandardOutput.ReadToEnd(); - if (string.IsNullOrWhiteSpace(output)) - { - throw new Exception("Could not get Youtube Media URL"); - } - return output; - } - - private void DownloadMediaUrl(string url, ulong guildId) - { - using (var web = new WebClient()) - { - web.DownloadFile(url, $"{_tempFolderPath}{guildId}"); - } -// var ffmpeg = new ProcessStartInfo -// { -// FileName = "ffmpeg", -// Arguments = $"-i \"{_tempFolderPath}{guildId}\" -c:a mp3 -b:a 256k {_tempFolderPath}{guildId}.mp3", -// UseShellExecute = false, -// RedirectStandardOutput = true, -// }; -// Process.Start(ffmpeg).WaitForExit(); -// File.Delete($"{_tempFolderPath}{guildId}"); - return; - } - } - - public interface IAudioUtils - { - IAudioClient GetAudioClient(ulong guildId); - void StoreAudioClient(ulong guildId, IAudioClient client); - Process CreateStreamFromFile(string path); - Process CreateStreamFromYoutube(string url, ulong guildId); - void Cleanup(ulong guildId); - } -} \ No newline at end of file diff --git a/Geekbot.net/Lib/CommandCategories.cs b/Geekbot.net/Lib/CommandCategories.cs index ca7ea58..d67123b 100644 --- a/Geekbot.net/Lib/CommandCategories.cs +++ b/Geekbot.net/Lib/CommandCategories.cs @@ -1,6 +1,6 @@ namespace Geekbot.net.Lib { - public class CommandCategories + public static class CommandCategories { public const string Randomness = "Randomness"; public const string Karma = "Karma"; diff --git a/Geekbot.net/Lib/Constants.cs b/Geekbot.net/Lib/Constants.cs index db5c875..d754b5c 100644 --- a/Geekbot.net/Lib/Constants.cs +++ b/Geekbot.net/Lib/Constants.cs @@ -3,7 +3,7 @@ public class Constants { public const string Name = "Geekbot"; - public const double BotVersion = 3.5; + public const double BotVersion = 3.6; public const double ApiVersion = 1; } } \ No newline at end of file diff --git a/Geekbot.net/Lib/EmojiConverter.cs b/Geekbot.net/Lib/EmojiConverter.cs index 7091f0c..b836485 100644 --- a/Geekbot.net/Lib/EmojiConverter.cs +++ b/Geekbot.net/Lib/EmojiConverter.cs @@ -5,13 +5,13 @@ namespace Geekbot.net.Lib { public class EmojiConverter : IEmojiConverter { - public string numberToEmoji(int number) + public string NumberToEmoji(int number) { if (number == 10) { return "🔟"; } - var emojiMap = new string[] + var emojiMap = new[] { ":zero:", ":one:", @@ -22,7 +22,7 @@ namespace Geekbot.net.Lib ":six:", ":seven:", ":eight:", - ":nine:", + ":nine:" }; var numbers = number.ToString().ToCharArray(); var returnString = new StringBuilder(); @@ -33,7 +33,7 @@ namespace Geekbot.net.Lib return returnString.ToString(); } - public string textToEmoji(string text) + public string TextToEmoji(string text) { var emojiMap = new Hashtable { @@ -93,7 +93,7 @@ namespace Geekbot.net.Lib public interface IEmojiConverter { - string numberToEmoji(int number); - string textToEmoji(string text); + string NumberToEmoji(int number); + string TextToEmoji(string text); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/ErrorHandler.cs b/Geekbot.net/Lib/ErrorHandler.cs index dc67db2..9bf99f4 100644 --- a/Geekbot.net/Lib/ErrorHandler.cs +++ b/Geekbot.net/Lib/ErrorHandler.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Diagnostics; using System.Net; using Discord.Commands; using Discord.Net; @@ -34,12 +32,12 @@ namespace Geekbot.net.Lib } } - public void HandleCommandException(Exception e, ICommandContext Context, string errorMessage = "def") + public void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def") { try { - var errorString = errorMessage == "def" ? _translation.GetString(Context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage; - var errorObj = SimpleConextConverter.ConvertContext(Context); + var errorString = errorMessage == "def" ? _translation.GetString(context.Guild.Id, "errorHandler", "SomethingWentWrong") : errorMessage; + var errorObj = SimpleConextConverter.ConvertContext(context); if (e.Message.Contains("50007")) return; if (e.Message.Contains("50013")) return; _logger.Error("Geekbot", "An error ocured", e, errorObj); @@ -49,11 +47,11 @@ namespace Geekbot.net.Lib { var resStackTrace = string.IsNullOrEmpty(e.InnerException?.ToString()) ? e.StackTrace : e.InnerException.ToString(); var maxLen = Math.Min(resStackTrace.Length, 1850); - Context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace?.Substring(0, maxLen)}\r\n```"); + context.Channel.SendMessageAsync($"{e.Message}\r\n```\r\n{resStackTrace.Substring(0, maxLen)}\r\n```"); } else { - Context.Channel.SendMessageAsync(errorString); + context.Channel.SendMessageAsync(errorString); } } @@ -74,18 +72,18 @@ namespace Geekbot.net.Lib } catch (Exception ex) { - Context.Channel.SendMessageAsync("Something went really really wrong here"); + context.Channel.SendMessageAsync("Something went really really wrong here"); _logger.Error("Geekbot", "Errorception", ex); } } - public async void HandleHttpException(HttpException e, ICommandContext Context) + public async void HandleHttpException(HttpException e, ICommandContext context) { - var errorStrings = _translation.GetDict(Context, "httpErrors"); + var errorStrings = _translation.GetDict(context, "httpErrors"); switch(e.HttpCode) { case HttpStatusCode.Forbidden: - await Context.Channel.SendMessageAsync(errorStrings["403"]); + await context.Channel.SendMessageAsync(errorStrings["403"]); break; } } @@ -95,7 +93,7 @@ namespace Geekbot.net.Lib public interface IErrorHandler { - void HandleCommandException(Exception e, ICommandContext Context, string errorMessage = "def"); - void HandleHttpException(HttpException e, ICommandContext Context); + void HandleCommandException(Exception e, ICommandContext context, string errorMessage = "def"); + void HandleHttpException(HttpException e, ICommandContext context); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/GeekbotLogger.cs b/Geekbot.net/Lib/GeekbotLogger.cs index f2feda7..b5214b0 100644 --- a/Geekbot.net/Lib/GeekbotLogger.cs +++ b/Geekbot.net/Lib/GeekbotLogger.cs @@ -10,7 +10,7 @@ namespace Geekbot.net.Lib private readonly ILogger _serilog; public GeekbotLogger() { - _serilog = LoggerFactory.createLogger(); + _serilog = LoggerFactory.CreateLogger(); //JsonSerializer.SetDefaultResolver(StandardResolver.AllowPrivateExcludeNullSnakeCase); Information("Geekbot", "Using GeekbotLogger"); } @@ -45,7 +45,7 @@ namespace Geekbot.net.Lib private string CreateLogObject(string type, string source, string message, Exception stackTrace = null, object extra = null) { - var logObject = new GeekbotLoggerObject() + var logObject = new GeekbotLoggerObject { Timestamp = DateTime.Now, Type = type, diff --git a/Geekbot.net/Lib/LevelCalc.cs b/Geekbot.net/Lib/LevelCalc.cs index d075754..75df83d 100644 --- a/Geekbot.net/Lib/LevelCalc.cs +++ b/Geekbot.net/Lib/LevelCalc.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; namespace Geekbot.net.Lib { diff --git a/Geekbot.net/Lib/LoggerFactory.cs b/Geekbot.net/Lib/LoggerFactory.cs index 789bdc6..9bff873 100644 --- a/Geekbot.net/Lib/LoggerFactory.cs +++ b/Geekbot.net/Lib/LoggerFactory.cs @@ -1,13 +1,12 @@ using System; using Serilog; -using Serilog.Formatting.Json; using Serilog.Sinks.SumoLogic; namespace Geekbot.net.Lib { public class LoggerFactory { - public static ILogger createLogger() + public static ILogger CreateLogger() { var loggerCreation = new LoggerConfiguration(); var template = "{Message}{NewLine}"; diff --git a/Geekbot.net/Lib/MalClient.cs b/Geekbot.net/Lib/MalClient.cs index bc09036..dcf4fe3 100644 --- a/Geekbot.net/Lib/MalClient.cs +++ b/Geekbot.net/Lib/MalClient.cs @@ -2,7 +2,6 @@ using MyAnimeListSharp.Auth; using MyAnimeListSharp.Core; using MyAnimeListSharp.Facade.Async; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Lib @@ -19,10 +18,10 @@ namespace Geekbot.net.Lib { _redis = redis; _logger = logger; - reloadClient(); + ReloadClient(); } - public bool reloadClient() + public bool ReloadClient() { var malCredentials = _redis.HashGetAll("malCredentials"); if (malCredentials.Length != 0) @@ -50,18 +49,18 @@ namespace Geekbot.net.Lib } - public bool isLoggedIn() + public bool IsLoggedIn() { return _credentials != null; } - public async Task getAnime(string query) + public async Task GetAnime(string query) { var response = await _animeSearch.SearchDeserializedAsync(query); return response.Entries.Count == 0 ? null : response.Entries[0]; } - public async Task getManga(string query) + public async Task GetManga(string query) { var response = await _mangaSearch.SearchDeserializedAsync(query); return response.Entries.Count == 0 ? null : response.Entries[0]; @@ -70,9 +69,8 @@ namespace Geekbot.net.Lib public interface IMalClient { - bool reloadClient(); - bool isLoggedIn(); - Task getAnime(string query); - Task getManga(string query); + bool IsLoggedIn(); + Task GetAnime(string query); + Task GetManga(string query); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/Media/FortunesProvider.cs b/Geekbot.net/Lib/Media/FortunesProvider.cs index 8a9b6f0..5988660 100644 --- a/Geekbot.net/Lib/Media/FortunesProvider.cs +++ b/Geekbot.net/Lib/Media/FortunesProvider.cs @@ -1,13 +1,12 @@ using System; using System.IO; -using Serilog; namespace Geekbot.net.Lib.Media { internal class FortunesProvider : IFortunesProvider { - private readonly string[] fortuneArray; - private readonly int totalFortunes; + private readonly string[] _fortuneArray; + private readonly int _totalFortunes; public FortunesProvider(IGeekbotLogger logger) { @@ -15,8 +14,8 @@ namespace Geekbot.net.Lib.Media if (File.Exists(path)) { var rawFortunes = File.ReadAllText(path); - fortuneArray = rawFortunes.Split("%"); - totalFortunes = fortuneArray.Length; + _fortuneArray = rawFortunes.Split("%"); + _totalFortunes = _fortuneArray.Length; logger.Debug("Geekbot", "Loaded {totalFortunes} Fortunes"); } else @@ -27,7 +26,7 @@ namespace Geekbot.net.Lib.Media public string GetRandomFortune() { - return fortuneArray[new Random().Next(0, totalFortunes)]; + return _fortuneArray[new Random().Next(0, _totalFortunes)]; } } diff --git a/Geekbot.net/Lib/Media/MediaProvider.cs b/Geekbot.net/Lib/Media/MediaProvider.cs index b8aeaa3..568f67d 100644 --- a/Geekbot.net/Lib/Media/MediaProvider.cs +++ b/Geekbot.net/Lib/Media/MediaProvider.cs @@ -1,8 +1,5 @@ using System; using System.IO; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; -using Serilog; namespace Geekbot.net.Lib.Media { @@ -92,42 +89,42 @@ namespace Geekbot.net.Lib.Media _logger.Debug("Geekbot", $"Loaded {_foxImages.Length} Foxes Images"); } - public string getCheckem() + public string GetCheckem() { return _checkemImages[_random.Next(0, _checkemImages.Length)]; } - public string getPanda() + public string GetPanda() { return _pandaImages[_random.Next(0, _pandaImages.Length)]; } - public string getCrossant() + public string GetCrossant() { return _croissantImages[_random.Next(0, _croissantImages.Length)]; } - public string getSquirrel() + public string GetSquirrel() { return _squirrelImages[_random.Next(0, _squirrelImages.Length)]; } - public string getPumpkin() + public string GetPumpkin() { return _pumpkinImages[_random.Next(0, _pumpkinImages.Length)]; } - public string getTurtle() + public string GetTurtle() { return _turtlesImages[_random.Next(0, _turtlesImages.Length)]; } - public string getPinguin() + public string GetPinguin() { return _pinguinImages[_random.Next(0, _pinguinImages.Length)]; } - public string getFox() + public string GetFox() { return _foxImages[_random.Next(0, _foxImages.Length)]; } @@ -135,13 +132,13 @@ namespace Geekbot.net.Lib.Media public interface IMediaProvider { - string getCheckem(); - string getPanda(); - string getCrossant(); - string getSquirrel(); - string getPumpkin(); - string getTurtle(); - string getPinguin(); - string getFox(); + string GetCheckem(); + string GetPanda(); + string GetCrossant(); + string GetSquirrel(); + string GetPumpkin(); + string GetTurtle(); + string GetPinguin(); + string GetFox(); } } \ No newline at end of file diff --git a/Geekbot.net/Lib/MtgManaConverter.cs b/Geekbot.net/Lib/MtgManaConverter.cs index 098542e..83b6767 100644 --- a/Geekbot.net/Lib/MtgManaConverter.cs +++ b/Geekbot.net/Lib/MtgManaConverter.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using System.Text.RegularExpressions; namespace Geekbot.net.Lib diff --git a/Geekbot.net/Lib/ReactionListener.cs b/Geekbot.net/Lib/ReactionListener.cs index f0e75a6..f837280 100644 --- a/Geekbot.net/Lib/ReactionListener.cs +++ b/Geekbot.net/Lib/ReactionListener.cs @@ -33,7 +33,7 @@ namespace Geekbot.net.Lib if (!r.Name.ToString().StartsWith('<')) { var emo = new Emoji(r.Name); - emote = (IEmote) emo; + emote = emo; } else { diff --git a/Geekbot.net/Lib/SimpleConextConverter.cs b/Geekbot.net/Lib/SimpleConextConverter.cs index 3dbc58b..ad029c7 100644 --- a/Geekbot.net/Lib/SimpleConextConverter.cs +++ b/Geekbot.net/Lib/SimpleConextConverter.cs @@ -1,5 +1,4 @@ -using System; -using Discord.Commands; +using Discord.Commands; using Discord.WebSocket; namespace Geekbot.net.Lib @@ -8,9 +7,9 @@ namespace Geekbot.net.Lib { public static MessageDto ConvertContext(ICommandContext context) { - return new MessageDto() + return new MessageDto { - Message = new MessageDto.MessageContent() + Message = new MessageDto.MessageContent { Content = context.Message.Content, Id = context.Message.Id.ToString(), @@ -19,17 +18,17 @@ namespace Geekbot.net.Lib UserMentions = context.Message.MentionedUserIds.Count, RoleMentions = context.Message.MentionedRoleIds.Count }, - User = new MessageDto.IdAndName() + User = new MessageDto.IdAndName { Id = context.User.Id.ToString(), Name = $"{context.User.Username}#{context.User.Discriminator}" }, - Guild = new MessageDto.IdAndName() + Guild = new MessageDto.IdAndName { Id = context.Guild.Id.ToString(), Name = context.Guild.Name }, - Channel = new MessageDto.IdAndName() + Channel = new MessageDto.IdAndName { Id = context.Channel.Id.ToString(), Name = context.Channel.Name @@ -39,9 +38,9 @@ namespace Geekbot.net.Lib public static MessageDto ConvertSocketMessage(SocketMessage message) { var channel = (SocketGuildChannel) message.Channel; - return new MessageDto() + return new MessageDto { - Message = new MessageDto.MessageContent() + Message = new MessageDto.MessageContent { Content = message.Content, Id = message.Id.ToString(), @@ -50,21 +49,21 @@ namespace Geekbot.net.Lib UserMentions = message.MentionedUsers.Count, RoleMentions = message.MentionedRoles.Count }, - User = new MessageDto.IdAndName() + User = new MessageDto.IdAndName { Id = message.Author.Id.ToString(), Name = $"{message.Author.Username}#{message.Author.Discriminator}" }, - Guild = new MessageDto.IdAndName() + Guild = new MessageDto.IdAndName { Id = channel.Guild.Id.ToString(), Name = channel.Guild.Name }, - Channel = new MessageDto.IdAndName() + Channel = new MessageDto.IdAndName { Id = channel.Id.ToString(), Name = channel.Name - }, + } }; } diff --git a/Geekbot.net/Lib/TranslationHandler.cs b/Geekbot.net/Lib/TranslationHandler.cs index cdacac8..5324496 100644 --- a/Geekbot.net/Lib/TranslationHandler.cs +++ b/Geekbot.net/Lib/TranslationHandler.cs @@ -4,8 +4,8 @@ using System.IO; using System.Linq; using Discord.Commands; using Discord.WebSocket; -using Serilog; using StackExchange.Redis; +using Utf8Json; namespace Geekbot.net.Lib { @@ -31,7 +31,7 @@ namespace Geekbot.net.Lib try { var translationFile = File.ReadAllText(Path.GetFullPath("./Storage/Translations.json")); - var rawTranslations = Utf8Json.JsonSerializer.Deserialize>>>(translationFile); + var rawTranslations = JsonSerializer.Deserialize>>>(translationFile); var sortedPerLanguage = new Dictionary>>(); foreach (var command in rawTranslations) { @@ -136,7 +136,7 @@ namespace Geekbot.net.Lib try { if (!_supportedLanguages.Contains(language)) return false; - _redis.HashSet($"{guildId}:Settings", new HashEntry[]{ new HashEntry("Language", language), }); + _redis.HashSet($"{guildId}:Settings", new[]{ new HashEntry("Language", language) }); _serverLanguages[guildId] = language; return true; } diff --git a/Geekbot.net/Lib/UserRepository.cs b/Geekbot.net/Lib/UserRepository.cs index b180ef9..28d0541 100644 --- a/Geekbot.net/Lib/UserRepository.cs +++ b/Geekbot.net/Lib/UserRepository.cs @@ -1,10 +1,7 @@ using System; using System.Collections.Generic; -using System.Globalization; -using System.Linq; using System.Threading.Tasks; using Discord.WebSocket; -using Serilog; using StackExchange.Redis; using Utf8Json; @@ -50,7 +47,7 @@ namespace Geekbot.net.Lib private void Store(UserRepositoryUser user) { - _redis.HashSetAsync($"Users:{user.Id.ToString()}", new HashEntry[] + _redis.HashSetAsync($"Users:{user.Id.ToString()}", new[] { new HashEntry("Id", user.Id.ToString()), new HashEntry("Username", user.Username), @@ -58,7 +55,7 @@ namespace Geekbot.net.Lib new HashEntry("AvatarUrl", user.AvatarUrl), new HashEntry("IsBot", user.IsBot), new HashEntry("Joined", user.Joined.ToString()), - new HashEntry("UsedNames", JsonSerializer.Serialize(user.UsedNames)), + new HashEntry("UsedNames", JsonSerializer.Serialize(user.UsedNames)) }); } @@ -67,7 +64,7 @@ namespace Geekbot.net.Lib try { var user = _redis.HashGetAll($"Users:{userId.ToString()}"); - for (int i = 1; i < 11; i++) + for (var i = 1; i < 11; i++) { if (user.Length != 0) break; user = _redis.HashGetAll($"Users:{(userId + (ulong) i).ToString()}"); @@ -88,7 +85,7 @@ namespace Geekbot.net.Lib dto.Discriminator = a.Value.ToString(); break; case "AvatarUrl": - dto.AvatarUrl = (a.Value != "0") ? a.Value.ToString() : null; + dto.AvatarUrl = a.Value != "0" ? a.Value.ToString() : null; break; case "IsBot": dto.IsBot = a.Value == 1; @@ -110,14 +107,14 @@ namespace Geekbot.net.Lib } } - public string getUserSetting(ulong userId, string setting) + public string GetUserSetting(ulong userId, string setting) { return _redis.HashGet($"Users:{userId}", setting); } - public bool saveUserSetting(ulong userId, string setting, string value) + public bool SaveUserSetting(ulong userId, string setting, string value) { - _redis.HashSet($"Users:{userId}", new HashEntry[] + _redis.HashSet($"Users:{userId}", new[] { new HashEntry(setting, value) }); @@ -140,7 +137,7 @@ namespace Geekbot.net.Lib { Task Update(SocketUser user); UserRepositoryUser Get(ulong userId); - string getUserSetting(ulong userId, string setting); - bool saveUserSetting(ulong userId, string setting, string value); + string GetUserSetting(ulong userId, string setting); + bool SaveUserSetting(ulong userId, string setting, string value); } } \ No newline at end of file diff --git a/Geekbot.net/Program.cs b/Geekbot.net/Program.cs index b805e5f..0a107e9 100755 --- a/Geekbot.net/Program.cs +++ b/Geekbot.net/Program.cs @@ -18,16 +18,16 @@ namespace Geekbot.net { internal class Program { - private DiscordSocketClient client; - private CommandService commands; - private IDatabase redis; - private IServiceCollection services; - private IServiceProvider servicesProvider; - private RedisValue token; - private IGeekbotLogger logger; - private IUserRepository userRepository; - private string[] args; - private bool firstStart = false; + private DiscordSocketClient _client; + private CommandService _commands; + private IDatabase _redis; + private IServiceCollection _services; + private IServiceProvider _servicesProvider; + private RedisValue _token; + private IGeekbotLogger _logger; + private IUserRepository _userRepository; + private string[] _args; + private bool _firstStart; private static void Main(string[] args) { @@ -53,23 +53,23 @@ namespace Geekbot.net private async Task MainAsync(string[] args, IGeekbotLogger logger) { - this.logger = logger; - this.args = args; + _logger = logger; + _args = args; logger.Information("Geekbot", "Initing Stuff"); - client = new DiscordSocketClient(new DiscordSocketConfig + _client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = LogSeverity.Verbose, MessageCacheSize = 1000 }); - client.Log += DiscordLogger; - commands = new CommandService(); + _client.Log += DiscordLogger; + _commands = new CommandService(); try { var redisMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379"); - redis = redisMultiplexer.GetDatabase(6); - logger.Information("Redis", $"Connected to db {redis.Database}"); + _redis = redisMultiplexer.GetDatabase(6); + logger.Information("Redis", $"Connected to db {_redis.Database}"); } catch (Exception e) { @@ -77,40 +77,38 @@ namespace Geekbot.net Environment.Exit(102); } - token = redis.StringGet("discordToken"); - if (token.IsNullOrEmpty) + _token = _redis.StringGet("discordToken"); + if (_token.IsNullOrEmpty) { Console.Write("Your bot Token: "); var newToken = Console.ReadLine(); - redis.StringSet("discordToken", newToken); - redis.StringSet("Game", "Ping Pong"); - token = newToken; - firstStart = true; + _redis.StringSet("discordToken", newToken); + _redis.StringSet("Game", "Ping Pong"); + _token = newToken; + _firstStart = true; } - services = new ServiceCollection(); + _services = new ServiceCollection(); - userRepository = new UserRepository(redis, logger); + _userRepository = new UserRepository(_redis, logger); var fortunes = new FortunesProvider(logger); var mediaProvider = new MediaProvider(logger); - var malClient = new MalClient(redis, logger); + var malClient = new MalClient(_redis, logger); var levelCalc = new LevelCalc(); var emojiConverter = new EmojiConverter(); - var audioUtils = new AudioUtils(); var mtgManaConverter = new MtgManaConverter(); var wikipediaClient = new WikipediaClient(); - services.AddSingleton(redis); - services.AddSingleton(logger); - services.AddSingleton(userRepository); - services.AddSingleton(levelCalc); - services.AddSingleton(emojiConverter); - services.AddSingleton(audioUtils); - services.AddSingleton(fortunes); - services.AddSingleton(mediaProvider); - services.AddSingleton(malClient); - services.AddSingleton(mtgManaConverter); - services.AddSingleton(wikipediaClient); + _services.AddSingleton(_redis); + _services.AddSingleton(logger); + _services.AddSingleton(_userRepository); + _services.AddSingleton(levelCalc); + _services.AddSingleton(emojiConverter); + _services.AddSingleton(fortunes); + _services.AddSingleton(mediaProvider); + _services.AddSingleton(malClient); + _services.AddSingleton(mtgManaConverter); + _services.AddSingleton(wikipediaClient); logger.Information("Geekbot", "Connecting to Discord"); @@ -123,94 +121,94 @@ namespace Geekbot.net { try { - await client.LoginAsync(TokenType.Bot, token); - await client.StartAsync(); - var isConneted = await isConnected(); + await _client.LoginAsync(TokenType.Bot, _token); + await _client.StartAsync(); + var isConneted = await IsConnected(); if (isConneted) { - await client.SetGameAsync(redis.StringGet("Game")); - logger.Information("Geekbot", $"Now Connected as {client.CurrentUser.Username} to {client.Guilds.Count} Servers"); + await _client.SetGameAsync(_redis.StringGet("Game")); + _logger.Information("Geekbot", $"Now Connected as {_client.CurrentUser.Username} to {_client.Guilds.Count} Servers"); - logger.Information("Geekbot", "Registering Stuff"); - var translationHandler = new TranslationHandler(client.Guilds, redis, logger); - var errorHandler = new ErrorHandler(logger, translationHandler, args.Contains("--expose-errors")); - var reactionListener = new ReactionListener(redis); - await commands.AddModulesAsync(Assembly.GetEntryAssembly()); - services.AddSingleton(commands); - services.AddSingleton(errorHandler); - services.AddSingleton(translationHandler); - services.AddSingleton(client); - services.AddSingleton(reactionListener); - servicesProvider = services.BuildServiceProvider(); + _logger.Information("Geekbot", "Registering Stuff"); + var translationHandler = new TranslationHandler(_client.Guilds, _redis, _logger); + var errorHandler = new ErrorHandler(_logger, translationHandler, _args.Contains("--expose-errors")); + var reactionListener = new ReactionListener(_redis); + await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); + _services.AddSingleton(_commands); + _services.AddSingleton(errorHandler); + _services.AddSingleton(translationHandler); + _services.AddSingleton(_client); + _services.AddSingleton(reactionListener); + _servicesProvider = _services.BuildServiceProvider(); - var handlers = new Handlers(client, logger, redis, servicesProvider, commands, userRepository, reactionListener); + var handlers = new Handlers(_client, _logger, _redis, _servicesProvider, _commands, _userRepository, reactionListener); - client.MessageReceived += handlers.RunCommand; - client.MessageReceived += handlers.UpdateStats; - client.MessageDeleted += handlers.MessageDeleted; - client.UserJoined += handlers.UserJoined; - client.UserUpdated += handlers.UserUpdated; - client.UserLeft += handlers.UserLeft; - client.ReactionAdded += handlers.ReactionAdded; - client.ReactionRemoved += handlers.ReactionRemoved; + _client.MessageReceived += handlers.RunCommand; + _client.MessageReceived += handlers.UpdateStats; + _client.MessageDeleted += handlers.MessageDeleted; + _client.UserJoined += handlers.UserJoined; + _client.UserUpdated += handlers.UserUpdated; + _client.UserLeft += handlers.UserLeft; + _client.ReactionAdded += handlers.ReactionAdded; + _client.ReactionRemoved += handlers.ReactionRemoved; - if (firstStart || args.Contains("--reset")) + if (_firstStart || _args.Contains("--reset")) { - logger.Information("Geekbot", "Finishing setup"); + _logger.Information("Geekbot", "Finishing setup"); await FinishSetup(); - logger.Information("Geekbot", "Setup finished"); + _logger.Information("Geekbot", "Setup finished"); } - if (!args.Contains("--disable-api")) + if (!_args.Contains("--disable-api")) { - startWebApi(); + StartWebApi(); } - logger.Information("Geekbot", "Done and ready for use"); + _logger.Information("Geekbot", "Done and ready for use"); } } catch (Exception e) { - logger.Error("Discord", "Could not connect...", e); + _logger.Error("Discord", "Could not connect...", e); Environment.Exit(103); } } - private async Task isConnected() + private async Task IsConnected() { - while (!client.ConnectionState.Equals(ConnectionState.Connected)) + while (!_client.ConnectionState.Equals(ConnectionState.Connected)) await Task.Delay(25); return true; } - private void startWebApi() + private void StartWebApi() { - logger.Information("API", "Starting Webserver"); + _logger.Information("API", "Starting Webserver"); var webApiUrl = new Uri("http://localhost:12995"); new NancyHost(webApiUrl).Start(); - logger.Information("API", $"Webserver now running on {webApiUrl}"); + _logger.Information("API", $"Webserver now running on {webApiUrl}"); } private async Task FinishSetup() { - var appInfo = await client.GetApplicationInfoAsync(); - logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}"); + var appInfo = await _client.GetApplicationInfoAsync(); + _logger.Information("Setup", $"Just a moment while i setup everything {appInfo.Owner.Username}"); try { - redis.StringSet("botOwner", appInfo.Owner.Id); - var req = HttpWebRequest.Create(appInfo.IconUrl); + _redis.StringSet("botOwner", appInfo.Owner.Id); + var req = WebRequest.Create(appInfo.IconUrl); using (var stream = req.GetResponse().GetResponseStream()) { - await client.CurrentUser.ModifyAsync(User => + await _client.CurrentUser.ModifyAsync(user => { - User.Avatar = new Image(stream); - User.Username = appInfo.Name.ToString(); + user.Avatar = new Image(stream); + user.Username = appInfo.Name.ToString(); }); } - logger.Information("Setup", "Everything done, enjoy!"); + _logger.Information("Setup", "Everything done, enjoy!"); } catch (Exception e) { - logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e); + _logger.Warning("Setup", "Oha, it seems like something went wrong while running the setup, geekbot will work never the less though", e); } return Task.CompletedTask; } @@ -222,19 +220,19 @@ namespace Geekbot.net { case LogSeverity.Verbose: case LogSeverity.Debug: - logger.Debug(message.Source, message.Message); + _logger.Debug(message.Source, message.Message); break; case LogSeverity.Info: - logger.Information(message.Source, message.Message); + _logger.Information(message.Source, message.Message); break; case LogSeverity.Critical: case LogSeverity.Error: case LogSeverity.Warning: if (logMessage.Contains("VOICE_STATE_UPDATE")) break; - logger.Error(message.Source, message.Message, message.Exception); + _logger.Error(message.Source, message.Message, message.Exception); break; default: - logger.Information(message.Source, $"{logMessage} --- {message.Severity}"); + _logger.Information(message.Source, $"{logMessage} --- {message.Severity}"); break; } return Task.CompletedTask; diff --git a/Geekbot.net/WebApi/HelpController.cs b/Geekbot.net/WebApi/HelpController.cs index 6146352..060dea0 100644 --- a/Geekbot.net/WebApi/HelpController.cs +++ b/Geekbot.net/WebApi/HelpController.cs @@ -3,10 +3,9 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using Discord; using Discord.Commands; -using Nancy; using Geekbot.net.Lib; +using Nancy; namespace Geekbot.net.WebApi { @@ -16,25 +15,18 @@ namespace Geekbot.net.WebApi { Get("/v1/commands", args => { - var commands = getCommands().Result; + var commands = GetCommands().Result; - var commandList = new List(); - foreach (var cmd in commands.Commands) - { - var cmdParamsObj = new List(); - foreach (var cmdParam in cmd.Parameters) - { - var singleParamObj = new CommandParamDto() + var commandList = (from cmd in commands.Commands + let cmdParamsObj = cmd.Parameters.Select(cmdParam => new CommandParamDto { Summary = cmdParam.Summary, - Default = cmdParam?.DefaultValue?.ToString() ?? null, - Type = cmdParam?.Type?.ToString() - }; - cmdParamsObj.Add(singleParamObj); - } - - var param = string.Join(", !", cmd.Aliases); - var cmdObj = new CommandDto() + Default = cmdParam.DefaultValue?.ToString() ?? null, + Type = cmdParam.Type?.ToString() + }) + .ToList() + let param = string.Join(", !", cmd.Aliases) + select new CommandDto { Name = cmd.Name, Summary = cmd.Summary, @@ -42,15 +34,13 @@ namespace Geekbot.net.WebApi IsAdminCommand = (param.Contains("admin")), Aliases = cmd.Aliases.ToArray(), Params = cmdParamsObj - }; - commandList.Add(cmdObj); - } + }).ToList(); return Response.AsJson(commandList); }); } - private async Task getCommands() + private async Task GetCommands() { var commands = new CommandService(); await commands.AddModulesAsync(Assembly.GetEntryAssembly()); diff --git a/Geekbot.net/WebApi/StatusController.cs b/Geekbot.net/WebApi/StatusController.cs index 2fd84f8..b785e07 100644 --- a/Geekbot.net/WebApi/StatusController.cs +++ b/Geekbot.net/WebApi/StatusController.cs @@ -1,5 +1,5 @@ -using Nancy; -using Geekbot.net.Lib; +using Geekbot.net.Lib; +using Nancy; namespace Geekbot.net.WebApi { @@ -9,7 +9,7 @@ namespace Geekbot.net.WebApi { Get("/", args => { - var responseBody = new ApiStatusDto() + var responseBody = new ApiStatusDto { GeekbotVersion = Constants.BotVersion.ToString(), ApiVersion = Constants.ApiVersion.ToString(), diff --git a/Tests/Lib/EmojiConverter.test.cs b/Tests/Lib/EmojiConverter.test.cs index b9e7b4f..4bfcf06 100644 --- a/Tests/Lib/EmojiConverter.test.cs +++ b/Tests/Lib/EmojiConverter.test.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; -using System.Threading.Tasks; using Geekbot.net.Lib; using Xunit; namespace Tests.Lib { - public class EmojiConverter_test + public class EmojiConverterTest { public static IEnumerable NumberToEmojiTestData { @@ -42,11 +41,11 @@ namespace Tests.Lib public void NumberToEmoji(int number, string expectedResult) { var emojiConverter = new EmojiConverter(); - var result = emojiConverter.numberToEmoji(number); + var result = emojiConverter.NumberToEmoji(number); Assert.Equal(result, expectedResult); } - public static IEnumerable textToEmojiTestData + public static IEnumerable TextToEmojiTestData { get { @@ -64,11 +63,11 @@ namespace Tests.Lib } - [Theory, MemberData(nameof(textToEmojiTestData))] + [Theory, MemberData(nameof(TextToEmojiTestData))] public void TextToEmoji(string text, string expectedResult) { var emojiConverter = new EmojiConverter(); - var result = emojiConverter.textToEmoji(text); + var result = emojiConverter.TextToEmoji(text); Assert.Equal(result, expectedResult); } } diff --git a/Tests/Lib/LevelCalc.test.cs b/Tests/Lib/LevelCalc.test.cs index 7c00392..ecca151 100644 --- a/Tests/Lib/LevelCalc.test.cs +++ b/Tests/Lib/LevelCalc.test.cs @@ -1,11 +1,10 @@ using System.Collections.Generic; -using System.Threading.Tasks; using Geekbot.net.Lib; using Xunit; namespace Tests.Lib { - public class LevelCalc_test + public class LevelCalcTest { public static IEnumerable LevelCalcTestData { diff --git a/WikipediaApi/Page/PageCoordinates.cs b/WikipediaApi/Page/PageCoordinates.cs index f86bb09..7fa42ba 100644 --- a/WikipediaApi/Page/PageCoordinates.cs +++ b/WikipediaApi/Page/PageCoordinates.cs @@ -2,7 +2,7 @@ { public class PageCoordinates { - public float lat { get; set; } - public float lon { get; set; } + public float Lat { get; set; } + public float Lon { get; set; } } } \ No newline at end of file diff --git a/WikipediaApi/Page/PagePreview.cs b/WikipediaApi/Page/PagePreview.cs index c1de2d7..8db9dad 100644 --- a/WikipediaApi/Page/PagePreview.cs +++ b/WikipediaApi/Page/PagePreview.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; @@ -18,7 +17,7 @@ namespace WikipediaApi.Page public string Displaytitle { get; set; } [JsonProperty("namespace")] - public PageNamespace @Namespace { get; set; } + public PageNamespace Namespace { get; set; } [JsonProperty("titles")] public PageTitles Titles { get; set; } diff --git a/WikipediaApi/WikipediaClient.cs b/WikipediaApi/WikipediaClient.cs index 161cbce..6576f3d 100644 --- a/WikipediaApi/WikipediaClient.cs +++ b/WikipediaApi/WikipediaClient.cs @@ -1,5 +1,4 @@ -using System; -using System.Net.Http; +using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using WikipediaApi.Page;