From 6ab43c5532d33a74cdcc6ab887f916b7315049db Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 7 Dec 2016 19:27:12 +0100 Subject: [PATCH 01/12] added SendConfirmAsync which will be used for confirmation responses --- src/NadekoBot/_Extensions/Extensions.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index a1d3498b..632c7ce3 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -162,6 +162,9 @@ namespace NadekoBot.Extensions public static Task SendErrorAsync(this IMessageChannel ch, string error, string title = null, string url = null) => ch.SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.ErrorColor }); + public static Task SendConfirmAsync(this IMessageChannel ch, string error, string title = null, string url = null) + => ch.SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.OkColor }); + public static Task SendTableAsync(this IMessageChannel ch, string seed, IEnumerable items, Func howToPrint, int columns = 3) { var i = 0; From 6d8158b476fb0965abd4aff0e30734a2884aa31c Mon Sep 17 00:00:00 2001 From: Kevin Date: Wed, 7 Dec 2016 15:10:47 -0500 Subject: [PATCH 02/12] urbandictionary api url api url updated to their site instead of using mashape. Why go through mashape -> ud? --- src/NadekoBot/Modules/Searches/Searches.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 870f3805..bd55e1e1 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -379,8 +379,8 @@ namespace NadekoBot.Modules.Searches using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); - http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey); - var res = await http.GetStringAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}").ConfigureAwait(false); + http.DefaultRequestHeaders.Add("Accept", "application/json"); + var res = await http.GetStringAsync($"http://api.urbandictionary.com/v0/define?term={Uri.EscapeUriString(arg)}").ConfigureAwait(false); try { var items = JObject.Parse(res); From 6aff020633148bcc75dba5bf603a897ca6479441 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 16:40:59 +0100 Subject: [PATCH 03/12] Prettification of the utility module --- src/NadekoBot/Modules/DiscordModule.cs | 2 - .../Modules/Utility/Commands/CalcCommand.cs | 48 ++++++------- .../Modules/Utility/Commands/InfoCommands.cs | 25 ++----- .../Modules/Utility/Commands/QuoteCommands.cs | 14 ++-- .../Modules/Utility/Commands/Remind.cs | 12 ++-- .../Utility/Commands/UnitConversion.cs | 23 +++---- src/NadekoBot/Modules/Utility/Utility.cs | 68 ++++++------------- src/NadekoBot/_Extensions/Extensions.cs | 15 ++-- 8 files changed, 84 insertions(+), 123 deletions(-) diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index bb7a6cbf..cc9db328 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -6,7 +6,6 @@ namespace NadekoBot.Modules { public class DiscordModule { - protected ILocalization _l { get; } protected CommandService _commands { get; } protected ShardedDiscordClient _client { get; } protected Logger _log { get; } @@ -20,7 +19,6 @@ namespace NadekoBot.Modules else _prefix = "?missing_prefix?"; - _l = loc; _commands = cmds; _client = client; _log = LogManager.GetCurrentClassLogger(); diff --git a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs index 2ec66349..31a91f6f 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs @@ -3,6 +3,8 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using System; +using System.Collections; +using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; @@ -10,24 +12,19 @@ using System.Threading.Tasks; namespace NadekoBot.Modules.Utility { - [Group] public partial class Utility { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public static async Task Calculate(IUserMessage msg, [Remainder] string expression) { - try - { - var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); - expr.EvaluateParameter += Expr_EvaluateParameter; - var result = expr.Evaluate(); - await msg.Reply(string.Format("βš™ `{0}`", expr.Error ?? result)); - } - catch (Exception e) - { - await msg.Reply($"Failed to evaluate: {e.Message} "); - } + var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); + expr.EvaluateParameter += Expr_EvaluateParameter; + var result = expr.Evaluate(); + if (expr.Error == null) + await msg.Channel.SendConfirmAsync("Result", $"{result}"); + else + await msg.Channel.SendErrorAsync($"βš™ Error", expr.Error); } private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args) @@ -44,20 +41,25 @@ namespace NadekoBot.Modules.Utility [RequireContext(ContextType.Guild)] public async Task CalcOps(IUserMessage msg) { - StringBuilder builder = new StringBuilder(); - var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Select(x => + var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x => { - var name = x.Name; - if (x.GetParameters().Any()) - { - name += " (" + string.Join(", ", x.GetParameters().Select(y => y.IsOptional ? $"[{y.ParameterType.Name + " " + y.Name }]" : y.ParameterType.Name + " " + y.Name)) + ")"; - } - return name; - }); - foreach (var method in selection) builder.AppendLine(method); - await msg.ReplyLong(builder.ToString()); + return x.Name; + }) + .Except(new[] { "ToString", + "Equals", + "GetHashCode", + "GetType"}); + await msg.Channel.SendConfirmAsync(string.Join(", ",selection)); } } + + class MethodInfoEqualityComparer : IEqualityComparer + { + public bool Equals(MethodInfo x, MethodInfo y) => x.Name == y.Name; + + public int GetHashCode(MethodInfo obj) => obj.Name.GetHashCode(); + } + class ExpressionContext { public double Pi { get; set; } = Math.PI; diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 44681852..edf3d974 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -10,25 +10,8 @@ using System.Threading.Tasks; namespace NadekoBot.Modules.Utility { - partial class Utility : DiscordModule + public partial class Utility { - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task TogetherTube(IUserMessage imsg) - { - var channel = (ITextChannel)imsg.Channel; - - Uri target; - using (var http = new HttpClient()) - { - var res = await http.GetAsync("https://togethertube.com/room/create").ConfigureAwait(false); - target = res.RequestMessage.RequestUri; - } - - await channel.SendMessageAsync($"🎞 {imsg.Author.Mention}, **Your new video room created. Join and invite to watch videos together with friends:** {target}") - .ConfigureAwait(false); - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ServerInfo(IUserMessage msg, string guild = null) @@ -61,7 +44,7 @@ __`Created At:`__ **{createdAt.ToString("dd.MM.yyyy HH:mm")}** sb.AppendLine($"__`Features:`__ **{string.Join(", ", server.Features)}**"); if (!string.IsNullOrWhiteSpace(server.SplashUrl)) sb.AppendLine($"__`Region:`__ **{server.VoiceRegionId}**"); - await msg.Reply(sb.ToString()).ConfigureAwait(false); + await channel.SendConfirmAsync(sb.ToString()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -77,7 +60,7 @@ __`ID:`__ **{ch.Id}** __`Created At:`__ **{createdAt.ToString("dd.MM.yyyy HH:mm")}** __`Topic:`__ {ch.Topic} __`Users:`__ **{(await ch.GetUsersAsync()).Count()}**"; - await msg.Reply(toReturn).ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(toReturn).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -99,7 +82,7 @@ __`Users:`__ **{(await ch.GetUsersAsync()).Count()}**"; if (!string.IsNullOrWhiteSpace(user.AvatarUrl)) toReturn += $@" πŸ“· __`Avatar URL:`__ **{await NadekoBot.Google.ShortenUrl(user.AvatarUrl).ConfigureAwait(false)}**"; - await msg.Reply(toReturn).ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(toReturn).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs index c1b35efe..be1f4dae 100644 --- a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs @@ -31,10 +31,10 @@ namespace NadekoBot.Modules.Utility } if (quotes.Any()) - await channel.SendMessageAsync($"πŸ’¬ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") + await channel.SendConfirmAsync($"πŸ’¬ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") .ConfigureAwait(false); else - await channel.SendMessageAsync("ℹ️ **No quotes on this page.**").ConfigureAwait(false); + await channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -57,7 +57,7 @@ namespace NadekoBot.Modules.Utility if (quote == null) return; - await channel.SendMessageAsync("πŸ“£ " + quote.Text.SanitizeMentions()); + await channel.SendConfirmAsync("πŸ“£ " + quote.Text.SanitizeMentions()); } [NadekoCommand, Usage, Description, Aliases] @@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Utility }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendMessageAsync("βœ… **Quote added.**").ConfigureAwait(false); + await channel.SendConfirmAsync("βœ… Quote added.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Utility if (qs==null || !qs.Any()) { - response = "ℹ️ **No quotes found.**"; + await channel.SendErrorAsync("No quotes found."); return; } @@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Utility await uow.CompleteAsync().ConfigureAwait(false); response = "πŸ—‘ **Deleted a random quote.**"; } - await channel.SendMessageAsync(response); + await channel.SendConfirmAsync(response); } [NadekoCommand, Usage, Description, Aliases] @@ -139,7 +139,7 @@ namespace NadekoBot.Modules.Utility await uow.CompleteAsync(); } - await channel.SendMessageAsync($"πŸ—‘ **Deleted all quotes** with **{keyword}** keyword."); + await channel.SendConfirmAsync($"πŸ—‘ **Deleted all quotes** with **{keyword}** keyword."); } } } diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index 391e9109..ed34131e 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -74,7 +74,7 @@ namespace NadekoBot.Modules.Utility if (ch == null) return; - await ch.SendMessageAsync( + await ch.SendConfirmAsync( replacements.Aggregate(RemindMessageFormat, (cur, replace) => cur.Replace(replace.Key, replace.Value(r))) .SanitizeMentions() @@ -124,7 +124,7 @@ namespace NadekoBot.Modules.Utility if (ch == null) { - await channel.SendMessageAsync($"⚠️ {umsg.Author.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); + await channel.SendErrorAsync($"{umsg.Author.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); return; } @@ -132,7 +132,7 @@ namespace NadekoBot.Modules.Utility if (m.Length == 0) { - await channel.SendMessageAsync("❎ **Not a valid time format.** type `-h .remind`").ConfigureAwait(false); + await channel.SendErrorAsync("Not a valid time format. Type `-h .remind`").ConfigureAwait(false); return; } @@ -157,7 +157,7 @@ namespace NadekoBot.Modules.Utility (groupName == "hours" && value > 23) || (groupName == "minutes" && value > 59)) { - await channel.SendMessageAsync($"⚠️ Invalid {groupName} value.").ConfigureAwait(false); + await channel.SendErrorAsync($"Invalid {groupName} value.").ConfigureAwait(false); return; } else @@ -187,7 +187,7 @@ namespace NadekoBot.Modules.Utility await uow.CompleteAsync(); } - try { await channel.SendMessageAsync($"⏰ I will remind **\"{(ch is ITextChannel ? ((ITextChannel)ch).Name : umsg.Author.Username)}\"** to **\"{message.SanitizeMentions()}\"** in **{output}** `({time:d.M.yyyy.} at {time:HH:mm})`").ConfigureAwait(false); } catch { } + try { await channel.SendConfirmAsync($"⏰ I will remind **\"{(ch is ITextChannel ? ((ITextChannel)ch).Name : umsg.Author.Username)}\"** to **\"{message.SanitizeMentions()}\"** in **{output}** `({time:d.M.yyyy.} at {time:HH:mm})`").ConfigureAwait(false); } catch { } await StartReminder(rem); } @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.Utility uow.BotConfig.GetOrCreate().RemindMessageFormat = arg.Trim(); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendMessageAsync("πŸ†— New remind template set."); + await channel.SendConfirmAsync("πŸ†— New remind template set."); } } } diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index 9c9c0aa0..e75f7c72 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -104,15 +104,14 @@ namespace NadekoBot.Modules.Utility [RequireContext(ContextType.Guild)] public async Task ConvertList(IUserMessage msg) { - var sb = new StringBuilder("Units that can be used by the converter: \n"); - var res = Units.GroupBy(x => x.UnitType); - foreach (var group in res) - { - sb.AppendLine($"{group.Key}: ```xl"); - sb.AppendLine(string.Join(",", group.Select(x => x.Triggers.FirstOrDefault()).OrderBy(x => x))); - sb.AppendLine("```"); - } - await msg.ReplyLong(sb.ToString(), breakOn: new[] { "```xl\n", "\n" }); + var res = Units.GroupBy(x => x.UnitType) + .Aggregate(new EmbedBuilder().WithTitle("__Units which can be used by the converter__") + .WithColor(NadekoBot.OkColor), + (embed, g) => embed.AddField(efb => + efb.WithName(g.Key.ToTitleCase()) + .WithValue(String.Join(", ", g.Select(x => x.Triggers.FirstOrDefault()) + .OrderBy(x => x))))); + await msg.Channel.EmbedAsync(res.Build()); } [NadekoCommand, Usage, Description, Aliases] public async Task Convert(IUserMessage msg, string origin, string target, decimal value) @@ -121,12 +120,12 @@ namespace NadekoBot.Modules.Utility var targetUnit = Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant())); if (originUnit == null || targetUnit == null) { - await msg.Reply(string.Format("Cannot convert {0} to {1}: units not found", origin, target)); + await msg.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: units not found", origin, target)); return; } if (originUnit.UnitType != targetUnit.UnitType) { - await msg.Reply(string.Format("Cannot convert {0} to {1}: types of unit are not equal", originUnit.Triggers.First(), targetUnit.Triggers.First())); + await msg.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: types of unit are not equal", originUnit.Triggers.First(), targetUnit.Triggers.First())); return; } decimal res; @@ -170,7 +169,7 @@ namespace NadekoBot.Modules.Utility } res = Math.Round(res, 4); - await msg.Reply(string.Format("{0} {1} is equal to {2} {3}", value, (originUnit.Triggers.First() + "s").SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2))); + await msg.Channel.SendConfirmAsync(string.Format("{0} {1} is equal to {2} {3}", value, (originUnit.Triggers.First() + "s").SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2))); } } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 5dce8930..c0a319f8 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -44,7 +44,9 @@ namespace NadekoBot.Modules.Utility if (!arr.Any()) await channel.SendErrorAsync("Nobody is playing that game.").ConfigureAwait(false); else - await channel.SendMessageAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 3).Select(ig => string.Concat(ig.Select(el => $"β€’ {el,-35}")))) + "\n```").ConfigureAwait(false); + await channel.SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 2) + .Select(ig => string.Concat(ig.Select(el => $"β€’ {el,-27}")))) + "\n```") + .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -55,7 +57,7 @@ namespace NadekoBot.Modules.Utility return; var channel = (ITextChannel)umsg.Channel; var arg = roles.Split(',').Select(r => r.Trim().ToUpperInvariant()); - string send = _l["ℹ️ **Here is a list of users in a specfic role:**"]; + string send = "ℹ️ **Here is a list of users in those roles:**"; foreach (var roleStr in arg.Where(str => !string.IsNullOrWhiteSpace(str) && str != "@EVERYONE" && str != "EVERYONE")) { var role = channel.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault(); @@ -69,16 +71,16 @@ namespace NadekoBot.Modules.Utility { if (!usr.GetPermissions(channel).ManageMessages) { - await channel.SendMessageAsync($"⚠️ {usr.Mention} **you are not allowed to use this command on roles with a lot of users in them to prevent abuse.**").ConfigureAwait(false); + await channel.SendErrorAsync($"⚠️ {usr.Mention} **you are not allowed to use this command on roles with a lot of users in them to prevent abuse.**").ConfigureAwait(false); return; } var curstr = send.Substring(0, 2000); - await channel.SendMessageAsync(curstr.Substring(0, + await channel.SendConfirmAsync(curstr.Substring(0, curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + send.Substring(2000); } - await channel.SendMessageAsync(send).ConfigureAwait(false); + await channel.SendConfirmAsync(send).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -95,7 +97,7 @@ namespace NadekoBot.Modules.Utility } builder.Append("```"); - await msg.Reply(builder.ToString()); + await msg.Channel.SendConfirmAsync(builder.ToString()); } [NadekoCommand, Usage, Description, Aliases] @@ -103,20 +105,20 @@ namespace NadekoBot.Modules.Utility public async Task UserId(IUserMessage msg, IGuildUser target = null) { var usr = target ?? msg.Author; - await msg.Reply($"πŸ†” of the user **{ usr.Username }** is `{ usr.Id }`").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync($"πŸ†” of the user **{ usr.Username }** is `{ usr.Id }`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task ChannelId(IUserMessage msg) { - await msg.Reply($"ℹ️ This **Channel's ID** is `{msg.Channel.Id}`").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync($"πŸ†” of this channel is `{msg.Channel.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ServerId(IUserMessage msg) { - await msg.Reply($"ℹ️ This **Server's ID** is `{((ITextChannel)msg.Channel).Guild.Id}`").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync($"πŸ†” of this server is `{((ITextChannel)msg.Channel).Guild.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -132,11 +134,11 @@ namespace NadekoBot.Modules.Utility return; if (target != null) { - await msg.Reply($"βš” **Page #{page} of roles for {target.Username}:** ```css\nβ€’ " + string.Join("\nβ€’ ", target.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); + await channel.SendConfirmAsync($"βš” **Page #{page} of roles for {target.Username}**", $"```css\nβ€’ " + string.Join("\nβ€’ ", target.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); } else { - await msg.Reply($"βš” **Page #{page} of all roles on this server:** ```css\nβ€’ " + string.Join("\nβ€’ ", guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); + await channel.SendConfirmAsync($"βš” **Page #{page} of all roles on this server:**", $"```css\nβ€’ " + string.Join("\nβ€’ ", guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); } } @@ -153,9 +155,9 @@ namespace NadekoBot.Modules.Utility var topic = channel.Topic; if (string.IsNullOrWhiteSpace(topic)) - await channel.SendMessageAsync("❎ **No topic set.**"); + await channel.SendErrorAsync("No topic set."); else - await channel.SendMessageAsync("ℹ️ **Topic:** " + topic); + await channel.SendConfirmAsync("Channel topic", topic); } [NadekoCommand, Usage, Description, Aliases] @@ -254,42 +256,16 @@ namespace NadekoBot.Modules.Utility if (!guilds.Any()) { - await channel.SendMessageAsync("❎ No servers found on that page.").ConfigureAwait(false); + await channel.SendErrorAsync("No servers found on that page.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(String.Join("\n", guilds.Select(g => $"```css\nName: {g.Name} ID:{g.Id} Members:#{g.GetUsers().Count} OwnerID: {g.OwnerId} ```"))).ConfigureAwait(false); + await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor), + (embed, g) => embed.AddField(efb => efb.WithName(g.Name) + .WithValue($"```css\nID: {g.Id}\nMembers: {g.GetUsers().Count}\nOwnerID: {g.OwnerId} ```") + .WithIsInline(false))) + .Build()) + .ConfigureAwait(false); } - - //[NadekoCommand, Usage, Description, Aliases] - //[RequireContext(ContextType.Guild)] - //public async Task TextToImage(IUserMessage msg, [Remainder] string arg) - //{ - // var channel = (ITextChannel)msg.Channel; - - // const string bgName = "xbiy3"; - - // if (string.IsNullOrWhiteSpace(arg)) - // return; - - // using (var http = new HttpClient()) - // { - // http.AddFakeHeaders(); - - // http.DefaultRequestHeaders.Add("Host", "www.tagsmaker.com"); - // http.DefaultRequestHeaders.Add("Referer", "http://www.tagsmaker.com/"); - // http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); - // http.DefaultRequestHeaders.Add("Alt-Used", "www.tagsmaker.com:443"); - - // var res = await http.GetAsync($"http://www.tagsmaker.com/tagsmaker.php?background_name=0011&tag_text={arg}&font_name=applejuiced&text_color=white&text_size=48&text_alignment=middle").ConfigureAwait(false); - - // var img = res.RequestMessage.RequestUri.Segments[1].Replace("image-", "").Replace("tag-", ""); - // var imgStream = await http.GetStreamAsync($"http://www.tagsmaker.com/upload/www.tagsmaker.com_{ img.ToString() }.png"); - // var ms = new MemoryStream(); - // await imgStream.CopyToAsync(ms).ConfigureAwait(false); - // ms.Position = 0; - // await channel.SendFileAsync(ms, arg+".png", "Provided by www.tagsmaker.com").ConfigureAwait(false); - // } - //} } } diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 632c7ce3..29d7e03d 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -74,9 +74,6 @@ namespace NadekoBot.Extensions public static async Task SendFileAsync(this IGuildUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); - public static async Task Reply(this IUserMessage msg, string content) => - await msg.Channel.SendMessageAsync(content).ConfigureAwait(false); - public static bool IsAuthor(this IUserMessage msg) => NadekoBot.Client.GetCurrentUser().Id == msg.Author.Id; @@ -159,11 +156,17 @@ namespace NadekoBot.Extensions public static Task EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); - public static Task SendErrorAsync(this IMessageChannel ch, string error, string title = null, string url = null) + public static Task SendErrorAsync(this IMessageChannel ch, string title, string error, string url = null) => ch.SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.ErrorColor }); - public static Task SendConfirmAsync(this IMessageChannel ch, string error, string title = null, string url = null) - => ch.SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.OkColor }); + public static Task SendErrorAsync(this IMessageChannel ch, string error) + => ch.SendMessageAsync("", embed: new Embed() { Description = error, Color = NadekoBot.ErrorColor }); + + public static Task SendConfirmAsync(this IMessageChannel ch, string title, string text, string url = null) + => ch.SendMessageAsync("", embed: new Embed() { Description = text, Title = title, Url = url, Color = NadekoBot.OkColor }); + + public static Task SendConfirmAsync(this IMessageChannel ch, string text) + => ch.SendMessageAsync("", embed: new Embed() { Description = text, Color = NadekoBot.OkColor }); public static Task SendTableAsync(this IMessageChannel ch, string seed, IEnumerable items, Func howToPrint, int columns = 3) { From 5324cc2229f26c1dd9a81be9501e560a6698ac7b Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 17:20:35 +0100 Subject: [PATCH 04/12] Cleanup --- .../Commands/StreamNotificationCommands.cs | 5 +--- src/NadekoBot/ShardedDiscordClient.cs | 28 +++++++++---------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 245081b4..39b60c2b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -111,10 +111,7 @@ namespace NadekoBot.Modules.Searches try { await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); } catch { } } } - catch (Exception ex) - { - - } + catch { } })); FirstPass = false; diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index e7b43881..014f0edc 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -13,20 +13,20 @@ namespace NadekoBot private DiscordSocketConfig discordSocketConfig; private Logger _log { get; } - public Func UserJoined { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func MessageReceived { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserLeft { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserUpdated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func, IMessage, Task> MessageUpdated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func, Task> MessageDeleted { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserBanned { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserUnbanned { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserPresenceUpdated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func UserVoiceStateUpdated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func ChannelCreated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func ChannelDestroyed { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func ChannelUpdated { get; internal set; } = delegate { return Task.CompletedTask; }; - public Func Disconnected { get; internal set; } = delegate { return Task.CompletedTask; }; + public event Func UserJoined = delegate { return Task.CompletedTask; }; + public event Func MessageReceived = delegate { return Task.CompletedTask; }; + public event Func UserLeft = delegate { return Task.CompletedTask; }; + public event Func UserUpdated = delegate { return Task.CompletedTask; }; + public event Func, IMessage, Task> MessageUpdated = delegate { return Task.CompletedTask; }; + public event Func, Task> MessageDeleted = delegate { return Task.CompletedTask; }; + public event Func UserBanned = delegate { return Task.CompletedTask; }; + public event Func UserUnbanned = delegate { return Task.CompletedTask; }; + public event Func UserPresenceUpdated = delegate { return Task.CompletedTask; }; + public event Func UserVoiceStateUpdated = delegate { return Task.CompletedTask; }; + public event Func ChannelCreated = delegate { return Task.CompletedTask; }; + public event Func ChannelDestroyed = delegate { return Task.CompletedTask; }; + public event Func ChannelUpdated = delegate { return Task.CompletedTask; }; + public event Func Disconnected = delegate { return Task.CompletedTask; }; private IReadOnlyList Clients { get; } From 9c989804e8d3dae7207fe693ce6647a85b0d1681 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 17:30:29 +0100 Subject: [PATCH 05/12] QoL changes --- src/NadekoBot/Modules/Administration/Administration.cs | 6 +++--- src/NadekoBot/Services/CommandHandler.cs | 4 ++-- src/NadekoBot/Services/Impl/StatsService.cs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 9634e698..ee6fee52 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -40,11 +40,11 @@ namespace NadekoBot.Modules.Administration } } - private async void DelMsgOnCmd_Handler(object sender, CommandExecutedEventArgs e) + private async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) { try { - var channel = e.Message.Channel as ITextChannel; + var channel = msg.Channel as ITextChannel; if (channel == null) return; @@ -56,7 +56,7 @@ namespace NadekoBot.Modules.Administration } if (shouldDelete) - await e.Message.DeleteAsync().ConfigureAwait(false); + await msg.DeleteAsync().ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 08aa6fbd..031a2dfe 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -39,7 +39,7 @@ namespace NadekoBot.Services private List ownerChannels { get; set; } - public event EventHandler CommandExecuted = delegate { }; + public event Func CommandExecuted = delegate { return Task.CompletedTask; }; public CommandHandler(ShardedDiscordClient client, CommandService commandService) { @@ -154,7 +154,7 @@ namespace NadekoBot.Services var channel = (usrMsg.Channel as ITextChannel); if (result.IsSuccess) { - CommandExecuted(this, new CommandExecutedEventArgs(usrMsg, command)); + await CommandExecuted(usrMsg, command); _log.Info("Command Executed after {4}s\n\t" + "User: {0}\n\t" + "Server: {1}\n\t" + diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 30993844..90378128 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -38,7 +38,7 @@ namespace NadekoBot.Services.Impl Reset(); this.client.MessageReceived += _ => Task.FromResult(MessageCounter++); - cmdHandler.CommandExecuted += (_, e) => CommandsRan++; + cmdHandler.CommandExecuted += (_, e) => Task.FromResult(CommandsRan++); this.client.Disconnected += _ => Reset(); From 3a60df953931a96a47cfb0907c297b5b5d01d315 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 18:35:34 +0100 Subject: [PATCH 06/12] massive cleanup --- .../Modules/Administration/Administration.cs | 13 +++- .../Commands/AntiRaidCommands.cs | 10 +-- .../Commands/AutoAssignRoleCommands.cs | 9 +-- .../Commands/CrossServerTextChannel.cs | 6 +- .../Commands/MessageRepeater.cs | 4 +- .../Commands/PlayingRotateCommands.cs | 7 +- .../Commands/RatelimitCommand.cs | 11 +-- .../Commands/ServerGreetCommands.cs | 9 +-- .../Commands/VoicePlusTextCommands.cs | 10 +-- .../Modules/ClashOfClans/ClashOfClans.cs | 2 +- .../CustomReactions/CustomReactions.cs | 2 +- src/NadekoBot/Modules/DiscordModule.cs | 6 +- .../Modules/Gambling/Commands/AnimalRacing.cs | 8 +- .../Gambling/Commands/FlipCoinCommand.cs | 3 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 2 +- .../Games/Commands/PlantAndPickCommands.cs | 27 +++---- src/NadekoBot/Modules/Games/Games.cs | 2 +- src/NadekoBot/Modules/Help/Help.cs | 10 +-- src/NadekoBot/Modules/Music/Music.cs | 2 +- src/NadekoBot/Modules/NSFW/NSFW.cs | 2 +- .../Permissions/Commands/CmdCdsCommands.cs | 2 +- .../Permissions/Commands/FilterCommands.cs | 10 +-- .../Modules/Permissions/Permissions.cs | 4 +- src/NadekoBot/Modules/Pokemon/Pokemon.cs | 2 +- .../Searches/Commands/AnimeSearchCommands.cs | 53 ++++++------- .../Modules/Searches/Commands/JokeCommands.cs | 8 +- .../Modules/Searches/Commands/LoLCommands.cs | 2 +- .../Modules/Searches/Commands/OsuCommands.cs | 4 +- .../Commands/PokemonSearchCommands.cs | 4 +- .../Commands/StreamNotificationCommands.cs | 14 ++-- src/NadekoBot/Modules/Searches/Searches.cs | 2 +- .../Modules/Utility/Commands/InfoCommands.cs | 2 +- src/NadekoBot/Modules/Utility/Utility.cs | 9 ++- src/NadekoBot/NadekoBot.cs | 14 ++-- src/NadekoBot/_Extensions/Extensions.cs | 75 +------------------ src/NadekoBot/project.json | 7 +- 36 files changed, 135 insertions(+), 222 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index ee6fee52..b2866ff6 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -15,6 +15,7 @@ using System.Net.Http; using System.IO; using static NadekoBot.Modules.Permissions.Permissions; using System.Collections.Concurrent; +using NLog; namespace NadekoBot.Modules.Administration { @@ -24,13 +25,17 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary GuildMuteRoles { get; } = new ConcurrentDictionary(); - public Administration(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + private static Logger _log { get; } + + public Administration() : base() { - NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; } static Administration() { + _log = LogManager.GetCurrentClassLogger(); + NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; + using (var uow = DbHandler.UnitOfWork()) { var configs = NadekoBot.AllGuildConfigs; @@ -40,7 +45,7 @@ namespace NadekoBot.Modules.Administration } } - private async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) + private static async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) { try { @@ -802,7 +807,7 @@ namespace NadekoBot.Modules.Administration { var channel = (ITextChannel)umsg.Channel; - var channels = await Task.WhenAll(_client.GetGuilds().Select(g => + var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g => g.GetDefaultChannelAsync() )).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 06613873..3003a00f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -74,13 +74,13 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary antiSpamGuilds = new ConcurrentDictionary(); - private Logger _log { get; } + private static Logger _log { get; } - public AntiRaidCommands(ShardedDiscordClient client) + static AntiRaidCommands() { _log = LogManager.GetCurrentClassLogger(); - client.MessageReceived += (imsg) => + NadekoBot.Client.MessageReceived += (imsg) => { var msg = imsg as IUserMessage; if (msg == null || msg.Author.IsBot) @@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; }; - client.UserJoined += (usr) => + NadekoBot.Client.UserJoined += (usr) => { if (usr.IsBot) return Task.CompletedTask; @@ -148,7 +148,7 @@ namespace NadekoBot.Modules.Administration }; } - private async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus) + private static async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus) { foreach (var gu in gus) { diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 8cf15cb7..3511b454 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -15,13 +15,12 @@ namespace NadekoBot.Modules.Administration [Group] public class AutoAssignRoleCommands { - private Logger _log { get; } + private static Logger _log { get; } - public AutoAssignRoleCommands() + static AutoAssignRoleCommands() { - var _client = NadekoBot.Client; - this._log = LogManager.GetCurrentClassLogger(); - _client.UserJoined += (user) => + _log = LogManager.GetCurrentClassLogger(); + NadekoBot.Client.UserJoined += (user) => { var t = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 50dfaed7..fc71e58b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Administration [Group] public class CrossServerTextChannel { - public CrossServerTextChannel() + static CrossServerTextChannel() { _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += (imsg) => @@ -50,11 +50,11 @@ namespace NadekoBot.Modules.Administration }; } - private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => + private static string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => $"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content; public static readonly ConcurrentDictionary> Subscribers = new ConcurrentDictionary>(); - private Logger _log { get; } + private static Logger _log { get; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 953f2446..8f00eded 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration [Group] public class RepeatCommands { - public ConcurrentDictionary repeaters; + public static ConcurrentDictionary repeaters { get; } public class RepeatRunner { @@ -70,7 +70,7 @@ namespace NadekoBot.Modules.Administration } } - public RepeatCommands() + static RepeatCommands() { using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index 3e047508..4490603f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration [Group] public class PlayingRotateCommands { - private Logger _log { get; } + private static Logger _log { get; } public static List RotatingStatusMessages { get; } public static bool RotatingStatuses { get; private set; } = false; @@ -30,12 +30,9 @@ namespace NadekoBot.Modules.Administration RotatingStatusMessages = conf.RotatingStatusMessages; RotatingStatuses = conf.RotatingStatuses; } - } - public PlayingRotateCommands() - { _log = LogManager.GetCurrentClassLogger(); - Task.Run(async () => + var t = Task.Run(async () => { var index = 0; do diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 224461b5..fe9b4639 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -16,9 +16,7 @@ namespace NadekoBot.Modules.Administration public class RatelimitCommand { public static ConcurrentDictionary RatelimitingChannels = new ConcurrentDictionary(); - private Logger _log { get; } - - private ShardedDiscordClient _client { get; } + private static Logger _log { get; } public class Ratelimiter { @@ -61,12 +59,11 @@ namespace NadekoBot.Modules.Administration } } - public RatelimitCommand() + static RatelimitCommand() { - this._client = NadekoBot.Client; - this._log = LogManager.GetCurrentClassLogger(); + _log = LogManager.GetCurrentClassLogger(); - _client.MessageReceived += (umsg) => + NadekoBot.Client.MessageReceived += (umsg) => { var t = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index 77960838..94d0589b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -17,17 +17,16 @@ namespace NadekoBot.Modules.Administration [Group] public class ServerGreetCommands { - public static long Greeted = 0; - private Logger _log; + private static Logger _log { get; } - public ServerGreetCommands() + static ServerGreetCommands() { NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserLeft += UserLeft; _log = LogManager.GetCurrentClassLogger(); } - private Task UserLeft(IGuildUser user) + private static Task UserLeft(IGuildUser user) { var leftTask = Task.Run(async () => { @@ -67,7 +66,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; } - private Task UserJoined(IGuildUser user) + private static Task UserJoined(IGuildUser user) { var joinedTask = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 8c7c4e00..a6ca255f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -17,10 +17,10 @@ namespace NadekoBot.Modules.Administration [Group] public class VoicePlusTextCommands { - Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled); + private static Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled); - private ConcurrentHashSet voicePlusTextCache; - public VoicePlusTextCommands() + private static ConcurrentHashSet voicePlusTextCache { get; } + static VoicePlusTextCommands() { using (var uow = DbHandler.UnitOfWork()) { @@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Administration NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler; } - private Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after) + private static Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after) { var user = (iuser as IGuildUser); var guild = user?.Guild; @@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; } - private string GetChannelName(string voiceName) => + private static string GetChannelName(string voiceName) => channelNameRegex.Replace(voiceName, "").Trim().Replace(" ", "-").TrimTo(90, true) + "-voice"; [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index c7cfdaad..4a61127a 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.ClashOfClans .ToDictionary(g => g.Key, g => g.ToList())); } } - public ClashOfClans(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public ClashOfClans() : base() { } diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 32614b05..7dfa0cb5 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.CustomReactions GlobalReactions = new ConcurrentHashSet(items.Where(g => g.GuildId == null || g.GuildId == 0)); } } - public CustomReactions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public CustomReactions() : base() { } diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index cc9db328..c5b129dc 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -6,12 +6,10 @@ namespace NadekoBot.Modules { public class DiscordModule { - protected CommandService _commands { get; } - protected ShardedDiscordClient _client { get; } protected Logger _log { get; } protected string _prefix { get; } - public DiscordModule(ILocalization loc, CommandService cmds, ShardedDiscordClient client) + public DiscordModule() { string prefix; if (NadekoBot.ModulePrefixes.TryGetValue(this.GetType().Name, out prefix)) @@ -19,8 +17,6 @@ namespace NadekoBot.Modules else _prefix = "?missing_prefix?"; - _commands = cmds; - _client = client; _log = LogManager.GetCurrentClassLogger(); } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index 9bda0461..9dc5de5b 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -18,11 +18,7 @@ namespace NadekoBot.Modules.Gambling [Group] public class AnimalRacing { - - public AnimalRacing() - { - } - public static ConcurrentDictionary AnimalRaces = new ConcurrentDictionary(); + public static ConcurrentDictionary AnimalRaces { get; } = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] @@ -119,7 +115,7 @@ namespace NadekoBot.Modules.Gambling await Task.Run(StartRace); End(); } - catch { } + catch { try { End(); } catch { } } }); } diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 0ea7bd5e..e5e84e11 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -15,10 +15,9 @@ namespace NadekoBot.Modules.Gambling [Group] public class FlipCoinCommands { - NadekoRandom rng { get; } = new NadekoRandom(); + private static NadekoRandom rng { get; } = new NadekoRandom(); private const string headsPath = "data/images/coins/heads.png"; private const string tailsPath = "data/images/coins/tails.png"; - public FlipCoinCommands() { } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 1ab94b4f..3dc865ca 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Gambling public static string CurrencyPluralName { get; set; } public static string CurrencySign { get; set; } - public Gambling(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Gambling() : base() { using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 0ac7e6e1..3a0ef80c 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -31,23 +31,20 @@ namespace NadekoBot.Modules.Games [Group] public class PlantPickCommands { - private Random rng; - - private ConcurrentHashSet generationChannels = new ConcurrentHashSet(); + private static ConcurrentHashSet generationChannels { get; } = new ConcurrentHashSet(); //channelid/message - private ConcurrentDictionary> plantedFlowers = new ConcurrentDictionary>(); + private static ConcurrentDictionary> plantedFlowers { get; } = new ConcurrentDictionary>(); //channelId/last generation - private ConcurrentDictionary lastGenerations = new ConcurrentDictionary(); + private static ConcurrentDictionary lastGenerations { get; } = new ConcurrentDictionary(); - private float chance; - private int cooldown; - private Logger _log { get; } + private static float chance { get; } + private static int cooldown { get; } + private static Logger _log { get; } - public PlantPickCommands() + static PlantPickCommands() { _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += PotentialFlowerGeneration; - rng = new NadekoRandom(); using (var uow = DbHandler.UnitOfWork()) { @@ -60,7 +57,7 @@ namespace NadekoBot.Modules.Games } } - private Task PotentialFlowerGeneration(IMessage imsg) + private static Task PotentialFlowerGeneration(IMessage imsg) { var msg = imsg as IUserMessage; if (msg == null || msg.IsAuthor() || msg.Author.IsBot) @@ -76,6 +73,7 @@ namespace NadekoBot.Modules.Games var t = Task.Run(async () => { var lastGeneration = lastGenerations.GetOrAdd(channel.Id, DateTime.MinValue); + var rng = new NadekoRandom(); if (DateTime.Now - TimeSpan.FromSeconds(cooldown) < lastGeneration) //recently generated in this channel, don't generate again return; @@ -194,8 +192,11 @@ namespace NadekoBot.Modules.Games } } - private string GetRandomCurrencyImagePath() => - Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault(); + private static string GetRandomCurrencyImagePath() + { + var rng = new NadekoRandom(); + return Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault(); + } int GetRandomNumber() { diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 115fdb94..a95a9bd8 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Games } } } - public Games(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Games() : base() { } diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 0166cf4c..80bcc0a0 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -30,7 +30,7 @@ namespace NadekoBot.Modules.Help } } - public Help(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Help() : base() { } @@ -38,7 +38,7 @@ namespace NadekoBot.Modules.Help public async Task Modules(IUserMessage umsg) { - await umsg.Channel.SendMessageAsync("πŸ“œ **List of modules:** ```css\nβ€’ " + string.Join("\nβ€’ ", _commands.Modules.Select(m => m.Name)) + $"\n``` ℹ️ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") + await umsg.Channel.SendMessageAsync("πŸ“œ **List of modules:** ```css\nβ€’ " + string.Join("\nβ€’ ", NadekoBot.CommandService.Modules.Select(m => m.Name)) + $"\n``` ℹ️ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") .ConfigureAwait(false); } @@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Help module = module?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(module)) return; - var cmds = _commands.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) + var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) .OrderBy(c => c.Text) .Distinct(new CommandTextEqualityComparer()) .AsEnumerable(); @@ -84,7 +84,7 @@ namespace NadekoBot.Modules.Help await ch.SendMessageAsync(HelpString).ConfigureAwait(false); return; } - var com = _commands.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); + var com = NadekoBot.CommandService.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); if (com == null) { @@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Help helpstr.AppendLine(string.Join("\n", NadekoBot.CommandService.Modules.Where(m => m.Name.ToLowerInvariant() != "help").OrderBy(m => m.Name).Prepend(NadekoBot.CommandService.Modules.FirstOrDefault(m=>m.Name.ToLowerInvariant()=="help")).Select(m => $"- [{m.Name}](#{m.Name.ToLowerInvariant()})"))); helpstr.AppendLine(); string lastModule = null; - foreach (var com in _commands.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First())) + foreach (var com in NadekoBot.CommandService.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First())) { if (com.Module.Name != lastModule) { diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index c0586225..a095a258 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Music public const string MusicDataPath = "data/musicdata"; private IGoogleApiService _google; - public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base(loc, cmds, client) + public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base() { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 4c16efbb..0d95ee21 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.NSFW [NadekoModule("NSFW", "~")] public class NSFW : DiscordModule { - public NSFW(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public NSFW() : base() { } diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index ac459dd0..8ef8f5c4 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Permissions public class CmdCdsCommands { public static ConcurrentDictionary> commandCooldowns { get; } - private static ConcurrentDictionary> activeCooldowns = new ConcurrentDictionary>(); + private static ConcurrentDictionary> activeCooldowns { get; } = new ConcurrentDictionary>(); static CmdCdsCommands() { diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index a581e007..d6f22fb5 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -14,14 +14,14 @@ namespace NadekoBot.Modules.Permissions [Group] public class FilterCommands { - public static ConcurrentHashSet InviteFilteringChannels { get; set; } - public static ConcurrentHashSet InviteFilteringServers { get; set; } + public static ConcurrentHashSet InviteFilteringChannels { get; } + public static ConcurrentHashSet InviteFilteringServers { get; } //serverid, filteredwords - private static ConcurrentDictionary> ServerFilteredWords { get; set; } + private static ConcurrentDictionary> ServerFilteredWords { get; } - public static ConcurrentHashSet WordFilteringChannels { get; set; } - public static ConcurrentHashSet WordFilteringServers { get; set; } + public static ConcurrentHashSet WordFilteringChannels { get; } + public static ConcurrentHashSet WordFilteringServers { get; } public static ConcurrentHashSet FilteredWordsForChannel(ulong channelId, ulong guildId) { diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 8d6c32ea..815896f6 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions } //guildid, root permission - public static ConcurrentDictionary Cache; + public static ConcurrentDictionary Cache { get; } static Permissions() { @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions } } - public Permissions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Permissions() : base() { } diff --git a/src/NadekoBot/Modules/Pokemon/Pokemon.cs b/src/NadekoBot/Modules/Pokemon/Pokemon.cs index 35e1b703..31dbf2cb 100644 --- a/src/NadekoBot/Modules/Pokemon/Pokemon.cs +++ b/src/NadekoBot/Modules/Pokemon/Pokemon.cs @@ -27,7 +27,7 @@ namespace NadekoBot.Modules.Pokemon private Logger _pokelog { get; } - public Pokemon(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Pokemon() : base() { _pokelog = LogManager.GetCurrentClassLogger(); if (File.Exists(PokemonTypesFile)) diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index 8571846b..24789931 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -10,6 +10,7 @@ using NLog; using System; using System.Collections.Generic; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Searches @@ -19,14 +20,30 @@ namespace NadekoBot.Modules.Searches [Group] public class AnimeSearchCommands { - private Logger _log; + private static Timer anilistTokenRefresher { get; } + private static Logger _log { get; } + private static string anilistToken { get; set; } - private string anilistToken { get; set; } - private DateTime lastRefresh { get; set; } - - public AnimeSearchCommands() + static AnimeSearchCommands() { _log = LogManager.GetCurrentClassLogger(); + anilistTokenRefresher = new Timer(async (state) => + { + var headers = new Dictionary { + {"grant_type", "client_credentials"}, + {"client_id", "kwoth-w0ki9"}, + {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, + }; + + using (var http = new HttpClient()) + { + http.AddFakeHeaders(); + var formContent = new FormUrlEncodedContent(headers); + var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); + var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); + } + }, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29)); } [NadekoCommand, Usage, Description, Aliases] @@ -119,7 +136,6 @@ namespace NadekoBot.Modules.Searches throw new ArgumentNullException(nameof(query)); try { - await RefreshAnilistToken().ConfigureAwait(false); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); using (var http = new HttpClient()) @@ -137,37 +153,12 @@ namespace NadekoBot.Modules.Searches } } - private async Task RefreshAnilistToken() - { - if (DateTime.Now - lastRefresh > TimeSpan.FromMinutes(29)) - lastRefresh = DateTime.Now; - else - { - return; - } - var headers = new Dictionary { - {"grant_type", "client_credentials"}, - {"client_id", "kwoth-w0ki9"}, - {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, - }; - using (var http = new HttpClient()) - { - http.AddFakeHeaders(); - var formContent = new FormUrlEncodedContent(headers); - var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); - var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); - } - - } - private async Task GetMangaData(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); try { - await RefreshAnilistToken().ConfigureAwait(false); using (var http = new HttpClient()) { var res = await http.GetStringAsync("http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index 98695f6f..f22fbf88 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -19,11 +19,11 @@ namespace NadekoBot.Modules.Searches [Group] public class JokeCommands { - private List wowJokes = new List(); - private List magicItems; - private Logger _log; + private static List wowJokes = new List(); + private static List magicItems; + private static Logger _log; - public JokeCommands() + static JokeCommands() { _log = LogManager.GetCurrentClassLogger(); if (File.Exists("data/wowjokes.json")) diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index b915a835..50ad53ea 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -23,7 +23,7 @@ namespace NadekoBot.Modules.Searches obj["name"].GetHashCode(); } - private string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.", + private static string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.", "Go with the flow. Don't think. Just ban one of these.", "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.", "Ask your teammates what would they like to play, and ban that.", diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index e3d663a5..de26d025 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -18,9 +18,9 @@ namespace NadekoBot.Modules.Searches [Group] public class OsuCommands { - private Logger _log; + private static Logger _log; - public OsuCommands() + static OsuCommands() { _log = LogManager.GetCurrentClassLogger(); } diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index efb7ee93..c2750c54 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -21,9 +21,9 @@ namespace NadekoBot.Modules.Searches public const string PokemonAbilitiesFile = "data/pokemon/pokemon_abilities.json"; public const string PokemonListFile = "data/pokemon/pokemon_list.json"; - private Logger _log; + private static Logger _log; - public PokemonSearchCommands() + static PokemonSearchCommands() { _log = LogManager.GetCurrentClassLogger(); if (File.Exists(PokemonListFile)) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 39b60c2b..b8b21bf5 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -69,14 +69,14 @@ namespace NadekoBot.Modules.Searches [Group] public class StreamNotificationCommands { - private Timer checkTimer { get; } - private ConcurrentDictionary oldCachedStatuses = new ConcurrentDictionary(); - private ConcurrentDictionary cachedStatuses = new ConcurrentDictionary(); - private Logger _log { get; } + private static Timer checkTimer { get; } + private static ConcurrentDictionary oldCachedStatuses = new ConcurrentDictionary(); + private static ConcurrentDictionary cachedStatuses = new ConcurrentDictionary(); + private static Logger _log { get; } - private bool FirstPass { get; set; } = true; + private static bool FirstPass { get; set; } = true; - public StreamNotificationCommands() + static StreamNotificationCommands() { _log = NLog.LogManager.GetCurrentClassLogger(); @@ -118,7 +118,7 @@ namespace NadekoBot.Modules.Searches }, null, TimeSpan.Zero, TimeSpan.FromSeconds(60)); } - private async Task GetStreamStatus(FollowedStream stream, bool checkCache = true) + private static async Task GetStreamStatus(FollowedStream stream, bool checkCache = true) { string response; StreamStatus result; diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index bd55e1e1..67a4fdc9 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Searches { private IGoogleApiService _google { get; } - public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base(loc, cmds, client) + public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base() { _google = youtube; } diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index edf3d974..90f71c55 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility if (guild == null) server = channel.Guild; else - server = _client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault(); + server = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault(); if (server == null) return; diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index c0a319f8..1e6fce9c 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility [NadekoModule("Utility", ".")] public partial class Utility : DiscordModule { - public Utility(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Utility() : base() { } @@ -236,8 +236,11 @@ namespace NadekoBot.Modules.Utility var result = string.Join("\n", matches.Cast() .Select(m => $"**Name:** {m.Groups["name"]} **Link:** http://discordapp.com/api/emojis/{m.Groups["id"]}.png")); - - await msg.Channel.SendMessageAsync(result).ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(result)) + await msg.Channel.SendErrorAsync("No special emojis found."); + else + await msg.Channel.SendMessageAsync(result).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index e110a8e2..1de7c3d3 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -75,12 +75,12 @@ namespace NadekoBot CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); - //setup DI - var depMap = new DependencyMap(); - depMap.Add(Localizer); - depMap.Add(Client); - depMap.Add(CommandService); - depMap.Add(Google); + ////setup DI + //var depMap = new DependencyMap(); + //depMap.Add(Localizer); + //depMap.Add(Client); + //depMap.Add(CommandService); + //depMap.Add(Google); //setup typereaders @@ -104,7 +104,7 @@ namespace NadekoBot // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); - await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false); + await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false); #if !GLOBAL_NADEKO await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false); #endif diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 29d7e03d..0b5051c7 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -79,80 +79,7 @@ namespace NadekoBot.Extensions public static IEnumerable Members(this IRole role) => NadekoBot.Client.GetGuild(role.GuildId)?.GetUsers().Where(u => u.Roles.Contains(role)) ?? Enumerable.Empty(); - - public static async Task ReplyLong(this IUserMessage msg, string content, string[] breakOn = null, string addToPartialEnd = "", string addToPartialStart = "") - { - if (content.Length == 0) return null; - var characterLimit = 1750; - if (content.Length < characterLimit) return new[] { await msg.Channel.SendMessageAsync(content).ConfigureAwait(false) }; - if (breakOn == null) breakOn = new[] { "\n", " ", " " }; - var list = new List(); - var splitItems = new List(); - foreach (var breaker in breakOn) - { - if (splitItems.Count == 0) - { - splitItems = Regex.Split(content, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); - } - else - { - for (int i = 0; i < splitItems.Count; i++) - { - var temp = splitItems[i]; - if (temp.Length > characterLimit) - { - var splitDeep = Regex.Split(temp, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s)); - splitItems.RemoveAt(i); - splitItems.InsertRange(i, splitDeep); - } - } - } - if (splitItems.All(s => s.Length < characterLimit)) break; - } - //We remove any entries that are larger than 2000 chars - if (splitItems.Any(s => s.Length >= characterLimit)) - { - splitItems = splitItems.Where(s => s.Length < characterLimit).ToList(); - } - //ensured every item can be sent (if individually) - var firstItem = true; - Queue buildItems = new Queue(splitItems); - StringBuilder builder = new StringBuilder(); - - while (buildItems.Count > 0) - { - if (builder.Length == 0) - { - //first item to add - if (!firstItem) - builder.Append(addToPartialStart); - else - firstItem = false; - builder.Append(buildItems.Dequeue()); - } - else - { - builder.Append(buildItems.Dequeue()); - } - if (buildItems.Count == 0) - { - list.Add(await msg.Channel.SendMessageAsync(builder.ToString())); - builder.Clear(); - } - else - { - var peeked = buildItems.Peek(); - if (builder.Length + peeked.Length + addToPartialEnd.Length > characterLimit) - { - builder.Append(addToPartialEnd); - list.Add(await msg.Channel.SendMessageAsync(builder.ToString())); - builder.Clear(); - } - } - } - return list.ToArray(); - } - + public static Task EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index b5fd1cbb..cbf49aa2 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -60,8 +60,11 @@ }, "configurations": { "GlobalNadeko": { - "buildOptions": { "define": [ "GLOBAL_NADEKO" ] }, - "compilationOptions": { "optimize": true } + "buildOptions": { + "define": [ "GLOBAL_NADEKO" ], + "nowarn": [ "CS1573", "CS1591" ], + "optimize": true + } } } } From 318701e25ac85bfbeb8397596a6d159d99a3583d Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 18:35:56 +0100 Subject: [PATCH 07/12] Small change to discord.net --- discord.net | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord.net b/discord.net index 57fc8290..63cc61d8 160000 --- a/discord.net +++ b/discord.net @@ -1 +1 @@ -Subproject commit 57fc8290666dba35b2385c97e3a51c493b40a425 +Subproject commit 63cc61d8db062fcbd577dc5f9e764a61f283689b From b3635ae577a4f725b67ea9868143c06434a6312d Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 18:46:08 +0100 Subject: [PATCH 08/12] Now even compiles and runs --- .../Administration/Commands/LogCommand.cs | 2 +- .../Administration/Commands/SelfCommands.cs | 4 ++-- src/NadekoBot/Modules/Music/Music.cs | 11 ++++------- src/NadekoBot/Modules/Searches/Searches.cs | 19 ++++++------------- src/NadekoBot/NadekoBot.cs | 4 +--- src/NadekoBot/Services/ILocalization.cs | 7 ------- src/NadekoBot/Services/Impl/Localization.cs | 2 +- src/NadekoBot/Services/Impl/StatsService.cs | 2 +- 8 files changed, 16 insertions(+), 35 deletions(-) delete mode 100644 src/NadekoBot/Services/ILocalization.cs diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 674bc681..9913c53b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -63,7 +63,7 @@ namespace NadekoBot.Modules.Administration }, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); } - public LogCommands(ShardedDiscordClient client) + public LogCommands() { //_client.MessageReceived += _client_MessageReceived; _client.MessageUpdated += _client_MessageUpdated; diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index 0c634461..d153a2dd 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -13,9 +13,9 @@ namespace NadekoBot.Modules.Administration { private ShardedDiscordClient _client; - public SelfCommands(ShardedDiscordClient client) + public SelfCommands() { - this._client = client; + this._client = NadekoBot.Client; } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index a095a258..6c4bc301 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -20,19 +20,16 @@ namespace NadekoBot.Modules.Music [NadekoModule("Music", "!!", AutoLoad = false)] public partial class Music : DiscordModule { - public static ConcurrentDictionary MusicPlayers = new ConcurrentDictionary(); + public static ConcurrentDictionary MusicPlayers { get; } = new ConcurrentDictionary(); public const string MusicDataPath = "data/musicdata"; - private IGoogleApiService _google; - public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base() + public Music() : base() { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } Directory.CreateDirectory(MusicDataPath); - - _google = google; } [NadekoCommand, Usage, Description, Aliases] @@ -259,13 +256,13 @@ namespace NadekoBot.Modules.Music await channel.SendMessageAsync("πŸ’’ You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); return; } - var plId = (await _google.GetPlaylistIdsByKeywordsAsync(arg).ConfigureAwait(false)).FirstOrDefault(); + var plId = (await NadekoBot.Google.GetPlaylistIdsByKeywordsAsync(arg).ConfigureAwait(false)).FirstOrDefault(); if (plId == null) { await channel.SendMessageAsync("No search results for that query."); return; } - var ids = await _google.GetPlaylistTracksAsync(plId, 500).ConfigureAwait(false); + var ids = await NadekoBot.Google.GetPlaylistTracksAsync(plId, 500).ConfigureAwait(false); if (!ids.Any()) { await channel.SendMessageAsync($"🎡 `Failed to find any songs.`").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 67a4fdc9..88865a41 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -23,13 +23,6 @@ namespace NadekoBot.Modules.Searches [NadekoModule("Searches", "~")] public partial class Searches : DiscordModule { - private IGoogleApiService _google { get; } - - public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base() - { - _google = youtube; - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Weather(IUserMessage umsg, string city, string country) @@ -63,7 +56,7 @@ namespace NadekoBot.Modules.Searches { var channel = (ITextChannel)umsg.Channel; if (!(await ValidateQuery(channel, query).ConfigureAwait(false))) return; - var result = (await _google.GetVideosByKeywordsAsync(query, 1)).FirstOrDefault(); + var result = (await NadekoBot.Google.GetVideosByKeywordsAsync(query, 1)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(result)) { await channel.SendMessageAsync("No results found for that query."); @@ -186,7 +179,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(ffs)) return; - await channel.SendMessageAsync(await _google.ShortenUrl($"")) + await channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl($"")) .ConfigureAwait(false); } @@ -240,7 +233,7 @@ namespace NadekoBot.Modules.Searches throw new KeyNotFoundException("Cannot find a card by that name"); var msg = $@"```css [β˜• Magic The Gathering]: {items[0]["name"].ToString()} -[Store URL]: {await _google.ShortenUrl(items[0]["store_url"].ToString())} +[Store URL]: {await NadekoBot.Google.ShortenUrl(items[0]["store_url"].ToString())} [Cost]: {items[0]["cost"].ToString()} [Description]: {items[0]["text"].ToString()} ``` @@ -387,7 +380,7 @@ namespace NadekoBot.Modules.Searches var sb = new StringBuilder(); sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); - sb.Append($"`Link:` <{await _google.ShortenUrl(items["list"][0]["permalink"].ToString()).ConfigureAwait(false)}>"); + sb.Append($"`Link:` <{await NadekoBot.Google.ShortenUrl(items["list"][0]["permalink"].ToString()).ConfigureAwait(false)}>"); await channel.SendMessageAsync(sb.ToString()); } catch @@ -429,7 +422,7 @@ namespace NadekoBot.Modules.Searches var items = JObject.Parse(res); var str = $@"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()} `Definition:` {items["defs"]["def"]["text"].ToString()} -`Link:` <{await _google.ShortenUrl(items["defs"]["def"]["uri"].ToString()).ConfigureAwait(false)}>"; +`Link:` <{await NadekoBot.Google.ShortenUrl(items["defs"]["def"]["uri"].ToString()).ConfigureAwait(false)}>"; await channel.SendMessageAsync(str); } catch @@ -564,7 +557,7 @@ namespace NadekoBot.Modules.Searches await channel.SendMessageAsync("Invalid user specified.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(await _google.ShortenUrl(usr.AvatarUrl).ConfigureAwait(false)).ConfigureAwait(false); + await channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl(usr.AvatarUrl).ConfigureAwait(false)).ConfigureAwait(false); } public static async Task GetSafebooruImageLink(string tag) diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 1de7c3d3..c0e5d9e0 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -30,7 +30,6 @@ namespace NadekoBot public static CommandService CommandService { get; private set; } public static CommandHandler CommandHandler { get; private set; } public static ShardedDiscordClient Client { get; private set; } - public static Localization Localizer { get; private set; } public static BotCredentials Credentials { get; private set; } public static GoogleApiService Google { get; private set; } @@ -70,7 +69,6 @@ namespace NadekoBot //initialize Services CommandService = new CommandService(); - Localizer = new Localization(); Google = new GoogleApiService(); CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); @@ -106,7 +104,7 @@ namespace NadekoBot await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false); #if !GLOBAL_NADEKO - await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false); + await CommandService.Load(new Music()).ConfigureAwait(false); #endif Ready = true; Console.WriteLine(await Stats.Print().ConfigureAwait(false)); diff --git a/src/NadekoBot/Services/ILocalization.cs b/src/NadekoBot/Services/ILocalization.cs deleted file mode 100644 index 892278da..00000000 --- a/src/NadekoBot/Services/ILocalization.cs +++ /dev/null @@ -1,7 +0,0 @@ -ο»Ώnamespace NadekoBot.Services -{ - public interface ILocalization - { - string this[string key] { get; } - } -} diff --git a/src/NadekoBot/Services/Impl/Localization.cs b/src/NadekoBot/Services/Impl/Localization.cs index 0bcecd45..5ec6e71d 100644 --- a/src/NadekoBot/Services/Impl/Localization.cs +++ b/src/NadekoBot/Services/Impl/Localization.cs @@ -1,6 +1,6 @@ ο»Ώnamespace NadekoBot.Services { - public class Localization : ILocalization + public class Localization { public string this[string key] => LoadCommandString(key); diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 90378128..8b71f3c4 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -31,7 +31,7 @@ namespace NadekoBot.Services.Impl Timer carbonitexTimer { get; } - public StatsService(ShardedDiscordClient client, CommandHandler cmdHandler) + public StatsService(ShardedDiscordClient client, CommandHandler cmdHandler) { this.client = client; From b907f1bf2f854307fab7259671a730955194cdda Mon Sep 17 00:00:00 2001 From: Kwoth Date: Thu, 8 Dec 2016 21:20:13 +0100 Subject: [PATCH 09/12] Searches.cs prettified with embeds :sparkles: --- .../Searches/Commands/OMDB/OmdbProvider.cs | 15 +- src/NadekoBot/Modules/Searches/Searches.cs | 205 +++++++++++------- 2 files changed, 135 insertions(+), 85 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs index a4fffa9d..02373bb3 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs @@ -1,4 +1,6 @@ -ο»Ώusing Newtonsoft.Json; +ο»Ώusing Discord; +using Discord.API; +using Newtonsoft.Json; using System; using System.Net.Http; using System.Threading.Tasks; @@ -32,6 +34,17 @@ namespace NadekoBot.Modules.Searches.Commands.OMDB public string Plot { get; set; } public string Poster { get; set; } + public Embed GetEmbed() => + new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithTitle(Title) + .WithUrl($"http://www.imdb.com/title/{ImdbId}/") + .WithDescription(Plot) + .AddField(efb => efb.WithName("Rating").WithValue(ImdbRating).WithIsInline(true)) + .AddField(efb => efb.WithName("Genre").WithValue(Genre).WithIsInline(true)) + .AddField(efb => efb.WithName("Year").WithValue(Year).WithIsInline(true)) + .WithImage(eib => eib.WithUrl(Poster)) + .Build(); + public override string ToString() => $@"`Title:` {Title} `Year:` {Year} diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 88865a41..551f61dc 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -59,10 +59,13 @@ namespace NadekoBot.Modules.Searches var result = (await NadekoBot.Google.GetVideosByKeywordsAsync(query, 1)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(result)) { - await channel.SendMessageAsync("No results found for that query."); + await channel.SendErrorAsync("No results found for that query.").ConfigureAwait(false); return; } + await channel.SendMessageAsync(result).ConfigureAwait(false); + + //await channel.EmbedAsync(new Discord.API.Embed() { Video = new Discord.API.EmbedVideo() { Url = result.Replace("watch?v=", "embed/") }, Color = NadekoBot.OkColor }).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -77,10 +80,10 @@ namespace NadekoBot.Modules.Searches var movie = await OmdbProvider.FindMovie(query); if (movie == null) { - await channel.SendMessageAsync("Failed to find that movie.").ConfigureAwait(false); + await channel.SendErrorAsync("Failed to find that movie.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(movie.ToString()).ConfigureAwait(false); + await channel.EmbedAsync(movie.GetEmbed()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -90,9 +93,8 @@ namespace NadekoBot.Modules.Searches var channel = (ITextChannel)umsg.Channel; using (var http = new HttpClient()) { - await channel.SendMessageAsync(JObject.Parse( - await http.GetStringAsync("http://www.random.cat/meow").ConfigureAwait(false))["file"].ToString()) - .ConfigureAwait(false); + var res = JObject.Parse(await http.GetStringAsync("http://www.random.cat/meow").ConfigureAwait(false)); + await channel.SendMessageAsync(res["file"].ToString()).ConfigureAwait(false); } } @@ -103,7 +105,8 @@ namespace NadekoBot.Modules.Searches var channel = (ITextChannel)umsg.Channel; using (var http = new HttpClient()) { - await channel.SendMessageAsync("http://random.dog/" + await http.GetStringAsync("http://random.dog/woof").ConfigureAwait(false)).ConfigureAwait(false); + await channel.SendMessageAsync("http://random.dog/" + await http.GetStringAsync("http://random.dog/woof") + .ConfigureAwait(false)).ConfigureAwait(false); } } @@ -128,11 +131,12 @@ namespace NadekoBot.Modules.Searches { if (exception.Message.Contains("403 (Forbidden)")) { - await channel.SendMessageAsync("Daily limit reached!"); + await channel.SendErrorAsync("Daily limit reached!"); } else { - await channel.SendMessageAsync("Something went wrong."); + await channel.SendErrorAsync("Something went wrong."); + _log.Error(exception); } } } @@ -160,11 +164,12 @@ namespace NadekoBot.Modules.Searches { if (exception.Message.Contains("403 (Forbidden)")) { - await channel.SendMessageAsync("Daily limit reached!"); + await channel.SendErrorAsync("Daily limit reached!"); } else { - await channel.SendMessageAsync("Something went wrong."); + await channel.SendErrorAsync("Something went wrong."); + _log.Error(exception); } } } @@ -179,7 +184,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(ffs)) return; - await channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl($"")) + await channel.SendConfirmAsync(await NadekoBot.Google.ShortenUrl($"")) .ConfigureAwait(false); } @@ -190,7 +195,19 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(arg)) return; - await msg.Channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl(arg).ConfigureAwait(false)); + var shortened = await NadekoBot.Google.ShortenUrl(arg).ConfigureAwait(false); + + if (shortened == arg) + { + await msg.Channel.SendErrorAsync("Failed to shorten that url."); + } + + await msg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + .AddField(efb => efb.WithName("Original Url") + .WithValue($"<{arg}>")) + .AddField(efb => efb.WithName("Short Url") + .WithValue($"<{shortened}>")) + .Build()); } [NadekoCommand, Usage, Description, Aliases] @@ -198,12 +215,12 @@ namespace NadekoBot.Modules.Searches public async Task Google(IUserMessage umsg, [Remainder] string terms = null) { var channel = (ITextChannel)umsg.Channel; - - + terms = terms?.Trim(); if (string.IsNullOrWhiteSpace(terms)) return; - await channel.SendMessageAsync($"https://google.com/search?q={ WebUtility.UrlEncode(terms).Replace(' ', '+') }") + + await channel.SendConfirmAsync($"https://google.com/search?q={ WebUtility.UrlEncode(terms).Replace(' ', '+') }") .ConfigureAwait(false); } @@ -215,7 +232,7 @@ namespace NadekoBot.Modules.Searches var arg = name; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ `Please enter a card name to search for.`").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); return; } @@ -231,18 +248,26 @@ namespace NadekoBot.Modules.Searches var items = JArray.Parse(response).Shuffle().ToList(); if (items == null) throw new KeyNotFoundException("Cannot find a card by that name"); - var msg = $@"```css -[β˜• Magic The Gathering]: {items[0]["name"].ToString()} -[Store URL]: {await NadekoBot.Google.ShortenUrl(items[0]["store_url"].ToString())} -[Cost]: {items[0]["cost"].ToString()} -[Description]: {items[0]["text"].ToString()} -``` -{items[0]["editions"][0]["image_url"].ToString()}"; - await channel.SendMessageAsync(msg).ConfigureAwait(false); + var item = items[0]; + var storeUrl = await NadekoBot.Google.ShortenUrl(item["store_url"].ToString()); + var cost = item["cost"].ToString(); + var desc = item["text"].ToString(); + var types = String.Join(",\n", item["types"].ToObject()); + var img = item["editions"][0]["image_url"].ToString(); + var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithTitle(item["name"].ToString()) + .WithDescription(desc) + .WithImage(eib => eib.WithUrl(img)) + .AddField(efb => efb.WithName("Store Url").WithValue(storeUrl).WithIsInline(true)) + .AddField(efb => efb.WithName("Cost").WithValue(cost).WithIsInline(true)) + .AddField(efb => efb.WithName("Types").WithValue(types).WithIsInline(true)); + //.AddField(efb => efb.WithName("Store Url").WithValue(await NadekoBot.Google.ShortenUrl(items[0]["store_url"].ToString())).WithIsInline(true)); + + await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); } catch { - await channel.SendMessageAsync($"πŸ’’ Error could not find the card {arg}").ConfigureAwait(false); + await channel.SendErrorAsync($"Error could not find the card '{arg}'.").ConfigureAwait(false); } } } @@ -255,13 +280,13 @@ namespace NadekoBot.Modules.Searches var arg = name; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ `Please enter a card name to search for.`").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendMessageAsync("πŸ’’ `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false); + await channel.SendErrorAsync ("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } @@ -301,7 +326,8 @@ namespace NadekoBot.Modules.Searches } catch (Exception ex) { - await channel.SendMessageAsync($"πŸ’’ Error {ex.Message}").ConfigureAwait(false); + await channel.SendErrorAsync($"Error occured.").ConfigureAwait(false); + _log.Error(ex); } } } @@ -314,14 +340,14 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendMessageAsync("πŸ’’ `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false); + await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ `Please enter a sentence.`").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a sentence.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -334,18 +360,15 @@ namespace NadekoBot.Modules.Searches try { var embed = new EmbedBuilder() - .WithTitle("Young Padawan") .WithUrl("http://www.yodaspeak.co.uk/") .WithAuthor(au => au.WithName("Yoda").WithIconUrl("http://www.yodaspeak.co.uk/yoda-small1.gif")) - .WithDescription("Seek advice, you must!") - .WithThumbnail(th => th.WithUrl("http://i.imgur.com/62Uh4u6.jpg")) - .AddField(fb => fb.WithName($"🌍 **{umsg.Author.Username}**").WithValue($"{res.ToString()}").WithIsInline(false)) + .WithDescription(res) .WithColor(NadekoBot.OkColor); await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); } catch { - await channel.SendMessageAsync("πŸ’’ Failed to yodify your sentence.").ConfigureAwait(false); + await channel.SendErrorAsync("Failed to yodify your sentence.").ConfigureAwait(false); } } } @@ -358,14 +381,14 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendMessageAsync("πŸ’’ `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false); + await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ `Please enter a search term.`").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -377,15 +400,19 @@ namespace NadekoBot.Modules.Searches try { var items = JObject.Parse(res); - var sb = new StringBuilder(); - sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}"); - sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); - sb.Append($"`Link:` <{await NadekoBot.Google.ShortenUrl(items["list"][0]["permalink"].ToString()).ConfigureAwait(false)}>"); - await channel.SendMessageAsync(sb.ToString()); + var item = items["list"][0]; + var word = item["word"].ToString(); + var def = item["definition"].ToString(); + var link = item["permalink"].ToString(); + var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithUrl(link) + .WithAuthor(eab => eab.WithIconUrl("http://i.imgur.com/nwERwQE.jpg").WithName(word)) + .WithDescription(def); + await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); } catch { - await channel.SendMessageAsync("πŸ’’ Failed finding a definition for that term.").ConfigureAwait(false); + await channel.SendErrorAsync("Failed finding a definition for that term.").ConfigureAwait(false); } } } @@ -399,12 +426,12 @@ namespace NadekoBot.Modules.Searches var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ `Please enter a search term.`").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendMessageAsync("πŸ’’ `Bot owner didn't specify MashapeApiKey. You can't use this functionality.`").ConfigureAwait(false); + await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } @@ -420,14 +447,20 @@ namespace NadekoBot.Modules.Searches try { var items = JObject.Parse(res); - var str = $@"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()} -`Definition:` {items["defs"]["def"]["text"].ToString()} -`Link:` <{await NadekoBot.Google.ShortenUrl(items["defs"]["def"]["uri"].ToString()).ConfigureAwait(false)}>"; - await channel.SendMessageAsync(str); + var item = items["defs"]["def"]; + var hashtag = item["hashtag"].ToString(); + var link = item["uri"].ToString(); + var desc = item["text"].ToString(); + await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithAuthor(eab => eab.WithUrl(link) + .WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg") + .WithName(query)) + .WithDescription(desc) + .Build()); } catch { - await channel.SendMessageAsync("πŸ’’ Failed finding a definition for that tag.").ConfigureAwait(false); + await channel.SendErrorAsync("Failed finding a definition for that tag.").ConfigureAwait(false); } } @@ -441,7 +474,9 @@ namespace NadekoBot.Modules.Searches var response = await http.GetStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false); if (response == null) return; - await channel.SendMessageAsync($"🐈 `{JObject.Parse(response)["facts"][0].ToString()}`").ConfigureAwait(false); + + var fact = JObject.Parse(response)["facts"][0].ToString(); + await channel.SendConfirmAsync("🐈fact", fact).ConfigureAwait(false); } } @@ -453,7 +488,7 @@ namespace NadekoBot.Modules.Searches if (usr == null) usr = umsg.Author; - await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); + await channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -465,7 +500,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(imageLink)) return; - await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false); + await channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -477,7 +512,7 @@ namespace NadekoBot.Modules.Searches tag = tag?.Trim() ?? ""; var link = await GetSafebooruImageLink(tag).ConfigureAwait(false); if (link == null) - await channel.SendMessageAsync("`No results.`"); + await channel.SendErrorAsync("No results."); else await channel.SendMessageAsync(link).ConfigureAwait(false); } @@ -496,7 +531,7 @@ namespace NadekoBot.Modules.Searches var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)); var data = JsonConvert.DeserializeObject(result); if (data.Query.Pages[0].Missing) - await channel.SendMessageAsync("`That page could not be found.`"); + await channel.SendErrorAsync("That page could not be found."); else await channel.SendMessageAsync(data.Query.Pages[0].FullUrl); } @@ -536,12 +571,12 @@ namespace NadekoBot.Modules.Searches str += new NadekoRandom().Next(); foreach (var usr in allUsrsArray) { - await (await (usr as IGuildUser).CreateDMChannelAsync()).SendMessageAsync(str).ConfigureAwait(false); + await (await (usr as IGuildUser).CreateDMChannelAsync()).SendConfirmAsync(str).ConfigureAwait(false); } } catch (Exception ex) { - Console.WriteLine(ex); + _log.Error(ex); } } @@ -554,7 +589,7 @@ namespace NadekoBot.Modules.Searches var usr = umsg.MentionedUsers.FirstOrDefault(); if (usr == null) { - await channel.SendMessageAsync("Invalid user specified.").ConfigureAwait(false); + await channel.SendErrorAsync("Invalid user specified.").ConfigureAwait(false); return; } await channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl(usr.AvatarUrl).ConfigureAwait(false)).ConfigureAwait(false); @@ -576,23 +611,23 @@ namespace NadekoBot.Modules.Searches } } + public enum BfGame + { + Bf3, Bf4 + } + [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task BFO(IUserMessage umsg, [Remainder] string game = null) + public async Task BFO(IUserMessage umsg, [Remainder] BfGame game) { var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(game)) - { - await channel.SendMessageAsync("πŸ’’ Please enter a game `(bf3, bf4)`").ConfigureAwait(false); - return; - } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); try { - if (game.Equals("bf3", StringComparison.OrdinalIgnoreCase)) + if (game == BfGame.Bf3) { var res = await http.GetStringAsync($"http://api.bf3stats.com/global/onlinestats/").ConfigureAwait(false); var items = JObject.Parse(res); @@ -610,7 +645,7 @@ PC: βœ”[{pc.ToString()}] ```"; await channel.SendMessageAsync(response); } - else if (game.Equals("bf4", StringComparison.OrdinalIgnoreCase)) + else if (game == BfGame.Bf4) { var res = await http.GetStringAsync($"http://api.bf4stats.com/api/onlinePlayers?output=json").ConfigureAwait(false); var items = JObject.Parse(res); @@ -625,29 +660,31 @@ PC: βœ”[{pc.ToString()}] sb.AppendLine("```css"); sb.AppendLine($"[β˜• BF4 Status: {status}]"); - foreach (var i in items) { + foreach (var i in items) + { var plat = items[i.Key]; sb.AppendLine($"{plat["label"]}: βœ”[{plat["count"]}] / ↑[{plat["peak24"]}]"); } sb.Append("```"); - await channel.SendMessageAsync(sb.ToString()); + await channel.SendConfirmAsync(sb.ToString()); } - } catch + } + catch { - await channel.SendMessageAsync($"πŸ’’ BF3/BF4 API is most likely not working at the moment or could not find {game}.").ConfigureAwait(false); + await channel.SendErrorAsync($"BF3/BF4 API is most likely not working at the moment or could not find {game}.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task BFU(IUserMessage umsg, string platform, string game, [Remainder] string query = null) + public async Task BFU(IUserMessage umsg, string platform, BfGame game, [Remainder] string query = null) { var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(platform) || string.IsNullOrWhiteSpace(game) || string.IsNullOrWhiteSpace(query)) + if (string.IsNullOrWhiteSpace(platform) || string.IsNullOrWhiteSpace(query)) { - await channel.SendMessageAsync("πŸ’’ Please enter a platform `(pc, xbox, ps3, xone, ps4)`, game `(bf3, bf4)`, followed by a search query.").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a platform `(pc, xbox, ps3, xone, ps4)`, game `(bf3, bf4)`, followed by a search query.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -656,7 +693,7 @@ PC: βœ”[{pc.ToString()}] http.DefaultRequestHeaders.Clear(); try { - if (game.Equals("bf3", StringComparison.OrdinalIgnoreCase)) + if (game == BfGame.Bf3) { var res = await http.GetStringAsync($"http://api.bf3stats.com/{Uri.EscapeUriString(platform)}/playerlist/players={Uri.EscapeUriString(query)}?output=json").ConfigureAwait(false); var items = JObject.Parse(res); @@ -688,7 +725,7 @@ Accuracy: %[{playerGlobal_Accuracy.ToString()}] ELO: [{playerGlobal_ELO.ToString()}] ```"; await channel.SendMessageAsync(response); - } else if (game.Equals("bf4", StringComparison.OrdinalIgnoreCase)) + } else if (game == BfGame.Bf4) { var res = await http.GetStringAsync($"http://api.bf4stats.com/api/playerInfo?plat={Uri.EscapeUriString(platform)}&name={Uri.EscapeUriString(query)}&output=json").ConfigureAwait(false); var items = JObject.Parse(res); @@ -725,7 +762,7 @@ ELO: [{playerELO.ToString()}] } catch { - await channel.SendMessageAsync($"πŸ’’ BF3/BF4 API is most likely not working at the moment or could not find {query}.").ConfigureAwait(false); + await channel.SendErrorAsync($"BF3/BF4 API is most likely not working at the moment or could not find {query}.").ConfigureAwait(false); } } } @@ -737,7 +774,7 @@ ELO: [{playerELO.ToString()}] var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query)) { - await channel.SendMessageAsync("πŸ’’ Please enter a target wikia, followed by search query.").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter a target wikia, followed by search query.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -756,7 +793,7 @@ ELO: [{playerELO.ToString()}] } catch { - await channel.SendMessageAsync($"πŸ’’ Failed finding `{query}`.").ConfigureAwait(false); + await channel.SendErrorAsync($"Failed finding `{query}`.").ConfigureAwait(false); } } } @@ -769,7 +806,7 @@ ELO: [{playerELO.ToString()}] var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ Please enter a `ip:port`.").ConfigureAwait(false); + await channel.SendErrorAsync("πŸ’’ Please enter a `ip:port`.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -793,7 +830,7 @@ ELO: [{playerELO.ToString()}] } catch { - await channel.SendMessageAsync($"πŸ’’ Failed finding `{arg}`.").ConfigureAwait(false); + await channel.SendErrorAsync($"Failed finding `{arg}`.").ConfigureAwait(false); } } } @@ -806,7 +843,7 @@ ELO: [{playerELO.ToString()}] var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendMessageAsync("πŸ’’ Please enter a `ip:port`.").ConfigureAwait(false); + await channel.SendErrorAsync("Please enter `ip:port`.").ConfigureAwait(false); return; } await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -833,7 +870,7 @@ ELO: [{playerELO.ToString()}] } catch { - await channel.SendMessageAsync($"πŸ’’ Failed finding server `{arg}`.").ConfigureAwait(false); + await channel.SendErrorAsync($"Failed finding server `{arg}`.").ConfigureAwait(false); } } } @@ -841,7 +878,7 @@ ELO: [{playerELO.ToString()}] public static async Task ValidateQuery(ITextChannel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) return true; - await ch.SendMessageAsync("Please specify search parameters.").ConfigureAwait(false); + await ch.SendErrorAsync("Please specify search parameters.").ConfigureAwait(false); return false; } } From 937fd5b32daca636735244791aa1e7f2761559c1 Mon Sep 17 00:00:00 2001 From: fkndean Date: Thu, 8 Dec 2016 17:11:34 -0500 Subject: [PATCH 10/12] remove bf --- src/NadekoBot/Modules/Searches/Searches.cs | 156 ------------------ .../Resources/CommandStrings.Designer.cs | 54 ------ src/NadekoBot/Resources/CommandStrings.resx | 18 -- 3 files changed, 228 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 551f61dc..229a0887 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -610,162 +610,6 @@ namespace NadekoBot.Modules.Searches return "http:" + matches[rng.Next(0, matches.Count)].Groups["url"].Value; } } - - public enum BfGame - { - Bf3, Bf4 - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task BFO(IUserMessage umsg, [Remainder] BfGame game) - { - var channel = (ITextChannel)umsg.Channel; - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); - using (var http = new HttpClient()) - { - http.DefaultRequestHeaders.Clear(); - try - { - if (game == BfGame.Bf3) - { - var res = await http.GetStringAsync($"http://api.bf3stats.com/global/onlinestats/").ConfigureAwait(false); - var items = JObject.Parse(res); - var sb = new StringBuilder(); - var status = items["status"]; - var x360 = items["360"]; - var ps3 = items["ps3"]; - var pc = items["pc"]; - - var response = $@"```css -[β˜• BF3 Status: {status.ToString().ToUpper()}] -XBOX360: βœ”[{x360.ToString()}] -PS3: βœ”[{ps3.ToString()}] -PC: βœ”[{pc.ToString()}] -```"; - await channel.SendMessageAsync(response); - } - else if (game == BfGame.Bf4) - { - var res = await http.GetStringAsync($"http://api.bf4stats.com/api/onlinePlayers?output=json").ConfigureAwait(false); - var items = JObject.Parse(res); - var sb = new StringBuilder(); - var status = !string.IsNullOrEmpty(items.ToString()) ? "OK" : "BAD"; - var pc = items["pc"]; - var ps3 = items["ps3"]; - var ps4 = items["ps4"]; - var xbox = items["xbox"]; - var xone = items["xone"]; - - sb.AppendLine("```css"); - sb.AppendLine($"[β˜• BF4 Status: {status}]"); - - foreach (var i in items) - { - var plat = items[i.Key]; - sb.AppendLine($"{plat["label"]}: βœ”[{plat["count"]}] / ↑[{plat["peak24"]}]"); - } - - sb.Append("```"); - await channel.SendConfirmAsync(sb.ToString()); - } - } - catch - { - await channel.SendErrorAsync($"BF3/BF4 API is most likely not working at the moment or could not find {game}.").ConfigureAwait(false); - } - } - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task BFU(IUserMessage umsg, string platform, BfGame game, [Remainder] string query = null) - { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(platform) || string.IsNullOrWhiteSpace(query)) - { - await channel.SendErrorAsync("Please enter a platform `(pc, xbox, ps3, xone, ps4)`, game `(bf3, bf4)`, followed by a search query.").ConfigureAwait(false); - return; - } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); - using (var http = new HttpClient()) - { - http.DefaultRequestHeaders.Clear(); - try - { - if (game == BfGame.Bf3) - { - var res = await http.GetStringAsync($"http://api.bf3stats.com/{Uri.EscapeUriString(platform)}/playerlist/players={Uri.EscapeUriString(query)}?output=json").ConfigureAwait(false); - var items = JObject.Parse(res); - var sb = new StringBuilder(); - var playerName = items["list"][query]; - var playerTag = playerName["tag"]; - var playerCountryName = playerName["country_name"]; - var playerStats = playerName["stats"]; - var playerRank = playerStats["rank"]; - var playerRank_name = playerRank["name"]; - var playerGlobal_Kills = playerStats["global"]["kills"]; - var playerGlobal_Deaths = playerStats["global"]["deaths"]; - var playerGlobal_KD = Math.Round(Double.Parse(playerGlobal_Kills.ToString()) / Double.Parse(playerGlobal_Deaths.ToString()), 2); - var playerGlobal_Wins = playerStats["global"]["wins"]; - var playerGlobal_Losses = playerStats["global"]["losses"]; - var playerGlobal_WL = Math.Round(Double.Parse(playerGlobal_Wins.ToString()) / Double.Parse(playerGlobal_Losses.ToString()), 2); - var playerGlobal_Shots = playerStats["global"]["shots"]; - var playerGlobal_Hits = playerStats["global"]["hits"]; - var playerGlobal_Accuracy = Math.Round(Double.Parse(playerGlobal_Hits.ToString()) / Double.Parse(playerGlobal_Shots.ToString()), 2); - var playerGlobal_ELO = playerStats["global"]["elo"]; - - var response = $@"```css -[β˜• BF3 Player: {query}] -Platform: [{platform.ToUpper()}] -Tag: [{playerTag.ToString()}] -K/D: [{playerGlobal_KD.ToString()}] -W/L: [{playerGlobal_WL.ToString()}] -Accuracy: %[{playerGlobal_Accuracy.ToString()}] -ELO: [{playerGlobal_ELO.ToString()}] -```"; - await channel.SendMessageAsync(response); - } else if (game == BfGame.Bf4) - { - var res = await http.GetStringAsync($"http://api.bf4stats.com/api/playerInfo?plat={Uri.EscapeUriString(platform)}&name={Uri.EscapeUriString(query)}&output=json").ConfigureAwait(false); - var items = JObject.Parse(res); - var sb = new StringBuilder(); - - var player = items["player"]; - var playerStats = items["stats"]; - - var playerName = player["name"]; - var playerTag = player["tag"]; - var playerPlatform = player["plat"]; - var playerKills = playerStats["kills"]; - var playerDeaths = playerStats["deaths"]; - var player_KD = Math.Round(Double.Parse(playerKills.ToString()) / Double.Parse(playerDeaths.ToString()), 2); - var playerWins = playerStats["numWins"]; - var playerRounds = playerStats["numRounds"]; - var player_WL = Math.Round(Double.Parse(playerWins.ToString()) / Double.Parse(playerRounds.ToString()), 2); - var shotsFired = playerStats["shotsFired"]; - var shotsHit = playerStats["shotsHit"]; - var accuracy = Math.Round(Double.Parse(shotsHit.ToString()) / Double.Parse(shotsFired.ToString()), 2); - var playerELO = playerStats["elo"]; - - var response = $@"```css -[β˜• BF4 Player: {playerName.ToString()}] -Platform: [{playerPlatform.ToString().ToUpper()}] -Tag: [{playerTag.ToString()}] -K/D: [{player_KD.ToString()}] -W/L: [{player_WL.ToString()}] -Accuracy: %[{accuracy.ToString()}] -ELO: [{playerELO.ToString()}] -```"; - await channel.SendMessageAsync(response); - } - } - catch - { - await channel.SendErrorAsync($"BF3/BF4 API is most likely not working at the moment or could not find {query}.").ConfigureAwait(false); - } - } - } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Resources/CommandStrings.Designer.cs b/src/NadekoBot/Resources/CommandStrings.Designer.cs index 9c0b8ac7..ca398e16 100644 --- a/src/NadekoBot/Resources/CommandStrings.Designer.cs +++ b/src/NadekoBot/Resources/CommandStrings.Designer.cs @@ -788,60 +788,6 @@ namespace NadekoBot.Resources { } } - /// - /// Looks up a localized string similar to bfonline bfo. - /// - public static string bfo_cmd { - get { - return ResourceManager.GetString("bfo_cmd", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Gives you online players for BF3 and BF4. - /// - public static string bfo_desc { - get { - return ResourceManager.GetString("bfo_desc", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to `{0}bfo bf3` or `{0}bfo bf4`. - /// - public static string bfo_usage { - get { - return ResourceManager.GetString("bfo_usage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to bfuser bfu. - /// - public static string bfu_cmd { - get { - return ResourceManager.GetString("bfu_cmd", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Gives you back a battlefield user's stats.. - /// - public static string bfu_desc { - get { - return ResourceManager.GetString("bfu_desc", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to `{0}bfu platform game user`. - /// - public static string bfu_usage { - get { - return ResourceManager.GetString("bfu_usage", resourceCulture); - } - } - /// /// Looks up a localized string similar to boobs. /// diff --git a/src/NadekoBot/Resources/CommandStrings.resx b/src/NadekoBot/Resources/CommandStrings.resx index 18b60146..e114f91c 100644 --- a/src/NadekoBot/Resources/CommandStrings.resx +++ b/src/NadekoBot/Resources/CommandStrings.resx @@ -2673,24 +2673,6 @@ `{0}wikia mtg Vigilance` or `{0}wikia mlp Dashy` - - bfonline bfo - - - Gives you online players for BF3 and BF4 - - - `{0}bfo bf3` or `{0}bfo bf4` - - - bfuser bfu - - - Gives you back a battlefield user's stats. - - - `{0}bfu platform game user` - yandere From 010c679a76fa05b904605e34323378b8b100b581 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 9 Dec 2016 04:22:23 +0100 Subject: [PATCH 11/12] Prettified whole searches module --- .../Searches/Commands/AnimeSearchCommands.cs | 58 +++++++---- .../Modules/Searches/Commands/JokeCommands.cs | 44 +++++---- .../Modules/Searches/Commands/LoLCommands.cs | 15 ++- .../Searches/Commands/MemegenCommands.cs | 18 +--- .../Searches/Commands/Models/MagicItem.cs | 2 - .../Searches/Commands/Models/SearchPokemon.cs | 5 +- .../Modules/Searches/Commands/OsuCommands.cs | 14 +-- .../Searches/Commands/PlaceCommands.cs | 3 +- .../Commands/PokemonSearchCommands.cs | 27 +++-- .../Commands/StreamNotificationCommands.cs | 98 ++++++------------- .../Modules/Searches/Commands/Translator.cs | 16 +-- .../Modules/Searches/Commands/XkcdCommands.cs | 10 +- src/NadekoBot/Modules/Searches/Searches.cs | 7 +- .../Utility/Commands/UnitConversion.cs | 2 +- 14 files changed, 155 insertions(+), 164 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index 24789931..a21ea1f5 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -29,19 +29,25 @@ namespace NadekoBot.Modules.Searches _log = LogManager.GetCurrentClassLogger(); anilistTokenRefresher = new Timer(async (state) => { - var headers = new Dictionary { - {"grant_type", "client_credentials"}, - {"client_id", "kwoth-w0ki9"}, - {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, - }; - - using (var http = new HttpClient()) + try { - http.AddFakeHeaders(); - var formContent = new FormUrlEncodedContent(headers); - var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); - var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); + var headers = new Dictionary { + {"grant_type", "client_credentials"}, + {"client_id", "kwoth-w0ki9"}, + {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, + }; + + using (var http = new HttpClient()) + { + http.AddFakeHeaders(); + var formContent = new FormUrlEncodedContent(headers); + var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); + var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); + } + } + catch (Exception ex) { + _log.Error(ex); } }, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29)); } @@ -57,6 +63,12 @@ namespace NadekoBot.Modules.Searches var animeData = await GetAnimeData(query).ConfigureAwait(false); + if (animeData == null) + { + await umsg.Channel.SendErrorAsync("Failed finding that animu.").ConfigureAwait(false); + return; + } + var embed = new Discord.API.Embed() { Description = animeData.Synopsis, @@ -96,32 +108,38 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(query)) return; - var animeData = await GetMangaData(query).ConfigureAwait(false); + var mangaData = await GetMangaData(query).ConfigureAwait(false); + + if (mangaData == null) + { + await umsg.Channel.SendErrorAsync("Failed finding that mango.").ConfigureAwait(false); + return; + } var embed = new Discord.API.Embed() { - Description = animeData.Synopsis, - Title = animeData.title_english, - Url = animeData.Link, + Description = mangaData.Synopsis, + Title = mangaData.title_english, + Url = mangaData.Link, Image = new Discord.API.EmbedImage() { - Url = animeData.image_url_lge + Url = mangaData.image_url_lge }, Fields = new[] { new Discord.API.EmbedField() { Inline = true, Name = "Chapters", - Value = animeData.total_chapters.ToString() + Value = mangaData.total_chapters.ToString() }, new Discord.API.EmbedField() { Inline = true, Name = "Status", - Value = animeData.publishing_status.ToString() + Value = mangaData.publishing_status.ToString() }, new Discord.API.EmbedField() { Inline = true, Name = "Genres", - Value = String.Join(", ", animeData.Genres) + Value = String.Join(", ", mangaData.Genres) } }, Color = NadekoBot.OkColor diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index f22fbf88..b5327810 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -1,6 +1,7 @@ ο»Ώusing Discord; using Discord.Commands; using NadekoBot.Attributes; +using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Models; using NadekoBot.Services; using Newtonsoft.Json; @@ -19,9 +20,9 @@ namespace NadekoBot.Modules.Searches [Group] public class JokeCommands { - private static List wowJokes = new List(); - private static List magicItems; - private static Logger _log; + private static List wowJokes { get; } = new List(); + private static List magicItems { get; } = new List(); + private static Logger _log { get; } static JokeCommands() { @@ -43,61 +44,62 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Yomama(IUserMessage umsg) + public async Task Yomama(IUserMessage msg) { - var channel = (ITextChannel)umsg.Channel; using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://api.yomomma.info/").ConfigureAwait(false); - await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` πŸ˜†").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " πŸ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Randjoke(IUserMessage umsg) + public async Task Randjoke(IUserMessage msg) { - var channel = (ITextChannel)umsg.Channel; using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false); - await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` πŸ˜†").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " πŸ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChuckNorris(IUserMessage umsg) + public async Task ChuckNorris(IUserMessage msg) { - var channel = (ITextChannel)umsg.Channel; using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://api.icndb.com/jokes/random/").ConfigureAwait(false); - await channel.SendMessageAsync("`" + JObject.Parse(response)["value"]["joke"].ToString() + "` πŸ˜†").ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(JObject.Parse(response)["value"]["joke"].ToString() + " πŸ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task WowJoke(IUserMessage umsg) + public async Task WowJoke(IUserMessage msg) { - var channel = (ITextChannel)umsg.Channel; - if (!wowJokes.Any()) { + await msg.Channel.SendErrorAsync("Jokes not loaded.").ConfigureAwait(false); + return; } - await channel.SendMessageAsync(wowJokes[new NadekoRandom().Next(0, wowJokes.Count)].ToString()); + var joke = wowJokes[new NadekoRandom().Next(0, wowJokes.Count)]; + await msg.Channel.SendConfirmAsync(joke.Question, joke.Answer).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task MagicItem(IUserMessage umsg) + public async Task MagicItem(IUserMessage msg) { - var channel = (ITextChannel)umsg.Channel; - var rng = new NadekoRandom(); - var item = magicItems[rng.Next(0, magicItems.Count)].ToString(); + if (!wowJokes.Any()) + { + await msg.Channel.SendErrorAsync("MagicItems not loaded.").ConfigureAwait(false); + return; + } + var item = magicItems[new NadekoRandom().Next(0, magicItems.Count)]; - await channel.SendMessageAsync(item).ConfigureAwait(false); + await msg.Channel.SendConfirmAsync("✨" + item.Name, item.Description).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index 50ad53ea..e50f2060 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -1,6 +1,7 @@ ο»Ώusing Discord; using Discord.Commands; using NadekoBot.Attributes; +using NadekoBot.Extensions; using NadekoBot.Services; using Newtonsoft.Json.Linq; using System; @@ -50,23 +51,19 @@ namespace NadekoBot.Modules.Searches $"limit={showCount}") .ConfigureAwait(false))["data"] as JArray; var dataList = data.Distinct(new ChampionNameComparer()).Take(showCount).ToList(); - var sb = new StringBuilder(); - sb.AppendLine($"**Showing {dataList.Count} top banned champions.**"); - sb.AppendLine($"`{trashTalk[new NadekoRandom().Next(0, trashTalk.Length)]}`"); + var eb = new EmbedBuilder().WithColor(NadekoBot.OkColor).WithTitle(Format.Underline($"{dataList.Count} most banned champions")); for (var i = 0; i < dataList.Count; i++) { - if (i % 2 == 0 && i != 0) - sb.AppendLine(); - sb.Append($"`{i + 1}.` **{dataList[i]["name"]}** {dataList[i]["general"]["banRate"]}% "); - //sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)"); + var champ = dataList[i]; + eb.AddField(efb => efb.WithName(champ["name"].ToString()).WithValue(champ["general"]["banRate"] + "%").WithIsInline(true)); } - await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); + await channel.EmbedAsync(eb.Build(), Format.Italics(trashTalk[new NadekoRandom().Next(0, trashTalk.Length)])).ConfigureAwait(false); } } catch (Exception) { - await channel.SendMessageAsync($":anger: `Something went wrong.`").ConfigureAwait(false); + await channel.SendMessageAsync("Something went wrong.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs index 6cd84286..3c48eab0 100644 --- a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs @@ -25,20 +25,11 @@ namespace NadekoBot.Modules.Searches using (var http = new HttpClient(handler)) { - http.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); - string rawJson = ""; - try - { - rawJson = await http.GetStringAsync("https://memegen.link/api/templates/").ConfigureAwait(false); - } - catch (Exception ex) - { - Console.WriteLine(ex); - } + var rawJson = await http.GetStringAsync("https://memegen.link/api/templates/").ConfigureAwait(false); var data = JsonConvert.DeserializeObject>(rawJson) - .Select(kvp => Path.GetFileName(kvp.Value)); + .Select(kvp => Path.GetFileName(kvp.Value)); - await channel.SendTableAsync(data, x => $"{x,-17}", 3); + await channel.SendTableAsync(data, x => $"{x,-17}", 3).ConfigureAwait(false); } } @@ -50,7 +41,8 @@ namespace NadekoBot.Modules.Searches var top = Uri.EscapeDataString(topText.Replace(' ', '-')); var bot = Uri.EscapeDataString(botText.Replace(' ', '-')); - await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg"); + await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg") + .ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/MagicItem.cs b/src/NadekoBot/Modules/Searches/Commands/Models/MagicItem.cs index 53397e8e..8c026894 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/MagicItem.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/MagicItem.cs @@ -4,7 +4,5 @@ { public string Name { get; set; } public string Description { get; set; } - public override string ToString() => - $"✨`{Name}`\n\t*{Description}*"; } } diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/SearchPokemon.cs b/src/NadekoBot/Modules/Searches/Commands/Models/SearchPokemon.cs index be5411d1..b1e24ad5 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/SearchPokemon.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/SearchPokemon.cs @@ -18,9 +18,8 @@ namespace NadekoBot.Modules.Searches.Models public int SPD { get; set; } public int SPE { get; set; } - public override string ToString() => $@" - **HP:** {HP,-4} **ATK:** {ATK,-4} **DEF:** {DEF,-4} - **SPA:** {SPA,-4} **SPD:** {SPD,-4} **SPE:** {SPE,-4}"; + public override string ToString() => $@"**HP:** {HP,-4} **ATK:** {ATK,-4} **DEF:** {DEF,-4} +**SPA:** {SPA,-4} **SPD:** {SPD,-4} **SPE:** {SPE,-4}"; } public int Id { get; set; } public string Species { get; set; } diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index de26d025..58d7dfdc 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Searches [Group] public class OsuCommands { - private static Logger _log; + private static Logger _log { get; } static OsuCommands() { @@ -52,7 +52,7 @@ namespace NadekoBot.Modules.Searches } catch (Exception ex) { - await channel.SendMessageAsync("πŸ’’ Failed retrieving osu signature :\\").ConfigureAwait(false); + await channel.SendErrorAsync("Failed retrieving osu signature.").ConfigureAwait(false); _log.Warn(ex, "Osu command failed"); } } @@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) { - await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); + await channel.SendErrorAsync("An osu! API key is required.").ConfigureAwait(false); return; } @@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Searches } catch (Exception ex) { - await channel.SendMessageAsync("Something went wrong."); + await channel.SendErrorAsync("Something went wrong."); _log.Warn(ex, "Osub command failed"); } } @@ -102,13 +102,13 @@ namespace NadekoBot.Modules.Searches var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) { - await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); + await channel.SendErrorAsync("An osu! API key is required.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(user)) { - await channel.SendMessageAsync("πŸ’’ Please provide a username.").ConfigureAwait(false); + await channel.SendErrorAsync("Please provide a username.").ConfigureAwait(false); return; } using (var http = new HttpClient()) @@ -141,7 +141,7 @@ namespace NadekoBot.Modules.Searches } catch (Exception ex) { - await channel.SendMessageAsync("Something went wrong."); + await channel.SendErrorAsync("Something went wrong."); _log.Warn(ex, "Osu5 command failed"); } diff --git a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs index 11ebee81..2be2d88a 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs @@ -1,6 +1,7 @@ ο»Ώusing Discord; using Discord.Commands; using NadekoBot.Attributes; +using NadekoBot.Extensions; using NadekoBot.Services; using System; using System.Threading.Tasks; @@ -36,7 +37,7 @@ namespace NadekoBot.Modules.Searches { var channel = (ITextChannel)imsg.Channel; - await channel.SendMessageAsync(typesStr) + await channel.SendConfirmAsync(typesStr) .ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index c2750c54..ccf80c0f 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -1,11 +1,13 @@ ο»Ώusing Discord; using Discord.Commands; using NadekoBot.Attributes; +using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Models; using Newtonsoft.Json; using NLog; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Threading.Tasks; namespace NadekoBot.Modules.Searches @@ -15,13 +17,13 @@ namespace NadekoBot.Modules.Searches [Group] public class PokemonSearchCommands { - private static Dictionary pokemons = new Dictionary(); - private static Dictionary pokemonAbilities = new Dictionary(); + private static Dictionary pokemons { get; } = new Dictionary(); + private static Dictionary pokemonAbilities { get; } = new Dictionary(); public const string PokemonAbilitiesFile = "data/pokemon/pokemon_abilities.json"; public const string PokemonListFile = "data/pokemon/pokemon_list.json"; - private static Logger _log; + private static Logger _log { get; } static PokemonSearchCommands() { @@ -52,11 +54,18 @@ namespace NadekoBot.Modules.Searches { if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant()) { - await channel.SendMessageAsync($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}"); + var p = kvp.Value; + await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithTitle(kvp.Key.ToTitleCase()) + .WithDescription(p.BaseStats.ToString()) + .AddField(efb => efb.WithName("Types").WithValue(string.Join(",\n", p.Types)).WithIsInline(true)) + .AddField(efb => efb.WithName("Height/Weight").WithValue($"{p.HeightM}m/{p.WeightKg}kg").WithIsInline(true)) + .AddField(efb => efb.WithName("Abilitities").WithValue(string.Join(",\n", p.Abilities.Select(a => a.Value))).WithIsInline(true)) + .Build()); return; } } - await channel.SendMessageAsync("`No pokemon found.`"); + await channel.SendErrorAsync("No pokemon found."); } [NadekoCommand, Usage, Description, Aliases] @@ -72,11 +81,15 @@ namespace NadekoBot.Modules.Searches { if (kvp.Key.ToUpperInvariant() == ability) { - await channel.SendMessageAsync($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}"); + await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithTitle(kvp.Value.Name) + .WithDescription(kvp.Value.Desc) + .AddField(efb => efb.WithName("Rating").WithValue(kvp.Value.Rating.ToString()).WithIsInline(true)) + .Build()).ConfigureAwait(false); return; } } - await channel.SendMessageAsync("`No ability found.`"); + await channel.SendErrorAsync("No ability found."); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index b8b21bf5..b81626f2 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -91,28 +91,28 @@ namespace NadekoBot.Modules.Searches } await Task.WhenAll(streams.Select(async fs => - { - try - { - var newStatus = await GetStreamStatus(fs).ConfigureAwait(false); - if (FirstPass) - { - return; - } + { + try + { + var newStatus = await GetStreamStatus(fs).ConfigureAwait(false); + if (FirstPass) + { + return; + } - StreamStatus oldStatus; - if (oldCachedStatuses.TryGetValue(newStatus.ApiLink, out oldStatus) && - oldStatus.IsLive != newStatus.IsLive) - { - var server = NadekoBot.Client.GetGuild(fs.GuildId); - var channel = server?.GetTextChannel(fs.ChannelId); - if (channel == null) - return; - try { await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); } catch { } - } - } - catch { } - })); + StreamStatus oldStatus; + if (oldCachedStatuses.TryGetValue(newStatus.ApiLink, out oldStatus) && + oldStatus.IsLive != newStatus.IsLive) + { + var server = NadekoBot.Client.GetGuild(fs.GuildId); + var channel = server?.GetTextChannel(fs.ChannelId); + if (channel == null) + return; + try { await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); } catch { } + } + } + catch { } + })); FirstPass = false; }, null, TimeSpan.Zero, TimeSpan.FromSeconds(60)); @@ -190,40 +190,6 @@ namespace NadekoBot.Modules.Searches return null; } - //[NadekoCommand, Usage, Description, Aliases] - //[RequireContext(ContextType.Guild)] - //public async Task Test(IUserMessage imsg) - //{ - // var channel = (ITextChannel)imsg.Channel; - - // await channel.EmbedAsync(new Discord.API.Embed() - // { - // Title = "Imqtpie", - // Url = "https://twitch.tv/masterkwoth", - // Fields = new[] { - // new Discord.API.EmbedField() - // { - // Name = "Status", - // Value = "Online", - // Inline = true, - // }, - // new Discord.API.EmbedField() - // { - // Name = "Viewers", - // Value = "123123", - // Inline = true - // }, - // new Discord.API.EmbedField() - // { - // Name = "Platform", - // Value = "Twitch", - // Inline = true - // }, - // }, - // Color = NadekoBot.OkColor - // }); - //} - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequirePermission(GuildPermission.ManageMessages)] @@ -262,7 +228,7 @@ namespace NadekoBot.Modules.Searches if (!streams.Any()) { - await channel.SendMessageAsync("You are not following any streams on this server.").ConfigureAwait(false); + await channel.SendConfirmAsync("You are not following any streams on this server.").ConfigureAwait(false); return; } @@ -271,7 +237,7 @@ namespace NadekoBot.Modules.Searches return $"`{snc.Username}`'s stream on **{channel.Guild.GetTextChannel(snc.ChannelId)?.Name}** channel. 【`{snc.Type.ToString()}`】"; })); - await channel.SendMessageAsync($"You are following **{streams.Count()}** streams on this server.\n\n" + text).ConfigureAwait(false); + await channel.SendConfirmAsync($"You are following **{streams.Count()}** streams on this server.\n\n" + text).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -300,10 +266,10 @@ namespace NadekoBot.Modules.Searches } if (!removed) { - await channel.SendMessageAsync("❎ No such stream.").ConfigureAwait(false); + await channel.SendErrorAsync("No such stream.").ConfigureAwait(false); return; } - await channel.SendMessageAsync($"πŸ—‘ Removed `{username}`'s stream ({type}) from notifications.").ConfigureAwait(false); + await channel.SendConfirmAsync($"Removed `{username}`'s stream ({type}) from notifications.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -324,22 +290,22 @@ namespace NadekoBot.Modules.Searches })); if (streamStatus.IsLive) { - await channel.SendMessageAsync($"`Streamer {username} is online with {streamStatus.Views} viewers.`"); + await channel.SendConfirmAsync($"Streamer {username} is online with {streamStatus.Views} viewers."); } else { - await channel.SendMessageAsync($"`Streamer {username} is offline.`"); + await channel.SendConfirmAsync($"Streamer {username} is offline."); } } catch { - await channel.SendMessageAsync("No channel found."); + await channel.SendErrorAsync("No channel found."); } } private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type) { - username = username.Trim(); + username = username.ToLowerInvariant().Trim(); var fs = new FollowedStream { GuildId = channel.Guild.Id, @@ -355,7 +321,7 @@ namespace NadekoBot.Modules.Searches } catch { - await channel.SendMessageAsync("πŸ’’ Stream probably doesn't exist.").ConfigureAwait(false); + await channel.SendErrorAsync("Stream probably doesn't exist.").ConfigureAwait(false); return; } @@ -366,9 +332,7 @@ namespace NadekoBot.Modules.Searches .Add(fs); await uow.CompleteAsync().ConfigureAwait(false); } - - var msg = $"πŸ†— I will notify this channel when status changes."; - await channel.EmbedAsync(fs.GetEmbed(status).Build(), msg).ConfigureAwait(false); + await channel.EmbedAsync(fs.GetEmbed(status).Build(), $"πŸ†— I will notify this channel when status changes.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index fe711303..943e152e 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -75,12 +75,12 @@ namespace NadekoBot.Modules.Searches { await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); var translation = await TranslateInternal(umsg, langs, text); - await channel.SendMessageAsync(translation).ConfigureAwait(false); + await channel.SendConfirmAsync(translation).ConfigureAwait(false); } catch { - await channel.SendMessageAsync("Bad input format, or something went wrong...").ConfigureAwait(false); + await channel.SendErrorAsync("Bad input format, or something went wrong...").ConfigureAwait(false); } } @@ -114,19 +114,19 @@ namespace NadekoBot.Modules.Searches if (autoDelete == AutoDeleteAutoTranslate.Del) { TranslatedChannels.AddOrUpdate(channel.Id, true, (key, val) => true); - try { await channel.SendMessageAsync("`Started automatic translation of messages on this channel. User messages will be auto-deleted.`").ConfigureAwait(false); } catch { } + try { await channel.SendConfirmAsync("Started automatic translation of messages on this channel. User messages will be auto-deleted.").ConfigureAwait(false); } catch { } return; } bool throwaway; if (TranslatedChannels.TryRemove(channel.Id, out throwaway)) { - try { await channel.SendMessageAsync("`Stopped automatic translation of messages on this channel.`").ConfigureAwait(false); } catch { } + try { await channel.SendConfirmAsync("Stopped automatic translation of messages on this channel.").ConfigureAwait(false); } catch { } return; } else if (TranslatedChannels.TryAdd(channel.Id, autoDelete == AutoDeleteAutoTranslate.Del)) { - try { await channel.SendMessageAsync("`Started automatic translation of messages on this channel.`").ConfigureAwait(false); } catch { } + try { await channel.SendConfirmAsync("Started automatic translation of messages on this channel.").ConfigureAwait(false); } catch { } } } @@ -145,7 +145,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(langs)) { if (UserLanguages.TryRemove(ucp, out langs)) - await channel.SendMessageAsync($"{msg.Author.Mention}'s auto-translate language has been removed.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{msg.Author.Mention}'s auto-translate language has been removed.").ConfigureAwait(false); return; } @@ -157,13 +157,13 @@ namespace NadekoBot.Modules.Searches if (!GoogleTranslator.Instance.Languages.Contains(from) || !GoogleTranslator.Instance.Languages.Contains(to)) { - try { await channel.SendMessageAsync("`Invalid source and/or target Language.`").ConfigureAwait(false); } catch { } + try { await channel.SendErrorAsync("Invalid source and/or target language.").ConfigureAwait(false); } catch { } return; } UserLanguages.AddOrUpdate(ucp, langs, (key, val) => langs); - await channel.SendMessageAsync(":ok:").ConfigureAwait(false); + await channel.SendConfirmAsync($"Your auto-translate language has been set to {from}>{to}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs b/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs index 4e901ea6..f5700698 100644 --- a/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs @@ -1,6 +1,7 @@ ο»Ώusing Discord; using Discord.Commands; using NadekoBot.Attributes; +using NadekoBot.Extensions; using NadekoBot.Services; using Newtonsoft.Json; using System.Net.Http; @@ -55,12 +56,17 @@ namespace NadekoBot.Modules.Searches var res = await http.GetStringAsync($"{xkcdUrl}/{num}/info.0.json").ConfigureAwait(false); var comic = JsonConvert.DeserializeObject(res); - var sent = await channel.SendMessageAsync($"{msg.Author.Mention} " + comic.ToString()) + var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithImage(eib => eib.WithUrl(comic.ImageLink)) + .WithAuthor(eab => eab.WithName(comic.Title).WithUrl($"{xkcdUrl}/{num}").WithIconUrl("http://xkcd.com/s/919f27.ico")) + .AddField(efb => efb.WithName("Comic#").WithValue(comic.Num.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName("Date").WithValue($"{comic.Month}/{comic.Year}").WithIsInline(true)); + var sent = await channel.EmbedAsync(embed.Build()) .ConfigureAwait(false); await Task.Delay(10000).ConfigureAwait(false); - await sent.ModifyAsync(m => m.Content = sent.Content + $"\n`Alt:` {comic.Alt}"); + await sent.ModifyAsync(m => m.Embed = embed.AddField(efb => efb.WithName("Alt").WithValue(comic.Alt.ToString()).WithIsInline(false)).Build()); } } } diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 229a0887..a3f5eb0e 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -199,7 +199,7 @@ namespace NadekoBot.Modules.Searches if (shortened == arg) { - await msg.Channel.SendErrorAsync("Failed to shorten that url."); + await msg.Channel.SendErrorAsync("Failed to shorten that url.").ConfigureAwait(false); } await msg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) @@ -207,7 +207,8 @@ namespace NadekoBot.Modules.Searches .WithValue($"<{arg}>")) .AddField(efb => efb.WithName("Short Url") .WithValue($"<{shortened}>")) - .Build()); + .Build()) + .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -286,7 +287,7 @@ namespace NadekoBot.Modules.Searches if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendErrorAsync ("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); + await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index e75f7c72..3468a15f 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Utility { public static List Units { get; set; } = new List(); - private static Logger _log; + private static Logger _log { get; } private static Timer _timer; private static TimeSpan updateInterval = new TimeSpan(12, 0, 0); From 85e69855839a30cab2ea195fe836debb89da062f Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 9 Dec 2016 04:24:19 +0100 Subject: [PATCH 12/12] Updated commandlist --- docs/Commands List.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/docs/Commands List.md b/docs/Commands List.md index 3b38e04f..bf31a9d1 100644 --- a/docs/Commands List.md +++ b/docs/Commands List.md @@ -10,6 +10,7 @@ You can support the project on patreon: or paypa - [Music](#music) - [NSFW](#nsfw) - [Permissions](#permissions) +- [Pokemon](#pokemon) - [Searches](#searches) - [Utility](#utility) @@ -268,6 +269,17 @@ Command and aliases | Description | Usage ###### [Back to TOC](#table-of-contents) +### Pokemon +Command and aliases | Description | Usage +----------------|--------------|------- +`>attack` | Attacks a target with the given move. Use `>movelist` to see a list of moves your type can use. | `>attack "vine whip" @someguy` +`>movelist` `>ml` | Lists the moves you are able to use | `>ml` +`>heal` | Heals someone. Revives those who fainted. Costs a NadekoFlower | `>heal @someone` +`>type` | Get the poketype of the target. | `>type @someone` +`>settype` | Set your poketype. Costs a NadekoFlower. Provide no arguments to see a list of available types. | `>settype fire` or `>settype` + +###### [Back to TOC](#table-of-contents) + ### Searches Command and aliases | Description | Usage ----------------|--------------|------- @@ -283,6 +295,7 @@ Command and aliases | Description | Usage `~google` `~g` | Get a google search link for some terms. | `~google query` `~magicthegathering` `~mtg` | Searches for a Magic The Gathering card. | `~magicthegathering about face` or `~mtg about face` `~hearthstone` `~hs` | Searches for a Hearthstone card and shows its image. Takes a while to complete. | `~hs Ysera` +`~yodify` `~yoda` | Translates your normal sentences into Yoda styled sentences! | ~yodify I was once an adventurer like you` or `~yoda my feelings hurt` `~urbandict` `~ud` | Searches Urban Dictionary for a word. | `~ud Pineapple` `~#` | Searches Tagdef.com for a hashtag. | `~# ff` `~catfact` | Shows a random catfact from | `~catfact` @@ -293,8 +306,6 @@ Command and aliases | Description | Usage `~color` `~clr` | Shows you what color corresponds to that hex. | `~clr 00ff00` `~videocall` | Creates a private video call link for you and other mentioned people. The link is sent to mentioned people via a private message. | `~videocall "@SomeGuy"` `~avatar` `~av` | Shows a mentioned person's avatar. | `~av "@SomeGuy"` -`~bfonline` `~bfo` | Gives you online players for BF3 and BF4 | `~bfo bf3` or `~bfo bf4` -`~bfuser` `~bfu` | Gives you back a battlefield user's stats. | `~bfu platform game user` `~wikia` | Gives you back a wikia link | `~wikia mtg Vigilance` or `~wikia mlp Dashy` `~minecraftping` `~mcping` | Pings a minecraft server. | `~mcping 127.0.0.1:25565` `~minecraftquery` `~mcq` | Finds information about a minecraft server. | `~mcq server:ip` @@ -319,7 +330,7 @@ Command and aliases | Description | Usage `~twitch` `~tw` | Notifies this channel when a certain user starts streaming. **Requires ManageMessages server permission.** | `~twitch SomeStreamer` `~beam` `~bm` | Notifies this channel when a certain user starts streaming. **Requires ManageMessages server permission.** | `~beam SomeStreamer` `~liststreams` `~ls` | Lists all streams you are following on this server. | `~ls` -`~removestream` `~rms` | Removes notifications of a certain streamer on this channel. **Requires ManageMessages server permission.** | `~rms SomeGuy` +`~removestream` `~rms` | Removes notifications of a certain streamer from a certain platform on this channel. **Requires ManageMessages server permission.** | `~rms Twitch SomeGuy` or `~rms Beam SomeOtherGuy` `~checkstream` `~cs` | Checks if a user is online on a certain streaming platform. | `~cs twitch MyFavStreamer` `~translate` `~trans` | Translates from>to text. From the given language to the destination language. | `~trans en>fr Hello` `~autotrans` `~at` | Starts automatic translation of all messages by users who set their `~atl` in this channel. You can set "del" argument to automatically delete all translated user messages. **Requires Administrator server permission.** **Bot Owner only.** | `~at` or `~at del` @@ -345,7 +356,6 @@ Command and aliases | Description | Usage `.listservers` | Lists servers the bot is on with some basic info. 15 per page. **Bot Owner only.** | `.listservers 3` `.calculate` `.calc` | Evaluate a mathematical expression. | `.calc 1+1` `.calcops` | Shows all available operations in .calc command | `.calcops` -`.togethertube` `.totube` | Creates a new room on and shows the link in the chat. | `.totube` `.serverinfo` `.sinfo` | Shows info about the server the bot is on. If no channel is supplied, it defaults to current one. | `.sinfo Some Server` `.channelinfo` `.cinfo` | Shows info about the channel. If no channel is supplied, it defaults to current one. | `.cinfo #some-channel` `.userinfo` `.uinfo` | Shows info about the user. If no user is supplied, it defaults a user running the command. | `.uinfo @SomeUser`