diff --git a/Geekbot.net/Commands/Admin.cs b/Geekbot.net/Commands/Admin.cs index 5191dcb..0b76b4b 100644 --- a/Geekbot.net/Commands/Admin.cs +++ b/Geekbot.net/Commands/Admin.cs @@ -13,12 +13,13 @@ namespace Geekbot.net.Commands [RequireUserPermission(GuildPermission.Administrator)] public class Admin : ModuleBase { - private readonly IDatabase _redis; private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; + private readonly IDatabase _redis; private readonly ITranslationHandler _translation; - - public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler, ITranslationHandler translationHandler) + + public Admin(IDatabase redis, DiscordSocketClient client, IErrorHandler errorHandler, + ITranslationHandler translationHandler) { _redis = redis; _client = client; @@ -31,7 +32,7 @@ namespace Geekbot.net.Commands [Summary("Set a Welcome Message (use '$user' to mention the new joined user).")] public async Task SetWelcomeMessage([Remainder] [Summary("message")] string welcomeMessage) { - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] { new HashEntry("WelcomeMsg", welcomeMessage) }); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("WelcomeMsg", welcomeMessage)}); var formatedMessage = welcomeMessage.Replace("$user", Context.User.Mention); await ReplyAsync("Welcome message has been changed\r\nHere is an example of how it would look:\r\n" + formatedMessage); @@ -49,7 +50,8 @@ namespace Geekbot.net.Commands sb.AppendLine("- `!admin showleave true` - send message to mod channel when someone leaves"); sb.AppendLine("- `!admin showdel true` - send message to mod channel when someone deletes a message"); await channel.SendMessageAsync(sb.ToString()); - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ModChannel", channel.Id.ToString())}); + _redis.HashSet($"{Context.Guild.Id}:Settings", + new[] {new HashEntry("ModChannel", channel.Id.ToString())}); } catch (Exception e) { @@ -69,20 +71,21 @@ namespace Geekbot.net.Commands if (enabled) { await modChannel.SendMessageAsync("Saved - now sending messages here when someone leaves"); - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowLeave", true)}); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", true)}); } else { await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone leaves"); - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowLeave", false)}); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowLeave", false)}); } } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context, "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); + _errorHandler.HandleCommandException(e, Context, + "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); } } - + [Command("showdel", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Notify modchannel when someone deletes a message")] @@ -94,21 +97,24 @@ namespace Geekbot.net.Commands var modChannel = (ISocketMessageChannel) _client.GetChannel(modChannelId); if (enabled) { - await modChannel.SendMessageAsync("Saved - now sending messages here when someone deletes a message"); - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowDelete", true)}); + await modChannel.SendMessageAsync( + "Saved - now sending messages here when someone deletes a message"); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", true)}); } else { - await modChannel.SendMessageAsync("Saved - stopping sending messages here when someone deletes a message"); - _redis.HashSet($"{Context.Guild.Id}:Settings", new HashEntry[] {new HashEntry("ShowDelete", false)}); + await modChannel.SendMessageAsync( + "Saved - stopping sending messages here when someone deletes a message"); + _redis.HashSet($"{Context.Guild.Id}:Settings", new[] {new HashEntry("ShowDelete", false)}); } } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context, "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); + _errorHandler.HandleCommandException(e, Context, + "Modchannel doesn't seem to exist, please set one with `!admin modchannel [channelId]`"); } } - + [Command("setlang", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Change the bots language")] @@ -124,6 +130,7 @@ namespace Geekbot.net.Commands await ReplyAsync(trans["NewLanguageSet"]); return; } + await ReplyAsync( $"That doesn't seem to be a supported language\r\nSupported Languages are {string.Join(", ", _translation.GetSupportedLanguages())}"); } @@ -132,7 +139,7 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + [Command("lang", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Change the bots language")] diff --git a/Geekbot.net/Commands/AvatarGetter.cs b/Geekbot.net/Commands/AvatarGetter.cs index 41be8af..9e31b6b 100644 --- a/Geekbot.net/Commands/AvatarGetter.cs +++ b/Geekbot.net/Commands/AvatarGetter.cs @@ -9,7 +9,7 @@ namespace Geekbot.net.Commands public class AvatarGetter : ModuleBase { private readonly IErrorHandler _errorHandler; - + public AvatarGetter(IErrorHandler errorHandler) { _errorHandler = errorHandler; @@ -18,14 +18,11 @@ 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 { - if (user == null) - { - user = Context.User; - } + if (user == null) user = Context.User; var url = user.GetAvatarUrl().Replace("128", "1024"); await ReplyAsync(url); } diff --git a/Geekbot.net/Commands/BattleTag.cs b/Geekbot.net/Commands/BattleTag.cs index e466abb..cbc5ecc 100644 --- a/Geekbot.net/Commands/BattleTag.cs +++ b/Geekbot.net/Commands/BattleTag.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using Discord.Commands; using Geekbot.net.Lib; -using StackExchange.Redis; namespace Geekbot.net.Commands { @@ -10,13 +9,11 @@ namespace Geekbot.net.Commands public class BattleTag : ModuleBase { private readonly IErrorHandler _errorHandler; - private readonly IDatabase _redis; private readonly IUserRepository _userRepository; - - public BattleTag(IErrorHandler errorHandler, IDatabase redis, IUserRepository userRepository) + + public BattleTag(IErrorHandler errorHandler, IUserRepository userRepository) { _errorHandler = errorHandler; - _redis = redis; _userRepository = userRepository; } @@ -29,21 +26,16 @@ namespace Geekbot.net.Commands { var tag = _userRepository.getUserSetting(Context.User.Id, "BattleTag"); if (!string.IsNullOrEmpty(tag)) - { - await ReplyAsync($"Your BattleTag is {tag}"); - } else - { await ReplyAsync("You haven't set your BattleTag, set it with `!battletag user#1234`"); - } } catch (Exception e) { _errorHandler.HandleCommandException(e, Context); } } - + [Command(RunMode = RunMode.Async)] [Remarks(CommandCategories.Games)] [Summary("Save your battletag")] @@ -71,7 +63,7 @@ namespace Geekbot.net.Commands { var splited = tag.Split("#"); if (splited.Length != 2) return false; - if (!int.TryParse(splited[1], out int discriminator)) 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; } diff --git a/Geekbot.net/Commands/Cat.cs b/Geekbot.net/Commands/Cat.cs index 57a3289..2120fe7 100644 --- a/Geekbot.net/Commands/Cat.cs +++ b/Geekbot.net/Commands/Cat.cs @@ -11,12 +11,12 @@ namespace Geekbot.net.Commands public class Cat : ModuleBase { private readonly IErrorHandler _errorHandler; - + public Cat(IErrorHandler errorHandler) { _errorHandler = errorHandler; } - + [Command("cat", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Return a random image of a cat.")] @@ -49,7 +49,7 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + private class CatResponse { public string file { get; set; } diff --git a/Geekbot.net/Commands/Changelog.cs b/Geekbot.net/Commands/Changelog.cs index 2354481..e060152 100644 --- a/Geekbot.net/Commands/Changelog.cs +++ b/Geekbot.net/Commands/Changelog.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; -using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Commands; @@ -15,15 +14,15 @@ namespace Geekbot.net.Commands { public class Changelog : ModuleBase { - private readonly IErrorHandler _errorHandler; private readonly DiscordSocketClient _client; - + private readonly IErrorHandler _errorHandler; + public Changelog(IErrorHandler errorHandler, DiscordSocketClient client) { _errorHandler = errorHandler; _client = client; } - + [Command("changelog", RunMode = RunMode.Async)] [Alias("updates")] [Remarks(CommandCategories.Helpers)] @@ -35,7 +34,8 @@ namespace Geekbot.net.Commands using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://api.github.com"); - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "http://developer.github.com/v3/#user-agent-required"); + client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", + "http://developer.github.com/v3/#user-agent-required"); var response = await client.GetAsync("/repos/pizzaandcoffee/geekbot.net/commits"); response.EnsureSuccessStatusCode(); @@ -43,7 +43,7 @@ namespace Geekbot.net.Commands var commits = JsonConvert.DeserializeObject>(stringResponse); var eb = new EmbedBuilder(); eb.WithColor(new Color(143, 165, 102)); - eb.WithAuthor(new EmbedAuthorBuilder() + eb.WithAuthor(new EmbedAuthorBuilder { IconUrl = _client.CurrentUser.GetAvatarUrl(), Name = "Latest Updates", @@ -51,11 +51,9 @@ 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})"); - } eb.Description = sb.ToString(); - eb.WithFooter(new EmbedFooterBuilder() + eb.WithFooter(new EmbedFooterBuilder { Text = $"List generated from github commits on {DateTime.Now:yyyy-MM-dd}" }); @@ -67,14 +65,14 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + private class Commit { public string sha { get; set; } public CommitInfo commit { get; set; } public Uri html_url { get; set; } } - + private class CommitInfo { public commitAuthor author { get; set; } diff --git a/Geekbot.net/Commands/CheckEm.cs b/Geekbot.net/Commands/CheckEm.cs index 1c488bd..11d0cef 100644 --- a/Geekbot.net/Commands/CheckEm.cs +++ b/Geekbot.net/Commands/CheckEm.cs @@ -11,8 +11,8 @@ namespace Geekbot.net.Commands public class CheckEm : ModuleBase { private readonly IMediaProvider _checkEmImages; - private readonly Random _rnd; private readonly IErrorHandler _errorHandler; + private readonly Random _rnd; public CheckEm(Random RandomClient, IMediaProvider mediaProvider, IErrorHandler errorHandler) { @@ -66,6 +66,7 @@ namespace Geekbot.net.Commands listOfInts.Add(num % 10); num = num / 10; } + listOfInts.Reverse(); return listOfInts.ToArray(); } diff --git a/Geekbot.net/Commands/Choose.cs b/Geekbot.net/Commands/Choose.cs index d8f1cf2..214a1a8 100644 --- a/Geekbot.net/Commands/Choose.cs +++ b/Geekbot.net/Commands/Choose.cs @@ -7,8 +7,8 @@ namespace Geekbot.net.Commands { public class Choose : ModuleBase { - private readonly Random _rnd; private readonly IErrorHandler _errorHandler; + private readonly Random _rnd; private readonly ITranslationHandler _translation; public Choose(Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation) @@ -21,7 +21,8 @@ namespace Geekbot.net.Commands [Command("choose", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Let the bot choose for you, seperate options with a semicolon.")] - public async Task Command([Remainder] [Summary("option1;option2")] string choices) + public async Task Command([Remainder] [Summary("option1;option2")] + string choices) { try { diff --git a/Geekbot.net/Commands/Dice.cs b/Geekbot.net/Commands/Dice.cs index edb155a..9195be8 100644 --- a/Geekbot.net/Commands/Dice.cs +++ b/Geekbot.net/Commands/Dice.cs @@ -10,11 +10,11 @@ namespace Geekbot.net.Commands { public class Dice : ModuleBase { - private readonly Random rnd; + private readonly Random _rnd; public Dice(Random RandomClient) { - rnd = RandomClient; + _rnd = RandomClient; } [Command("dice", RunMode = RunMode.Async)] @@ -39,6 +39,7 @@ namespace Geekbot.net.Commands await ReplyAsync("You can only have one mod"); return; } + mod = dice.mod; } } @@ -56,6 +57,7 @@ namespace Geekbot.net.Commands await ReplyAsync("You can't throw more than 20 dices"); return; } + if (dices.Any(d => d.sides > 120)) { await ReplyAsync("A dice can't have more than 120 sides"); @@ -73,32 +75,26 @@ namespace Geekbot.net.Commands var results = new List(); for (var i = 0; i < dice.times; i++) { - var roll = rnd.Next(1, dice.sides); + var roll = _rnd.Next(1, dice.sides); total += roll; results.Add(roll); - if (roll == dice.sides) - { - extraText = "**Critical Hit!**"; - } - if (roll == 1) - { - extraText = "**Critical Fail!**"; - } + if (roll == dice.sides) extraText = "**Critical Hit!**"; + if (roll == 1) extraText = "**Critical Fail!**"; } + resultStrings.Add($"{dice.diceType} ({string.Join(",", results)})"); } + rep.Append(string.Join(" + ", resultStrings)); if (mod != 0) { rep.Append($" + {mod}"); total += mod; } + rep.AppendLine(); rep.AppendLine($"**Total:** {total}"); - if (extraText != "") - { - rep.AppendLine(extraText); - } + if (extraText != "") rep.AppendLine(extraText); await ReplyAsync(rep.ToString()); } @@ -106,29 +102,25 @@ namespace Geekbot.net.Commands { var diceParts = dice.Split('d'); if (diceParts.Length == 2 - && int.TryParse(diceParts[0], out int times) - && int.TryParse(diceParts[1], out int max)) - { - return new DiceTypeDto() + && int.TryParse(diceParts[0], out var times) + && int.TryParse(diceParts[1], out var max)) + return new DiceTypeDto { diceType = dice, times = times, sides = max }; - } if (dice.Length == 1 - && int.TryParse(diceParts[0], out int mod)) - { - return new DiceTypeDto() + && int.TryParse(diceParts[0], out var mod)) + return new DiceTypeDto { mod = mod }; - } return new DiceTypeDto(); } } - class DiceTypeDto + internal class DiceTypeDto { public string diceType { get; set; } public int times { get; set; } diff --git a/Geekbot.net/Commands/Dog.cs b/Geekbot.net/Commands/Dog.cs index 978e5dd..485b7f0 100644 --- a/Geekbot.net/Commands/Dog.cs +++ b/Geekbot.net/Commands/Dog.cs @@ -11,12 +11,12 @@ namespace Geekbot.net.Commands public class Dog : ModuleBase { private readonly IErrorHandler _errorHandler; - + public Dog(IErrorHandler errorHandler) { _errorHandler = errorHandler; } - + [Command("dog", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Return a random image of a dog.")] @@ -49,7 +49,7 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + private class DogResponse { public string url { get; set; } diff --git a/Geekbot.net/Commands/EightBall.cs b/Geekbot.net/Commands/EightBall.cs index 4a369a4..5cadee5 100644 --- a/Geekbot.net/Commands/EightBall.cs +++ b/Geekbot.net/Commands/EightBall.cs @@ -8,8 +8,8 @@ namespace Geekbot.net.Commands { public class EightBall : ModuleBase { - private readonly Random _rnd; private readonly IErrorHandler _errorHandler; + private readonly Random _rnd; public EightBall(Random RandomClient, IErrorHandler errorHandler) { diff --git a/Geekbot.net/Commands/Emojify.cs b/Geekbot.net/Commands/Emojify.cs index 7d8d102..7bdbf8a 100644 --- a/Geekbot.net/Commands/Emojify.cs +++ b/Geekbot.net/Commands/Emojify.cs @@ -1,7 +1,5 @@ using System; -using System.Text; using System.Threading.Tasks; -using Discord; using Discord.Commands; using Geekbot.net.Lib; @@ -9,38 +7,31 @@ namespace Geekbot.net.Commands { public class Emojify : ModuleBase { - private readonly IErrorHandler _errorHandler; private readonly IEmojiConverter _emojiConverter; + private readonly IErrorHandler _errorHandler; public Emojify(IErrorHandler errorHandler, IEmojiConverter emojiConverter) { _errorHandler = errorHandler; _emojiConverter = emojiConverter; } - + [Command("emojify", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Emojify text")] - public async Task Dflt([Remainder, Summary("text")] string text) + public async Task Dflt([Remainder] [Summary("text")] string text) { try { - var sb = new StringBuilder(); var emojis = _emojiConverter.textToEmoji(text); if (emojis.Length > 1999) { await ReplyAsync("I can't take that much at once!"); return; } - var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder() - { - IconUrl = Context.User.GetAvatarUrl(), - Name = $"{Context.User.Username}#{Context.User.Discriminator}" - }); - eb.WithColor(new Color(59, 136, 195)); - eb.Description = emojis; - await ReplyAsync("", false, eb.Build()); + + await ReplyAsync($"{Context.User.Username}#{Context.User.Discriminator} said:"); + await ReplyAsync(emojis); } catch (Exception e) { diff --git a/Geekbot.net/Commands/Fortune.cs b/Geekbot.net/Commands/Fortune.cs index ba4bc07..1335139 100644 --- a/Geekbot.net/Commands/Fortune.cs +++ b/Geekbot.net/Commands/Fortune.cs @@ -7,11 +7,11 @@ namespace Geekbot.net.Commands { public class Fortune : ModuleBase { - private readonly IFortunesProvider fortunes; + private readonly IFortunesProvider _fortunes; public Fortune(IFortunesProvider fortunes) { - this.fortunes = fortunes; + _fortunes = fortunes; } [Command("fortune", RunMode = RunMode.Async)] @@ -19,7 +19,7 @@ namespace Geekbot.net.Commands [Summary("Get a random fortune")] public async Task GetAFortune() { - await ReplyAsync(fortunes.GetRandomFortune()); + await ReplyAsync(_fortunes.GetRandomFortune()); } } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Google.cs b/Geekbot.net/Commands/Google.cs deleted file mode 100644 index 16151c5..0000000 --- a/Geekbot.net/Commands/Google.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System.Threading.Tasks; -using Discord.Commands; -using Geekbot.net.Lib; - -namespace Geekbot.net.Commands -{ - public class Google : ModuleBase - { - [Command("google", RunMode = RunMode.Async)] - [Remarks(CommandCategories.Fun)] - [Summary("Google Something.")] - public async Task Eyes([Remainder, Summary("SearchText")] string searchText) - { - var url = $"http://lmgtfy.com/?q={searchText.Replace(' ', '+')}"; - - await ReplyAsync($"Please click here :unamused:\r\n{url}"); - } - } -} \ No newline at end of file diff --git a/Geekbot.net/Commands/GuildInfo.cs b/Geekbot.net/Commands/GuildInfo.cs index f195472..2ca76c6 100644 --- a/Geekbot.net/Commands/GuildInfo.cs +++ b/Geekbot.net/Commands/GuildInfo.cs @@ -10,9 +10,9 @@ namespace Geekbot.net.Commands { public class GuildInfo : ModuleBase { - private readonly IDatabase _redis; - private readonly ILevelCalc _levelCalc; private readonly IErrorHandler _errorHandler; + private readonly ILevelCalc _levelCalc; + private readonly IDatabase _redis; public GuildInfo(IDatabase redis, ILevelCalc levelCalc, IErrorHandler errorHandler) { diff --git a/Geekbot.net/Commands/Info.cs b/Geekbot.net/Commands/Info.cs index 7f7f6f4..e8c35dc 100644 --- a/Geekbot.net/Commands/Info.cs +++ b/Geekbot.net/Commands/Info.cs @@ -12,10 +12,10 @@ namespace Geekbot.net.Commands { public class Info : ModuleBase { - private readonly IDatabase _redis; - private readonly IErrorHandler _errorHandler; private readonly DiscordSocketClient _client; private readonly CommandService _commands; + private readonly IErrorHandler _errorHandler; + private readonly IDatabase _redis; public Info(IDatabase redis, IErrorHandler errorHandler, DiscordSocketClient client, CommandService commands) { @@ -33,30 +33,30 @@ namespace Geekbot.net.Commands try { var eb = new EmbedBuilder(); - + eb.WithAuthor(new EmbedAuthorBuilder() .WithIconUrl(_client.CurrentUser.GetAvatarUrl()) .WithName($"{Constants.Name} V{Constants.BotVersion}")); var botOwner = await Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))); - var uptime = (DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime)); - + var uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime); + eb.AddInlineField("Bot Name", _client.CurrentUser.Username); eb.AddInlineField("Bot Owner", $"{botOwner.Username}#{botOwner.Discriminator}"); eb.AddInlineField("Library", "Discord.NET V1.0.2"); eb.AddInlineField("Uptime", $"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S"); eb.AddInlineField("Servers", Context.Client.GetGuildsAsync().Result.Count); eb.AddInlineField("Total Commands", _commands.Commands.Count()); - + eb.AddField("Website", "https://geekbot.pizzaandcoffee.rocks/"); await ReplyAsync("", false, eb.Build()); } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context); + _errorHandler.HandleCommandException(e, Context); } } - + [Command("uptime", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Get the Bot Uptime")] @@ -64,12 +64,12 @@ namespace Geekbot.net.Commands { try { - var uptime = (DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime)); + var uptime = DateTime.Now.Subtract(Process.GetCurrentProcess().StartTime); await ReplyAsync($"{uptime.Days}D {uptime.Hours}H {uptime.Minutes}M {uptime.Seconds}S"); } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context); + _errorHandler.HandleCommandException(e, Context); } } } diff --git a/Geekbot.net/Commands/Counters.cs b/Geekbot.net/Commands/Karma.cs similarity index 87% rename from Geekbot.net/Commands/Counters.cs rename to Geekbot.net/Commands/Karma.cs index b999eeb..1affa82 100644 --- a/Geekbot.net/Commands/Counters.cs +++ b/Geekbot.net/Commands/Karma.cs @@ -3,18 +3,17 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Lib; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Commands { - public class Counters : ModuleBase + public class Karma : ModuleBase { - private readonly IDatabase _redis; private readonly IErrorHandler _errorHandler; + private readonly IDatabase _redis; private readonly ITranslationHandler _translation; - public Counters(IDatabase redis, IErrorHandler errorHandler, ITranslationHandler translation) + public Karma(IDatabase redis, IErrorHandler errorHandler, ITranslationHandler translation) { _redis = redis; _errorHandler = errorHandler; @@ -37,13 +36,14 @@ namespace Geekbot.net.Commands } else if (TimeoutFinished(lastKarma)) { - await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, GetTimeLeft(lastKarma))); + await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, + GetTimeLeft(lastKarma))); } - else + else { var newKarma = _redis.HashIncrement($"{Context.Guild.Id}:Karma", user.Id.ToString()); _redis.HashSet($"{Context.Guild.Id}:KarmaTimeout", - new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))}); + new[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString("u"))}); var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder() @@ -80,13 +80,14 @@ namespace Geekbot.net.Commands } else if (TimeoutFinished(lastKarma)) { - await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, GetTimeLeft(lastKarma))); + await ReplyAsync(string.Format(transDict["WaitUntill"], Context.User.Username, + GetTimeLeft(lastKarma))); } else { var newKarma = _redis.HashDecrement($"{Context.Guild.Id}:Karma", user.Id.ToString()); _redis.HashSet($"{Context.Guild.Id}:KarmaTimeout", - new HashEntry[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())}); + new[] {new HashEntry(Context.User.Id.ToString(), DateTimeOffset.Now.ToString())}); var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder() @@ -109,15 +110,16 @@ namespace Geekbot.net.Commands private DateTimeOffset ConvertToDateTimeOffset(string dateTimeOffsetString) { - if(string.IsNullOrEmpty(dateTimeOffsetString)) return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)); + if (string.IsNullOrEmpty(dateTimeOffsetString)) + return DateTimeOffset.Now.Subtract(new TimeSpan(7, 18, 0, 0)); return DateTimeOffset.Parse(dateTimeOffsetString); } - + private bool TimeoutFinished(DateTimeOffset lastKarma) { return lastKarma.AddMinutes(3) > DateTimeOffset.Now; } - + private string GetTimeLeft(DateTimeOffset lastKarma) { var dt = lastKarma.AddMinutes(3).Subtract(DateTimeOffset.Now); diff --git a/Geekbot.net/Commands/MagicTheGathering.cs b/Geekbot.net/Commands/MagicTheGathering.cs index 219e5f8..e2702b1 100644 --- a/Geekbot.net/Commands/MagicTheGathering.cs +++ b/Geekbot.net/Commands/MagicTheGathering.cs @@ -1,24 +1,20 @@ using System; using System.Collections.Generic; -using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Lib; using MtgApiManager.Lib.Service; -using Serilog; namespace Geekbot.net.Commands { public class Magicthegathering : ModuleBase { - private ILogger _logger; - private IErrorHandler _errorHandler; + private readonly IErrorHandler _errorHandler; - public Magicthegathering(ILogger logger, IErrorHandler errorHandler) + public Magicthegathering(IErrorHandler errorHandler) { - _logger = logger; _errorHandler = errorHandler; } @@ -38,26 +34,28 @@ namespace Geekbot.net.Commands await ReplyAsync("I couldn't find that card..."); return; } + var eb = new EmbedBuilder(); eb.Title = card.Name; eb.Description = card.Type; - + if (card.Colors != null) eb.WithColor(GetColor(card.Colors)); if (card.ImageUrl != null) eb.ImageUrl = card.ImageUrl.ToString(); if (!string.IsNullOrEmpty(card.Text)) eb.AddField("Text", card.Text); - + if (!string.IsNullOrEmpty(card.Flavor)) eb.AddField("Flavor", card.Flavor); if (!string.IsNullOrEmpty(card.SetName)) eb.AddInlineField("Set", card.SetName); if (!string.IsNullOrEmpty(card.Power)) eb.AddInlineField("Power", card.Power); if (!string.IsNullOrEmpty(card.Loyalty)) eb.AddInlineField("Loyality", card.Loyalty); if (!string.IsNullOrEmpty(card.Toughness)) eb.AddInlineField("Thoughness", card.Toughness); - + if (!string.IsNullOrEmpty(card.ManaCost)) eb.AddInlineField("Cost", card.ManaCost); if (!string.IsNullOrEmpty(card.Rarity)) eb.AddInlineField("Rarity", card.Rarity); - - if (card.Legalities != null) eb.AddField("Legality", string.Join(", ", card.Legalities.Select(e => e.Format))); + + if (card.Legalities != null) + eb.AddField("Legality", string.Join(", ", card.Legalities.Select(e => e.Format))); await ReplyAsync("", false, eb.Build()); } diff --git a/Geekbot.net/Commands/Mod.cs b/Geekbot.net/Commands/Mod.cs index 01c4bd7..c927b0d 100644 --- a/Geekbot.net/Commands/Mod.cs +++ b/Geekbot.net/Commands/Mod.cs @@ -15,19 +15,20 @@ namespace Geekbot.net.Commands [RequireUserPermission(GuildPermission.ManageRoles)] public class Mod : ModuleBase { - private readonly IUserRepository _userRepository; + private readonly DiscordSocketClient _client; private readonly IErrorHandler _errorHandler; private readonly IDatabase _redis; - private readonly DiscordSocketClient _client; - - public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis, DiscordSocketClient client) + private readonly IUserRepository _userRepository; + + public Mod(IUserRepository userRepositry, IErrorHandler errorHandler, IDatabase redis, + DiscordSocketClient client) { _userRepository = userRepositry; _errorHandler = errorHandler; _redis = redis; _client = client; } - + [Command("namehistory", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("See past usernames of an user")] @@ -38,30 +39,26 @@ namespace Geekbot.net.Commands var userRepo = _userRepository.Get(user.Id); var sb = new StringBuilder(); sb.AppendLine($":bust_in_silhouette: {user.Username} has been known as:"); - foreach (var name in userRepo.UsedNames) - { - sb.AppendLine($"- `{name}`"); - } + foreach (var name in userRepo.UsedNames) sb.AppendLine($"- `{name}`"); await ReplyAsync(sb.ToString()); } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context, $"I don't have enough permissions to give {user.Username} that role"); + _errorHandler.HandleCommandException(e, Context, + $"I don't have enough permissions to give {user.Username} that role"); } } - + [Command("kick", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Ban a user")] - public async Task kick([Summary("@user")] IUser userNormal, [Summary("reason"), Remainder] string reason = "none") + public async Task kick([Summary("@user")] IUser userNormal, + [Summary("reason")] [Remainder] string reason = "none") { try { - var user = (IGuildUser)userNormal; - if (reason == "none") - { - reason = "No reason provided"; - } + var user = (IGuildUser) userNormal; + if (reason == "none") reason = "No reason provided"; await user.GetOrCreateDMChannelAsync().Result.SendMessageAsync( $"You have been kicked from {Context.Guild.Name} for the following reason: \"{reason}\""); await user.KickAsync(); diff --git a/Geekbot.net/Commands/Overwatch.cs b/Geekbot.net/Commands/Overwatch.cs index 3527cdf..9007804 100644 --- a/Geekbot.net/Commands/Overwatch.cs +++ b/Geekbot.net/Commands/Overwatch.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Lib; -using Google.Apis.Util; using OverwatchAPI; using OverwatchAPI.Config; using Serilog; @@ -17,7 +16,7 @@ namespace Geekbot.net.Commands private readonly IErrorHandler _errorHandler; private readonly ILogger _logger; private readonly IUserRepository _userRepository; - + public Overwatch(IErrorHandler errorHandler, ILogger logger, IDatabase redis, IUserRepository userRepository) { _errorHandler = errorHandler; @@ -38,21 +37,22 @@ namespace Geekbot.net.Commands await ReplyAsync("You have no battle Tag saved, use `!battletag`"); return; } + var profile = await createProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); return; } - await ReplyAsync("", false, profile.Build()); + await ReplyAsync("", false, profile.Build()); } catch (Exception e) { _errorHandler.HandleCommandException(e, Context); } } - + [Command("profile", RunMode = RunMode.Async)] [Summary("Get someones overwatch profile. EU on PC only. Default battletag is your own (if set).")] [Remarks(CommandCategories.Games)] @@ -65,12 +65,14 @@ namespace Geekbot.net.Commands await ReplyAsync("That doesn't seem to be a valid battletag..."); return; } + var profile = await createProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); return; } + await ReplyAsync("", false, profile.Build()); } catch (Exception e) @@ -92,12 +94,14 @@ namespace Geekbot.net.Commands await ReplyAsync("This user didn't set a battletag"); return; } + var profile = await createProfile(tag); if (profile == null) { await ReplyAsync("That player doesn't seem to exist"); return; } + await ReplyAsync("", false, profile.Build()); } catch (Exception e) @@ -112,10 +116,7 @@ namespace Geekbot.net.Commands using (var owClient = new OverwatchClient(owConfig)) { var player = await owClient.GetPlayerAsync(battletag); - if (player.Username == null) - { - return null; - } + if (player.Username == null) return null; _logger.Debug($"[OW] Username = {player.Username}"); var eb = new EmbedBuilder(); eb.WithAuthor(new EmbedAuthorBuilder() @@ -123,10 +124,11 @@ namespace Geekbot.net.Commands .WithName(player.Username)); eb.Url = player.ProfileUrl; eb.AddInlineField("Level", player.PlayerLevel); - eb.AddInlineField("Current Rank", player.CompetitiveRank > 0 ? player.CompetitiveRank.ToString() : "Unranked"); + eb.AddInlineField("Current Rank", + player.CompetitiveRank > 0 ? player.CompetitiveRank.ToString() : "Unranked"); return eb; } } } -} +} \ No newline at end of file diff --git a/Geekbot.net/Commands/Owner.cs b/Geekbot.net/Commands/Owner.cs index c05700c..c3c9cc0 100644 --- a/Geekbot.net/Commands/Owner.cs +++ b/Geekbot.net/Commands/Owner.cs @@ -13,13 +13,14 @@ namespace Geekbot.net.Commands [RequireUserPermission(GuildPermission.Administrator)] public class Owner : ModuleBase { - private readonly IDatabase _redis; private readonly DiscordSocketClient _client; - private readonly ILogger _logger; - private readonly IUserRepository _userRepository; private readonly IErrorHandler _errorHandler; - - public Owner(IDatabase redis, DiscordSocketClient client, ILogger logger, IUserRepository userRepositry, IErrorHandler errorHandler) + private readonly ILogger _logger; + private readonly IDatabase _redis; + private readonly IUserRepository _userRepository; + + public Owner(IDatabase redis, DiscordSocketClient client, ILogger logger, IUserRepository userRepositry, + IErrorHandler errorHandler) { _redis = redis; _client = client; @@ -27,7 +28,7 @@ namespace Geekbot.net.Commands _userRepository = userRepositry; _errorHandler = errorHandler; } - + [Command("youtubekey", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Set the youtube api key")] @@ -36,14 +37,15 @@ namespace Geekbot.net.Commands var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result; if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString())) { - await ReplyAsync($"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); + await ReplyAsync( + $"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); return; } _redis.StringSet("youtubeKey", key); await ReplyAsync("Apikey has been set"); } - + [Command("game", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Set the game that the bot is playing")] @@ -52,7 +54,8 @@ namespace Geekbot.net.Commands var botOwner = Context.Guild.GetUserAsync(ulong.Parse(_redis.StringGet("botOwner"))).Result; if (!Context.User.Id.ToString().Equals(botOwner.Id.ToString())) { - await ReplyAsync($"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); + await ReplyAsync( + $"Sorry, only the botowner can do this ({botOwner.Username}#{botOwner.Discriminator})"); return; } @@ -61,7 +64,7 @@ namespace Geekbot.net.Commands _logger.Information($"[Geekbot] Changed game to {key}"); await ReplyAsync($"Now Playing {key}"); } - + [Command("popuserrepo", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] [Summary("Populate user cache")] @@ -83,6 +86,7 @@ namespace Geekbot.net.Commands $"Sorry, only the botowner can do this"); return; } + var success = 0; var failed = 0; try @@ -98,12 +102,15 @@ namespace Geekbot.net.Commands var inc = succeded ? success++ : failed++; } } + _logger.Warning("[UserRepository] Finished Updating User Repositry"); - await ReplyAsync($"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})"); + await ReplyAsync( + $"Successfully Populated User Repository with {success} Users in {_client.Guilds.Count} Guilds (Failed: {failed})"); } catch (Exception e) { - _errorHandler.HandleCommandException(e, Context, "Couldn't complete User Repository, see console for more info"); + _errorHandler.HandleCommandException(e, Context, + "Couldn't complete User Repository, see console for more info"); } } } diff --git a/Geekbot.net/Commands/Pokedex.cs b/Geekbot.net/Commands/Pokedex.cs index b187841..2b43693 100644 --- a/Geekbot.net/Commands/Pokedex.cs +++ b/Geekbot.net/Commands/Pokedex.cs @@ -5,14 +5,13 @@ using Discord; using Discord.Commands; using Geekbot.net.Lib; using PokeAPI; -using Serilog; namespace Geekbot.net.Commands { public class Pokedex : ModuleBase { private readonly IErrorHandler _errorHandler; - + public Pokedex(IErrorHandler errorHandler) { _errorHandler = errorHandler; @@ -36,6 +35,7 @@ namespace Geekbot.net.Commands await ReplyAsync("I couldn't find that pokemon :confused:"); return; } + var embed = await pokemonEmbedBuilder(pokemon); await ReplyAsync("", false, embed.Build()); } @@ -52,8 +52,10 @@ namespace Geekbot.net.Commands 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; @@ -61,22 +63,14 @@ namespace Geekbot.net.Commands private string getSingularOrPlural(int lenght, string word) { - if (lenght == 1) - { - return word; - } - return word.EndsWith("y") ? $"{word.Remove(word.Length-1)}ies" : $"{word}s"; + if (lenght == 1) return word; + return word.EndsWith("y") ? $"{word.Remove(word.Length - 1)}ies" : $"{word}s"; } - + private string toUpper(string s) { - if (string.IsNullOrEmpty(s)) - { - return string.Empty; - } + if (string.IsNullOrEmpty(s)) return string.Empty; return char.ToUpper(s[0]) + s.Substring(1); } - - } } \ No newline at end of file diff --git a/Geekbot.net/Commands/Poll.cs b/Geekbot.net/Commands/Poll.cs index ae2ae77..51b6742 100644 --- a/Geekbot.net/Commands/Poll.cs +++ b/Geekbot.net/Commands/Poll.cs @@ -14,12 +14,13 @@ namespace Geekbot.net.Commands [Group("poll")] public class Poll : ModuleBase { + private readonly IEmojiConverter _emojiConverter; private readonly IErrorHandler _errorHandler; private readonly IDatabase _redis; - private readonly IEmojiConverter _emojiConverter; private readonly IUserRepository _userRepository; - public Poll(IErrorHandler errorHandler, IDatabase redis, IEmojiConverter emojiConverter, IUserRepository userRepository) + public Poll(IErrorHandler errorHandler, IDatabase redis, IEmojiConverter emojiConverter, + IUserRepository userRepository) { _errorHandler = errorHandler; _redis = redis; @@ -41,6 +42,7 @@ namespace Geekbot.net.Commands "There is no poll in this channel ongoing at the moment\r\nYou can create one with `!poll create question;option1;option2;option3`"); return; } + await ReplyAsync("There is a poll running at the moment"); } catch (Exception e) @@ -48,11 +50,12 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + [Command("create", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Create a poll")] - public async Task Create([Remainder, Summary("question;option1;option2")] string rawPollString) + public async Task Create([Remainder] [Summary("question;option1;option2")] + string rawPollString) { try { @@ -62,6 +65,7 @@ namespace Geekbot.net.Commands await ReplyAsync("You have not finished you last poll yet. To finish it use `!poll end`"); return; } + var pollList = rawPollString.Split(';').ToList(); if (pollList.Count <= 2) { @@ -88,7 +92,7 @@ namespace Geekbot.net.Commands pollMessage.AddReactionAsync(new Emoji(_emojiConverter.numberToEmoji(i))); i++; }); - var poll = new PollData() + var poll = new PollData { Creator = Context.User.Id, MessageId = pollMessage.Id, @@ -97,14 +101,14 @@ namespace Geekbot.net.Commands Options = pollList }; var pollJson = JsonConvert.SerializeObject(poll); - _redis.HashSet($"{Context.Guild.Id}:Polls", new HashEntry[] {new HashEntry(Context.Channel.Id, pollJson)}); + _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)}); } catch (Exception e) { _errorHandler.HandleCommandException(e, Context); } } - + [Command("end", RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("End the current poll")] @@ -118,18 +122,16 @@ namespace Geekbot.net.Commands await ReplyAsync("There is no ongoing poll at the moment"); return; } + var results = await getPollResults(currentPoll); var sb = new StringBuilder(); sb.AppendLine("**Poll Results**"); sb.AppendLine(currentPoll.Question); - foreach (var result in results) - { - sb.AppendLine($"{result.VoteCount} - {result.Option}"); - } + foreach (var result in results) sb.AppendLine($"{result.VoteCount} - {result.Option}"); await ReplyAsync(sb.ToString()); currentPoll.IsFinshed = true; var pollJson = JsonConvert.SerializeObject(currentPoll); - _redis.HashSet($"{Context.Guild.Id}:Polls", new HashEntry[] {new HashEntry(Context.Channel.Id, pollJson)}); + _redis.HashSet($"{Context.Guild.Id}:Polls", new[] {new HashEntry(Context.Channel.Id, pollJson)}); } catch (Exception e) { @@ -144,7 +146,7 @@ namespace Geekbot.net.Commands var currentPoll = _redis.HashGet($"{Context.Guild.Id}:Polls", Context.Channel.Id); return JsonConvert.DeserializeObject(currentPoll.ToString()); } - catch + catch { return new PollData(); } @@ -152,14 +154,13 @@ namespace Geekbot.net.Commands private async Task> getPollResults(PollData poll) { - var message = (IUserMessage)(await Context.Channel.GetMessageAsync(poll.MessageId)); + var message = (IUserMessage) await Context.Channel.GetMessageAsync(poll.MessageId); var results = new List(); foreach (var r in message.Reactions) - { try { var option = int.Parse(r.Key.Name.ToCharArray()[0].ToString()); - var result = new PollResult() + var result = new PollResult { Option = poll.Options[option - 1], VoteCount = r.Value.ReactionCount @@ -167,8 +168,8 @@ namespace Geekbot.net.Commands results.Add(result); } catch {} - } - results.Sort((x,y) => y.VoteCount.CompareTo(x.VoteCount)); + + results.Sort((x, y) => y.VoteCount.CompareTo(x.VoteCount)); return results; } @@ -180,7 +181,7 @@ namespace Geekbot.net.Commands public string Question { get; set; } public List Options { get; set; } } - + private class PollResult { public string Option { get; set; } diff --git a/Geekbot.net/Commands/Quote.cs b/Geekbot.net/Commands/Quote.cs index d6eae26..5b7e2ee 100644 --- a/Geekbot.net/Commands/Quote.cs +++ b/Geekbot.net/Commands/Quote.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Discord; using Discord.Commands; using Geekbot.net.Lib; using Newtonsoft.Json; -using Serilog; using StackExchange.Redis; namespace Geekbot.net.Commands @@ -14,23 +12,21 @@ namespace Geekbot.net.Commands [Group("quote")] public class Quote : ModuleBase { - private readonly IDatabase redis; - private readonly ILogger logger; private readonly IErrorHandler errorHandler; - - public Quote(IDatabase redis, ILogger logger, IErrorHandler errorHandler) + private readonly IDatabase redis; + + public Quote(IDatabase redis, IErrorHandler errorHandler) { this.redis = redis; - this.logger = logger; this.errorHandler = errorHandler; } - [Command()] + [Command] [Remarks(CommandCategories.Quotes)] [Summary("Return a random quoute from the database")] public async Task getRandomQuote() { - var randomQuote = redis.SetRandomMember($"{Context.Guild.Id}:Quotes"); + var randomQuote = redis.SetRandomMember($"{Context.Guild.Id}:Quotes"); try { var quote = JsonConvert.DeserializeObject(randomQuote); @@ -42,7 +38,7 @@ namespace Geekbot.net.Commands errorHandler.HandleCommandException(e, Context, "Whoops, seems like the quote was to edgy to return"); } } - + [Command("save")] [Remarks(CommandCategories.Quotes)] [Summary("Save a quote from the last sent message by @user")] @@ -55,11 +51,13 @@ namespace Geekbot.net.Commands await ReplyAsync("You can't save your own quotes..."); return; } + if (user.IsBot) { await ReplyAsync("You can't save quotes by a bot..."); return; } + var lastMessage = await getLastMessageByUser(user); var quote = createQuoteObject(lastMessage); var quoteStore = JsonConvert.SerializeObject(quote); @@ -69,10 +67,11 @@ namespace Geekbot.net.Commands } catch (Exception e) { - errorHandler.HandleCommandException(e, Context, "I counldn't find a quote from that user :disappointed:"); + errorHandler.HandleCommandException(e, Context, + "I counldn't find a quote from that user :disappointed:"); } } - + [Command("save")] [Remarks(CommandCategories.Quotes)] [Summary("Save a quote from a message id")] @@ -86,24 +85,26 @@ namespace Geekbot.net.Commands await ReplyAsync("You can't save your own quotes..."); return; } + if (message.Author.IsBot) { await ReplyAsync("You can't save quotes by a bot..."); return; } + var quote = createQuoteObject(message); var quoteStore = JsonConvert.SerializeObject(quote); redis.SetAdd($"{Context.Guild.Id}:Quotes", quoteStore); var embed = quoteBuilder(quote); await ReplyAsync("**Quote Added**", false, embed.Build()); - } catch (Exception e) { - errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); + errorHandler.HandleCommandException(e, Context, + "I couldn't find a message with that id :disappointed:"); } } - + [Command("make")] [Remarks(CommandCategories.Quotes)] [Summary("Create a quote from the last sent message by @user")] @@ -118,10 +119,11 @@ namespace Geekbot.net.Commands } catch (Exception e) { - errorHandler.HandleCommandException(e, Context, "I counldn't find a quote from that user :disappointed:"); + errorHandler.HandleCommandException(e, Context, + "I counldn't find a quote from that user :disappointed:"); } } - + [Command("make")] [Remarks(CommandCategories.Quotes)] [Summary("Create a quote from a message id")] @@ -136,21 +138,22 @@ namespace Geekbot.net.Commands } catch (Exception e) { - errorHandler.HandleCommandException(e, Context, "I couldn't find a message with that id :disappointed:"); + errorHandler.HandleCommandException(e, Context, + "I couldn't find a message with that id :disappointed:"); } } private async Task getLastMessageByUser(IUser user) { - Task> list = Context.Channel.GetMessagesAsync().Flatten(); + var list = Context.Channel.GetMessagesAsync().Flatten(); await list; return list.Result - .First(msg => msg.Author.Id == user.Id - && msg.Embeds.Count == 0 - && msg.Id != Context.Message.Id - && !msg.Content.ToLower().StartsWith("!")); + .First(msg => msg.Author.Id == user.Id + && msg.Embeds.Count == 0 + && msg.Id != Context.Message.Id + && !msg.Content.ToLower().StartsWith("!")); } - + private EmbedBuilder quoteBuilder(QuoteObject quote) { var user = Context.Client.GetUserAsync(quote.userId).Result; @@ -159,10 +162,7 @@ namespace Geekbot.net.Commands 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; } @@ -177,7 +177,8 @@ namespace Geekbot.net.Commands { image = null; } - return new QuoteObject() + + return new QuoteObject { userId = message.Author.Id, time = message.Timestamp.DateTime, @@ -186,8 +187,9 @@ namespace Geekbot.net.Commands }; } } - - public class QuoteObject { + + public class QuoteObject + { public ulong userId { get; set; } public string quote { get; set; } public DateTime time { get; set; } diff --git a/Geekbot.net/Commands/RandomAnimals.cs b/Geekbot.net/Commands/RandomAnimals.cs index 7d1f723..29930eb 100644 --- a/Geekbot.net/Commands/RandomAnimals.cs +++ b/Geekbot.net/Commands/RandomAnimals.cs @@ -8,12 +8,12 @@ namespace Geekbot.net.Commands public class RandomAnimals : ModuleBase { private readonly IMediaProvider _mediaProvider; - + public RandomAnimals(IMediaProvider mediaProvider) { _mediaProvider = mediaProvider; } - + [Command("panda", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random panda image")] @@ -21,7 +21,7 @@ namespace Geekbot.net.Commands { await ReplyAsync(_mediaProvider.getPanda()); } - + [Command("croissant", RunMode = RunMode.Async)] [Alias("gipfeli")] [Remarks(CommandCategories.Randomness)] @@ -30,7 +30,7 @@ namespace Geekbot.net.Commands { await ReplyAsync(_mediaProvider.getCrossant()); } - + [Command("pumpkin", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random pumpkin image")] @@ -38,7 +38,7 @@ namespace Geekbot.net.Commands { await ReplyAsync(_mediaProvider.getPumpkin()); } - + [Command("squirrel", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random squirrel image")] @@ -46,7 +46,7 @@ namespace Geekbot.net.Commands { await ReplyAsync(_mediaProvider.getSquirrel()); } - + [Command("turtle", RunMode = RunMode.Async)] [Remarks(CommandCategories.Randomness)] [Summary("Get a random turtle image")] diff --git a/Geekbot.net/Commands/Rank.cs b/Geekbot.net/Commands/Rank.cs index 2c232f9..4052d4c 100644 --- a/Geekbot.net/Commands/Rank.cs +++ b/Geekbot.net/Commands/Rank.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using Discord; using Discord.Commands; using Geekbot.net.Lib; using Serilog; @@ -13,13 +12,14 @@ namespace Geekbot.net.Commands { public class Rank : ModuleBase { - private readonly IDatabase _redis; + private readonly IEmojiConverter _emojiConverter; private readonly IErrorHandler _errorHandler; private readonly ILogger _logger; + private readonly IDatabase _redis; private readonly IUserRepository _userRepository; - private readonly IEmojiConverter _emojiConverter; - - public Rank(IDatabase redis, IErrorHandler errorHandler, ILogger logger, IUserRepository userRepository, IEmojiConverter emojiConverter) + + public Rank(IDatabase redis, IErrorHandler errorHandler, ILogger logger, IUserRepository userRepository, + IEmojiConverter emojiConverter) { _redis = redis; _errorHandler = errorHandler; @@ -27,11 +27,12 @@ namespace Geekbot.net.Commands _userRepository = userRepository; _emojiConverter = emojiConverter; } - + [Command("rank", RunMode = RunMode.Async)] [Remarks(CommandCategories.Statistics)] [Summary("get user top 10 in messages or karma")] - public async Task RankCmd([Summary("type")] string typeUnformated = "messages", [Summary("amount")] int amount = 10) + public async Task RankCmd([Summary("type")] string typeUnformated = "messages", + [Summary("amount")] int amount = 10) { try { @@ -42,7 +43,7 @@ namespace Geekbot.net.Commands await ReplyAsync("Valid types are '`messages`' '`karma`', '`rolls`'"); return; } - + var replyBuilder = new StringBuilder(); if (amount > 20) @@ -50,7 +51,7 @@ namespace Geekbot.net.Commands replyBuilder.AppendLine(":warning: Limiting to 20"); amount = 20; } - + var messageList = _redis.HashGetAll($"{Context.Guild.Id}:{type}"); var sortedList = messageList.OrderByDescending(e => e.Value).ToList(); var guildMessages = (int) sortedList.First().Value; @@ -64,10 +65,10 @@ namespace Geekbot.net.Commands if (listLimiter > amount) break; try { - var guildUser = _userRepository.Get((ulong)user.Name); + var guildUser = _userRepository.Get((ulong) user.Name); if (guildUser.Username != null) { - highscoreUsers.Add(new RankUserPolyfill() + highscoreUsers.Add(new RankUserPolyfill { Username = guildUser.Username, Discriminator = guildUser.Discriminator @@ -75,21 +76,21 @@ namespace Geekbot.net.Commands } else { - highscoreUsers.Add(new RankUserPolyfill() + highscoreUsers.Add(new RankUserPolyfill { Id = user.Name }, (int) user.Value); failedToRetrieveUser = true; } + listLimiter++; } catch (Exception e) { _logger.Warning(e, $"Could not retrieve user {user.Name}"); } - } - + if (failedToRetrieveUser) replyBuilder.AppendLine(":warning: Couldn't get all userdata\n"); replyBuilder.AppendLine($":bar_chart: **{type} Highscore for {Context.Guild.Name}**"); var highscorePlace = 1; @@ -114,13 +115,14 @@ namespace Geekbot.net.Commands break; case "Rolls": replyBuilder.Append($" - {user.Value} Guessed"); - break; + break; } replyBuilder.Append("\n"); - + highscorePlace++; } + await ReplyAsync(replyBuilder.ToString()); } catch (Exception e) @@ -129,8 +131,8 @@ namespace Geekbot.net.Commands } } } - - class RankUserPolyfill + + internal class RankUserPolyfill { public string Username { get; set; } public string Discriminator { get; set; } diff --git a/Geekbot.net/Commands/Role.cs b/Geekbot.net/Commands/Role.cs index f40ccf1..77e917f 100644 --- a/Geekbot.net/Commands/Role.cs +++ b/Geekbot.net/Commands/Role.cs @@ -2,7 +2,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -using AngleSharp; using Discord; using Discord.Commands; using Discord.Net; @@ -16,13 +15,13 @@ namespace Geekbot.net.Commands { private readonly IErrorHandler _errorHandler; private readonly IDatabase _redis; - + public Role(IErrorHandler errorHandler, IDatabase redis) { _errorHandler = errorHandler; _redis = redis; } - + [Command(RunMode = RunMode.Async)] [Remarks(CommandCategories.Helpers)] [Summary("Get a list of all available roles.")] @@ -36,13 +35,11 @@ namespace Geekbot.net.Commands await ReplyAsync("There are no roles configured for this server"); return; } + var sb = new StringBuilder(); sb.AppendLine($"**Self Service Roles on {Context.Guild.Name}**"); sb.AppendLine("To get a role, use `!role name`"); - foreach (var role in roles) - { - sb.AppendLine($"- {role.Name}"); - } + foreach (var role in roles) sb.AppendLine($"- {role.Name}"); await ReplyAsync(sb.ToString()); } catch (Exception e) @@ -69,16 +66,19 @@ namespace Geekbot.net.Commands await ReplyAsync("That role doesn't seem to exist"); return; } + if (guildUser.RoleIds.Contains(roleId)) { await guildUser.RemoveRoleAsync(role); await ReplyAsync($"Removed you from {role.Name}"); return; } + await guildUser.AddRoleAsync(role); await ReplyAsync($"Added you to {role.Name}"); return; } + await ReplyAsync("That role doesn't seem to exist"); } catch (HttpException e) @@ -104,16 +104,20 @@ namespace Geekbot.net.Commands await ReplyAsync("You can't add a role that is managed by discord"); return; } + if (role.Permissions.ManageRoles || role.Permissions.Administrator || role.Permissions.ManageGuild || role.Permissions.BanMembers || role.Permissions.KickMembers) { - await ReplyAsync("Woah, i don't think you want to add that role to self service as it contains some dangerous permissions"); + await ReplyAsync( + "Woah, i don't think you want to add that role to self service as it contains some dangerous permissions"); return; } - _redis.HashSet($"{Context.Guild.Id}:RoleWhitelist", new HashEntry[] { new HashEntry(roleName.ToLower(), role.Id.ToString()) }); + + _redis.HashSet($"{Context.Guild.Id}:RoleWhitelist", + new[] {new HashEntry(roleName.ToLower(), role.Id.ToString())}); await ReplyAsync($"Added {role.Name} to the whitelist"); } catch (Exception e) diff --git a/Geekbot.net/Commands/Roll.cs b/Geekbot.net/Commands/Roll.cs index 9d7b576..33cdf67 100644 --- a/Geekbot.net/Commands/Roll.cs +++ b/Geekbot.net/Commands/Roll.cs @@ -8,10 +8,10 @@ namespace Geekbot.net.Commands { public class Roll : ModuleBase { + private readonly IErrorHandler _errorHandler; private readonly IDatabase _redis; private readonly Random _rnd; private readonly ITranslationHandler _translation; - private readonly IErrorHandler _errorHandler; public Roll(IDatabase redis, Random RandomClient, IErrorHandler errorHandler, ITranslationHandler translation) { @@ -40,7 +40,9 @@ namespace Geekbot.net.Commands await ReplyAsync(string.Format(transDict["NoPrevGuess"], Context.Message.Author.Mention)); return; } - _redis.HashSet($"{Context.Guild.Id}:RollsPrevious", new HashEntry[]{ new HashEntry(Context.Message.Author.Id, guess), }); + + _redis.HashSet($"{Context.Guild.Id}:RollsPrevious", + new[] {new HashEntry(Context.Message.Author.Id, guess)}); await ReplyAsync(string.Format(transDict["Rolled"], Context.Message.Author.Mention, number, guess)); if (guess == number) { diff --git a/Geekbot.net/Commands/Say.cs b/Geekbot.net/Commands/Say.cs index 7ddcbbc..4c878c4 100644 --- a/Geekbot.net/Commands/Say.cs +++ b/Geekbot.net/Commands/Say.cs @@ -14,7 +14,7 @@ namespace Geekbot.net.Commands { _errorHandler = errorHandler; } - + [RequireUserPermission(GuildPermission.Administrator)] [Command("say", RunMode = RunMode.Async)] [Remarks(CommandCategories.Admin)] diff --git a/Geekbot.net/Commands/Ship.cs b/Geekbot.net/Commands/Ship.cs index 0b87f90..7b85eb0 100644 --- a/Geekbot.net/Commands/Ship.cs +++ b/Geekbot.net/Commands/Ship.cs @@ -9,9 +9,9 @@ namespace Geekbot.net.Commands { public class Ship : ModuleBase { + private readonly IErrorHandler _errorHandler; private readonly IDatabase _redis; private readonly Random _rnd; - private readonly IErrorHandler _errorHandler; public Ship(IDatabase redis, Random randomClient, IErrorHandler errorHandler) { @@ -87,6 +87,7 @@ namespace Geekbot.net.Commands { blocks = blocks + ":black_medium_small_square:"; } + return blocks; } } diff --git a/Geekbot.net/Commands/Stats.cs b/Geekbot.net/Commands/Stats.cs index 90e878a..67b76b9 100644 --- a/Geekbot.net/Commands/Stats.cs +++ b/Geekbot.net/Commands/Stats.cs @@ -9,10 +9,10 @@ namespace Geekbot.net.Commands { public class Stats : ModuleBase { - private readonly IDatabase _redis; private readonly IErrorHandler _errorHandler; private readonly ILevelCalc _levelCalc; - + private readonly IDatabase _redis; + public Stats(IDatabase redis, IErrorHandler errorHandler, ILevelCalc levelCalc) { _redis = redis; @@ -45,12 +45,14 @@ namespace Geekbot.net.Commands .WithIconUrl(userInfo.GetAvatarUrl()) .WithName(userInfo.Username)); eb.WithColor(new Color(221, 255, 119)); - + var karma = _redis.HashGet($"{Context.Guild.Id}:Karma", userInfo.Id.ToString()); var correctRolls = _redis.HashGet($"{Context.Guild.Id}:Rolls", userInfo.Id.ToString()); - eb.AddInlineField("Discordian Since", $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") - .AddInlineField("Joined Server", $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") + eb.AddInlineField("Discordian Since", + $"{createdAt.Day}.{createdAt.Month}.{createdAt.Year} ({age} days)") + .AddInlineField("Joined Server", + $"{joinedAt.Day}.{joinedAt.Month}.{joinedAt.Year} ({joinedDayAgo} days)") .AddInlineField("Karma", karma.ToString() ?? "0") .AddInlineField("Level", level) .AddInlineField("Messages Sent", messages) diff --git a/Geekbot.net/Commands/UrbanDictionary.cs b/Geekbot.net/Commands/UrbanDictionary.cs index 520fb2a..573b289 100644 --- a/Geekbot.net/Commands/UrbanDictionary.cs +++ b/Geekbot.net/Commands/UrbanDictionary.cs @@ -13,16 +13,16 @@ namespace Geekbot.net.Commands public class UrbanDictionary : ModuleBase { private readonly IErrorHandler _errorHandler; - + public UrbanDictionary(IErrorHandler errorHandler) { _errorHandler = errorHandler; } - + [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 { @@ -39,23 +39,21 @@ namespace Geekbot.net.Commands await ReplyAsync("That word hasn't been defined..."); return; } + var definition = definitions.list.First(e => !string.IsNullOrWhiteSpace(e.example)); - + var eb = new EmbedBuilder(); - eb.WithAuthor(new EmbedAuthorBuilder() + eb.WithAuthor(new EmbedAuthorBuilder { Name = definition.word, Url = definition.permalink }); - eb.WithColor(new Color(239,255,0)); + 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)); - } + if (definitions.tags.Length > 0) eb.AddField("Tags", string.Join(", ", definitions.tags)); await ReplyAsync("", false, eb.Build()); } @@ -65,14 +63,14 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + private class UrbanResponse { public string[] tags { get; set; } public string result_type { get; set; } public List list { get; set; } } - + private class UrbanListItem { public string definition { get; set; } diff --git a/Geekbot.net/Commands/Voice.cs b/Geekbot.net/Commands/Voice.cs index 8fc230e..242d642 100644 --- a/Geekbot.net/Commands/Voice.cs +++ b/Geekbot.net/Commands/Voice.cs @@ -1,7 +1,6 @@ using System; using System.Threading.Tasks; using Discord; -using Discord.Audio; using Discord.Commands; using Geekbot.net.Lib; @@ -9,8 +8,8 @@ namespace Geekbot.net.Commands { public class Voice : ModuleBase { - private readonly IErrorHandler _errorHandler; private readonly IAudioUtils _audioUtils; + private readonly IErrorHandler _errorHandler; public Voice(IErrorHandler errorHandler, IAudioUtils audioUtils) { @@ -42,7 +41,7 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + [Command("disconnect")] public async Task DisconnectChannel() { @@ -54,6 +53,7 @@ namespace Geekbot.net.Commands await Context.Channel.SendMessageAsync("I'm not in a voice channel at the moment"); return; } + await audioClient.StopAsync(); await ReplyAsync("Disconnected from channel!"); } @@ -62,7 +62,7 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + // [Command("play")] // public async Task play(IVoiceChannel channel = null) // { diff --git a/Geekbot.net/Commands/Youtube.cs b/Geekbot.net/Commands/Youtube.cs index 043cd3e..305052b 100644 --- a/Geekbot.net/Commands/Youtube.cs +++ b/Geekbot.net/Commands/Youtube.cs @@ -10,8 +10,8 @@ namespace Geekbot.net.Commands { public class Youtube : ModuleBase { - private readonly IDatabase _redis; private readonly IErrorHandler _errorHandler; + private readonly IDatabase _redis; public Youtube(IDatabase redis, IErrorHandler errorHandler) { diff --git a/Geekbot.net/Commands/mal.cs b/Geekbot.net/Commands/mal.cs index 261b39f..22b3d4a 100644 --- a/Geekbot.net/Commands/mal.cs +++ b/Geekbot.net/Commands/mal.cs @@ -1,5 +1,6 @@ using System; using System.Threading.Tasks; +using System.Web; using Discord; using Discord.Commands; using Geekbot.net.Lib; @@ -8,19 +9,19 @@ namespace Geekbot.net.Commands { public class mal : ModuleBase { - private readonly IMalClient _malClient; private readonly IErrorHandler _errorHandler; + private readonly IMalClient _malClient; public mal(IMalClient malClient, IErrorHandler errorHandler) { _malClient = malClient; _errorHandler = errorHandler; } - + [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 { @@ -31,11 +32,11 @@ namespace Geekbot.net.Commands { var eb = new EmbedBuilder(); - var description = System.Web.HttpUtility.HtmlDecode(anime.Synopsis) + var description = HttpUtility.HtmlDecode(anime.Synopsis) .Replace("
", "") .Replace("[i]", "*") .Replace("[/i]", "*"); - + eb.Title = anime.Title; eb.Description = description; eb.ImageUrl = anime.Image; @@ -65,11 +66,11 @@ namespace Geekbot.net.Commands _errorHandler.HandleCommandException(e, Context); } } - + [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 { @@ -80,11 +81,11 @@ namespace Geekbot.net.Commands { var eb = new EmbedBuilder(); - var description = System.Web.HttpUtility.HtmlDecode(manga.Synopsis) + var description = HttpUtility.HtmlDecode(manga.Synopsis) .Replace("
", "") .Replace("[i]", "*") .Replace("[/i]", "*"); - + eb.Title = manga.Title; eb.Description = description; eb.ImageUrl = manga.Image;