diff --git a/src/NadekoBot/Attributes/LocalizedCommand.cs b/src/NadekoBot/Attributes/LocalizedCommand.cs index 8c23932a..b145c820 100644 --- a/src/NadekoBot/Attributes/LocalizedCommand.cs +++ b/src/NadekoBot/Attributes/LocalizedCommand.cs @@ -10,7 +10,7 @@ namespace NadekoBot.Attributes { public class LocalizedCommandAttribute : CommandAttribute { - public LocalizedCommandAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant() + "_text")) + public LocalizedCommandAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant() + "_text")) { } diff --git a/src/NadekoBot/Attributes/LocalizedDescription.cs b/src/NadekoBot/Attributes/LocalizedDescription.cs index 116efd88..65aaa802 100644 --- a/src/NadekoBot/Attributes/LocalizedDescription.cs +++ b/src/NadekoBot/Attributes/LocalizedDescription.cs @@ -10,7 +10,7 @@ namespace NadekoBot.Attributes { public class LocalizedDescriptionAttribute : DescriptionAttribute { - public LocalizedDescriptionAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant()+"_description")) + public LocalizedDescriptionAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant()+"_description")) { } diff --git a/src/NadekoBot/Attributes/LocalizedSummary.cs b/src/NadekoBot/Attributes/LocalizedSummary.cs index d24ca42d..d2a7f10f 100644 --- a/src/NadekoBot/Attributes/LocalizedSummary.cs +++ b/src/NadekoBot/Attributes/LocalizedSummary.cs @@ -10,7 +10,7 @@ namespace NadekoBot.Attributes { public class LocalizedSummaryAttribute : SummaryAttribute { - public LocalizedSummaryAttribute([CallerMemberName] string memberName="") : base(Localization.LoadString(memberName.ToLowerInvariant() + "_summary")) + public LocalizedSummaryAttribute([CallerMemberName] string memberName="") : base(Localization.LoadCommandString(memberName.ToLowerInvariant() + "_summary")) { } diff --git a/src/NadekoBot/Classes/Extensions.cs b/src/NadekoBot/Classes/Extensions.cs deleted file mode 100644 index 098e4732..00000000 --- a/src/NadekoBot/Classes/Extensions.cs +++ /dev/null @@ -1,378 +0,0 @@ -using Discord; -using Discord.Commands; -using NadekoBot.Classes; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Net; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Extensions -{ - public static class Extensions - { - private static Random rng = new Random(); - - public static string Scramble(this string word) - { - - var letters = word.ToArray(); - var count = 0; - for (var i = 0; i < letters.Length; i++) - { - if (letters[i] == ' ') - continue; - - count++; - if (count <= letters.Length / 5) - continue; - - if (count % 3 == 0) - continue; - - if (letters[i] != ' ') - letters[i] = '_'; - } - return "`" + string.Join(" ", letters) + "`"; - } - public static string TrimTo(this string str, int num, bool hideDots = false) - { - if (num < 0) - throw new ArgumentOutOfRangeException(nameof(num), "TrimTo argument cannot be less than 0"); - if (num == 0) - return string.Empty; - if (num <= 3) - return string.Concat(str.Select(c => '.')); - if (str.Length < num) - return str; - return string.Concat(str.Take(num - 3)) + (hideDots ? "" : "..."); - } - /// - /// Removes trailing S or ES (if specified) on the given string if the num is 1 - /// - /// - /// - /// - /// String with the correct singular/plural form - public static string SnPl(this string str, int? num, bool es = false) - { - if (str == null) - throw new ArgumentNullException(nameof(str)); - if (num == null) - throw new ArgumentNullException(nameof(num)); - return num == 1 ? str.Remove(str.Length - 1, es ? 2 : 1) : str; - } - - /// - /// Sends a message to the channel from which this command is called. - /// - /// EventArg - /// Message to be sent - /// - public static async Task Send(this CommandEventArgs e, string message) - => await e.Channel.SendMessage(message).ConfigureAwait(false); - - /// - /// Sends a message to the channel from which MessageEventArg came. - /// - /// EventArg - /// Message to be sent - /// - public static async Task Send(this MessageEventArgs e, string message) - { - if (string.IsNullOrWhiteSpace(message)) - return; - await e.Channel.SendMessage(message).ConfigureAwait(false); - } - - /// - /// Sends a message to this channel. - /// - /// - /// - /// - public static async Task Send(this Channel c, string message) - { - await c.SendMessage(message).ConfigureAwait(false); - } - - /// - /// Sends a private message to this user. - /// - /// - /// - /// - public static async Task Send(this User u, string message) - { - await u.SendMessage(message).ConfigureAwait(false); - } - - /// - /// Replies to a user who invoked this command, message start with that user's mention. - /// - /// - /// - /// - public static async Task Reply(this CommandEventArgs e, string message) - { - await e.Channel.SendMessage(e.User.Mention + " " + message).ConfigureAwait(false); - } - - /// - /// Replies to a user who invoked this command, message start with that user's mention. - /// - /// - /// - /// - public static async Task Reply(this MessageEventArgs e, string message) - { - await e.Channel.SendMessage(e.User.Mention + " " + message).ConfigureAwait(false); - } - - /// - /// Randomizes element order in a list - /// - /// - /// - public static IList Shuffle(this IList list) - { - - // Thanks to @Joe4Evr for finding a bug in the old version of the shuffle - var provider = new RNGCryptoServiceProvider(); - var n = list.Count; - while (n > 1) - { - var box = new byte[(n / Byte.MaxValue) + 1]; - int boxSum; - do - { - provider.GetBytes(box); - boxSum = box.Sum(b => b); - } - while (!(boxSum < n * ((Byte.MaxValue * box.Length) / n))); - var k = (boxSum % n); - n--; - var value = list[k]; - list[k] = list[n]; - list[n] = value; - } - return list; - } - - /// - /// Shortens a string URL - /// - /// - /// - /// - public static async Task ShortenUrl(this string str) - { - try - { - var result = await SearchHelper.ShortenUrl(str).ConfigureAwait(false); - return result; - } - catch (WebException ex) - { - throw new InvalidOperationException("You must enable URL shortner in google developers console.", ex); - } - } - - public static string GetOnPage(this IEnumerable source, int pageIndex, int itemsPerPage = 5) - { - var items = source.Skip(pageIndex * itemsPerPage).Take(itemsPerPage); - if (!items.Any()) - { - return $"No items on page {pageIndex + 1}."; - } - var sb = new StringBuilder($"---page {pageIndex + 1} --\n"); - var itemsDC = items as IEnumerable>>; - var itemsDS = items as IEnumerable>; - if (itemsDC != null) - { - foreach (var item in itemsDC) - { - sb.Append($"{ Format.Code(item.Key)}\n"); - int i = 1; - var last = item.Value.Last(); - foreach (var value in item.Value) - { - if (last != value) - sb.AppendLine(" `├" + i++ + "─`" + Format.Bold(value)); - else - sb.AppendLine(" `└" + i++ + "─`" + Format.Bold(value)); - } - - } - } - else if (itemsDS != null) - { - foreach (var item in itemsDS) - { - sb.Append($"{ Format.Code(item.Key)}\n"); - sb.AppendLine(" `└─`" + Format.Bold(item.Value)); - } - - } - else - { - foreach (var item in items) - { - sb.Append($"{ Format.Code(item.ToString())} \n"); - } - } - - return sb.ToString(); - } - /// - /// Gets the program runtime - /// - /// - /// - /// - public static string GetRuntime(this DiscordClient c) => ".Net Framework 4.5.2"; - - public static string Matrix(this string s) - => - string.Concat(s.Select(c => c.ToString() + " ̵̢̬̜͉̞̭̖̰͋̉̎ͬ̔̇̌̀".TrimTo(rng.Next(0, 12), true))); - //.Replace("`", ""); - - public static void ForEach(this IEnumerable source, Action action) - { - foreach (var element in source) - { - action(element); - } - } - - //http://www.dotnetperls.com/levenshtein - public static int LevenshteinDistance(this string s, string t) - { - var n = s.Length; - var m = t.Length; - var d = new int[n + 1, m + 1]; - - // Step 1 - if (n == 0) - { - return m; - } - - if (m == 0) - { - return n; - } - - // Step 2 - for (var i = 0; i <= n; d[i, 0] = i++) - { - } - - for (var j = 0; j <= m; d[0, j] = j++) - { - } - - // Step 3 - for (var i = 1; i <= n; i++) - { - //Step 4 - for (var j = 1; j <= m; j++) - { - // Step 5 - var cost = (t[j - 1] == s[i - 1]) ? 0 : 1; - - // Step 6 - d[i, j] = Math.Min( - Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), - d[i - 1, j - 1] + cost); - } - } - // Step 7 - return d[n, m]; - } - - public static int KiB(this int value) => value * 1024; - public static int KB(this int value) => value * 1000; - - public static int MiB(this int value) => value.KiB() * 1024; - public static int MB(this int value) => value.KB() * 1000; - - public static int GiB(this int value) => value.MiB() * 1024; - public static int GB(this int value) => value.MB() * 1000; - - public static ulong KiB(this ulong value) => value * 1024; - public static ulong KB(this ulong value) => value * 1000; - - public static ulong MiB(this ulong value) => value.KiB() * 1024; - public static ulong MB(this ulong value) => value.KB() * 1000; - - public static ulong GiB(this ulong value) => value.MiB() * 1024; - public static ulong GB(this ulong value) => value.MB() * 1000; - - public static Stream ToStream(this Image img, System.Drawing.Imaging.ImageFormat format = null) - { - if (format == null) - format = System.Drawing.Imaging.ImageFormat.Jpeg; - var stream = new MemoryStream(); - img.Save(stream, format); - stream.Position = 0; - return stream; - } - - /// - /// Merges Images into 1 Image and returns a bitmap. - /// - /// The Images you want to merge. - /// Merged bitmap - public static Bitmap Merge(this IEnumerable images, int reverseScaleFactor = 1) - { - var imageArray = images as Image[] ?? images.ToArray(); - if (!imageArray.Any()) return null; - var width = imageArray.Sum(i => i.Width); - var height = imageArray.First().Height; - var bitmap = new Bitmap(width / reverseScaleFactor, height / reverseScaleFactor); - var r = new Random(); - var offsetx = 0; - foreach (var img in imageArray) - { - var bm = new Bitmap(img); - for (var w = 0; w < img.Width; w++) - { - for (var h = 0; h < bitmap.Height; h++) - { - bitmap.SetPixel(w / reverseScaleFactor + offsetx, h, bm.GetPixel(w, h * reverseScaleFactor)); - } - } - offsetx += img.Width / reverseScaleFactor; - } - return bitmap; - } - - /// - /// Merges Images into 1 Image and returns a bitmap asynchronously. - /// - /// The Images you want to merge. - /// - /// Merged bitmap - public static async Task MergeAsync(this IEnumerable images, int reverseScaleFactor = 1) => - await Task.Run(() => images.Merge(reverseScaleFactor)).ConfigureAwait(false); - - public static string Unmention(this string str) => str.Replace("@", "ම"); - - public static Stream ToStream(this string str) - { - var sw = new StreamWriter(new MemoryStream()); - sw.Write(str); - sw.Flush(); - sw.BaseStream.Position = 0; - return sw.BaseStream; - } - - public static double UnixTimestamp(this DateTime dt) => dt.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds; - - } -} diff --git a/src/NadekoBot/Classes/SearchHelper.cs b/src/NadekoBot/Classes/SearchHelper.cs index a0a59e9b..3b30a205 100644 --- a/src/NadekoBot/Classes/SearchHelper.cs +++ b/src/NadekoBot/Classes/SearchHelper.cs @@ -251,91 +251,7 @@ namespace NadekoBot.Classes } - public static async Task GetDanbooruImageLink(string tag) - { - var rng = new Random(); - - if (tag == "loli") //loli doesn't work for some reason atm - tag = "flat_chest"; - - var link = $"http://danbooru.donmai.us/posts?" + - $"page={rng.Next(0, 15)}"; - if (!string.IsNullOrWhiteSpace(tag)) - link += $"&tags={tag.Replace(" ", "_")}"; - - var webpage = await GetResponseStringAsync(link).ConfigureAwait(false); - var matches = Regex.Matches(webpage, "data-large-file-url=\"(?.*?)\""); - - if (matches.Count == 0) - return null; - return $"http://danbooru.donmai.us" + - $"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}"; - } - - public static async Task GetGelbooruImageLink(string tag) - { - var headers = new Dictionary() { - {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, - {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, - }; - var url = - $"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; - var webpage = await GetResponseStringAsync(url, headers).ConfigureAwait(false); - var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); - if (matches.Count == 0) - return null; - var rng = new Random(); - var match = matches[rng.Next(0, matches.Count)]; - return matches[rng.Next(0, matches.Count)].Groups["url"].Value; - } - - public static async Task GetSafebooruImageLink(string tag) - { - var rng = new Random(); - var url = - $"http://safebooru.org/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; - var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); - var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); - if (matches.Count == 0) - return null; - var match = matches[rng.Next(0, matches.Count)]; - return matches[rng.Next(0, matches.Count)].Groups["url"].Value; - } - - public static async Task GetRule34ImageLink(string tag) - { - var rng = new Random(); - var url = - $"http://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; - var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); - var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); - if (matches.Count == 0) - return null; - var match = matches[rng.Next(0, matches.Count)]; - return "http:" + matches[rng.Next(0, matches.Count)].Groups["url"].Value; - } - - - internal static async Task GetE621ImageLink(string tags) - { - try - { - var headers = new Dictionary() { - {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, - {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, - }; - var data = await GetResponseStreamAsync( - "http://e621.net/post/index.xml?tags=" + Uri.EscapeUriString(tags) + "%20order:random&limit=1", - headers); - var doc = XDocument.Load(data); - return doc.Descendants("file_url").FirstOrDefault().Value; - } - catch (Exception ex) - { - Console.WriteLine("Error in e621 search: \n" + ex); - return "Error, do you have too many tags?"; - } - } + public static async Task ShortenUrl(string url) { diff --git a/src/NadekoBot/_Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs similarity index 84% rename from src/NadekoBot/_Modules/ClashOfClans/ClashOfClans.cs rename to src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 1ae491ad..f6949ca8 100644 --- a/src/NadekoBot/_Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using Discord; +using Newtonsoft.Json; using System; using System.Linq; using System.Text; @@ -14,7 +15,7 @@ namespace NadekoBot.Classes.ClashOfClans { Started, Ended, Created } - [System.Serializable] + internal class Caller { public string CallUser { get; set; } @@ -62,7 +63,7 @@ namespace NadekoBot.Classes.ClashOfClans public ulong ChannelId { get; set; } [JsonIgnore] - public Discord.Channel Channel { get; internal set; } + public ITextChannel Channel { get; internal set; } /// /// This init is purely for the deserialization @@ -76,7 +77,15 @@ namespace NadekoBot.Classes.ClashOfClans this.Bases = new Caller[size]; this.ServerId = serverId; this.ChannelId = channelId; - this.Channel = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id == serverId)?.TextChannels.FirstOrDefault(c => c.Id == channelId); + this.Channel = NadekoBot.Client.GetGuildsAsync() //nice api you got here volt, + .GetAwaiter() //especially like how getguildsasync isn't async at all internally. + .GetResult() //But hey, lib has to be async kek + .FirstOrDefault(s => s.Id == serverId)? // srsly + .GetChannelsAsync() //wtf is this + .GetAwaiter() // oh i know, its the implementation detail + .GetResult() // and makes library look consistent + .FirstOrDefault(c => c.Id == channelId) // its not common sense to make library work like this. + as ITextChannel; // oh and don't forget to cast it to this arbitrary bullshit } internal void End() diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClansModule.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClansModule.cs new file mode 100644 index 00000000..2ea71a2d --- /dev/null +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClansModule.cs @@ -0,0 +1,289 @@ +using Discord.Commands; +using NadekoBot.Classes.ClashOfClans; +using Newtonsoft.Json; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Discord; +using NadekoBot.Services; +using NadekoBot.Attributes; + +namespace NadekoBot.Modules.ClashOfClans +{ + [Module(",",AppendSpace = false)] + internal class ClashOfClansModule : DiscordModule + { + public static ConcurrentDictionary> ClashWars { get; set; } = new ConcurrentDictionary>(); + + private readonly object writeLock = new object(); + + public ClashOfClansModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client) + { + } + + private static async Task CheckWar(TimeSpan callExpire, ClashWar war) + { + var Bases = war.Bases; + for (var i = 0; i < Bases.Length; i++) + { + if (Bases[i] == null) continue; + if (!Bases[i].BaseDestroyed && DateTime.UtcNow - Bases[i].TimeAdded >= callExpire) + { + await war.Channel.SendMessageAsync($"❗🔰**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false); + Bases[i] = null; + } + } + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task CreateWar(IMessage imsg, int size, [Remainder] string enemyClan) + { + var channel = imsg.Channel as IGuildChannel; + + if (!(imsg.Author as IGuildUser).GuildPermissions.ManageChannels) + return; + + if (string.IsNullOrWhiteSpace(enemyClan)) + return; + + if (size < 10 || size > 50 || size % 5 != 0) + { + await imsg.Channel.SendMessageAsync("💢🔰 Not a Valid war size").ConfigureAwait(false); + return; + } + List wars; + if (!ClashWars.TryGetValue(channel.Guild.Id, out wars)) + { + wars = new List(); + if (!ClashWars.TryAdd(channel.Guild.Id, wars)) + return; + } + + + var cw = new ClashWar(enemyClan, size, channel.Guild.Id, imsg.Channel.Id); + //cw.Start(); + + wars.Add(cw); + await imsg.Channel.SendMessageAsync($"❗🔰**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task StartWar(IMessage imsg, [Remainder] string number) + { + var channel = imsg.Channel as IGuildChannel; + + int num = 0; + int.TryParse(number, out num); + + var warsInfo = GetWarInfo(imsg, num); + if (warsInfo == null) + { + await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false); + return; + } + var war = warsInfo.Item1[warsInfo.Item2]; + try + { + war.Start(); + await imsg.Channel.SendMessageAsync($"🔰**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false); + } + catch + { + await imsg.Channel.SendMessageAsync($"🔰**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false); + } + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ListWar(IMessage imsg, [Remainder] string number) + { + var channel = imsg.Channel as IGuildChannel; + + // if number is null, print all wars in a short way + if (string.IsNullOrWhiteSpace(number)) + { + //check if there are any wars + List wars = null; + ClashWars.TryGetValue(channel.Guild.Id, out wars); + if (wars == null || wars.Count == 0) + { + await imsg.Channel.SendMessageAsync("🔰 **No active wars.**").ConfigureAwait(false); + return; + } + + var sb = new StringBuilder(); + sb.AppendLine("🔰 **LIST OF ACTIVE WARS**"); + sb.AppendLine("**-------------------------**"); + for (var i = 0; i < wars.Count; i++) + { + sb.AppendLine($"**#{i + 1}.** `Enemy:` **{wars[i].EnemyClan}**"); + sb.AppendLine($"\t\t`Size:` **{wars[i].Size} v {wars[i].Size}**"); + sb.AppendLine("**-------------------------**"); + } + await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); + return; + + } + var num = 0; + int.TryParse(number, out num); + //if number is not null, print the war needed + var warsInfo = GetWarInfo(imsg, num); + if (warsInfo == null) + { + await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false); + return; + } + await imsg.Channel.SendMessageAsync(warsInfo.Item1[warsInfo.Item2].ToString()).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Claim(IMessage imsg, int number, int baseNumber, [Remainder] string other_name) + { + var channel = imsg.Channel as IGuildChannel; + var warsInfo = GetWarInfo(imsg, number); + if (warsInfo == null || warsInfo.Item1.Count == 0) + { + await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false); + return; + } + var usr = + string.IsNullOrWhiteSpace(other_name) ? + imsg.Author.Username : + other_name; + try + { + var war = warsInfo.Item1[warsInfo.Item2]; + war.Call(usr, baseNumber - 1); + await imsg.Channel.SendMessageAsync($"🔰**{usr}** claimed a base #{baseNumber} for a war against {war.ShortPrint()}").ConfigureAwait(false); + } + catch (Exception ex) + { + await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false); + } + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ClaimFinish1(IMessage imsg, int number, int baseNumber, [Remainder] string other_name) + { + var channel = imsg.Channel as IGuildChannel; + await FinishClaim(imsg, number, baseNumber, other_name, 1); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ClaimFinish2(IMessage imsg, int number, int baseNumber, [Remainder] string other_name) + { + var channel = imsg.Channel as IGuildChannel; + await FinishClaim(imsg, number, baseNumber, other_name, 2); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ClaimFinish(IMessage imsg, int number, int baseNumber, [Remainder] string other_name) + { + var channel = imsg.Channel as IGuildChannel; + await FinishClaim(imsg, number, baseNumber, other_name); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task EndWar(IMessage imsg, int number) + { + var channel = imsg.Channel as IGuildChannel; + + var warsInfo = GetWarInfo(imsg,number); + if (warsInfo == null) + { + await imsg.Channel.SendMessageAsync("💢🔰 That war does not exist.").ConfigureAwait(false); + return; + } + warsInfo.Item1[warsInfo.Item2].End(); + await imsg.Channel.SendMessageAsync($"❗🔰**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false); + + var size = warsInfo.Item1[warsInfo.Item2].Size; + warsInfo.Item1.RemoveAt(warsInfo.Item2); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Unclaim(IMessage imsg, int number, [Remainder] string otherName) + { + var channel = imsg.Channel as IGuildChannel; + + var warsInfo = GetWarInfo(imsg, number); + if (warsInfo == null || warsInfo.Item1.Count == 0) + { + await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false); + return; + } + var usr = + string.IsNullOrWhiteSpace(otherName) ? + imsg.Author.Username : + otherName; + try + { + var war = warsInfo.Item1[warsInfo.Item2]; + var baseNumber = war.Uncall(usr); + await imsg.Channel.SendMessageAsync($"🔰 @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false); + } + catch (Exception ex) + { + await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false); + } + } + + private async Task FinishClaim(IMessage imsg, int number, int baseNumber, [Remainder] string other_name, int stars = 3) + { + var channel = imsg.Channel as IGuildChannel; + var warInfo = GetWarInfo(imsg, number); + if (warInfo == null || warInfo.Item1.Count == 0) + { + await imsg.Channel.SendMessageAsync("💢🔰 **That war does not exist.**").ConfigureAwait(false); + return; + } + var usr = + string.IsNullOrWhiteSpace(other_name) ? + imsg.Author.Username : + other_name; + + var war = warInfo.Item1[warInfo.Item2]; + try + { + var baseNum = war.FinishClaim(usr, stars); + await imsg.Channel.SendMessageAsync($"❗🔰{imsg.Author.Mention} **DESTROYED** a base #{baseNum + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); + } + catch (Exception ex) + { + await imsg.Channel.SendMessageAsync($"💢🔰 {ex.Message}").ConfigureAwait(false); + } + } + + private static Tuple, int> GetWarInfo(IMessage imsg, int num) + { + var channel = imsg.Channel as IGuildChannel; + //check if there are any wars + List wars = null; + ClashWars.TryGetValue(channel.Guild.Id, out wars); + if (wars == null || wars.Count == 0) + { + return null; + } + // get the number of the war + else if (num < 1 || num > wars.Count) + { + return null; + } + num -= 1; + //get the actual war + return new Tuple, int>(wars, num); + } + } +} diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs new file mode 100644 index 00000000..aeac5d11 --- /dev/null +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -0,0 +1,26 @@ +using Discord; +using Discord.Commands; +using NadekoBot.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Modules +{ + public class DiscordModule + { + protected ILocalization _l; + protected CommandService _commands; + protected IBotConfiguration _config; + protected IDiscordClient _client; + + public DiscordModule(ILocalization loc, CommandService cmds, IBotConfiguration config,IDiscordClient client) + { + _l = loc; + _commands = cmds; + _config = config; + _client = client; + } + } +} diff --git a/src/NadekoBot/Modules/NSFW/NSFWModule.cs b/src/NadekoBot/Modules/NSFW/NSFWModule.cs new file mode 100644 index 00000000..46234cc4 --- /dev/null +++ b/src/NadekoBot/Modules/NSFW/NSFWModule.cs @@ -0,0 +1,237 @@ +using Discord; +using Discord.Commands; +using NadekoBot.Attributes; +using Newtonsoft.Json.Linq; +using System; +using System.Linq; +using System.Threading.Tasks; +using NadekoBot.Services; +using System.Net.Http; +using System.Text.RegularExpressions; + +namespace NadekoBot.Modules.NSFW +{ + [Module("~", AppendSpace = false)] + public class NSFWModule : DiscordModule + { + + private readonly Random rng = new Random(); + + public NSFWModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client) + { + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Hentai(IMessage imsg, [Remainder] string tag) + { + var channel = imsg.Channel as IGuildChannel; + + tag = tag?.Trim() ?? ""; + + var links = await Task.WhenAll(GetGelbooruImageLink("rating%3Aexplicit+" + tag), GetDanbooruImageLink("rating%3Aexplicit+" + tag)).ConfigureAwait(false); + + if (links.All(l => l == null)) + { + await imsg.Channel.SendMessageAsync("`No results.`"); + return; + } + + await imsg.Channel.SendMessageAsync(String.Join("\n\n", links)).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Danbooru(IMessage imsg, [Remainder] string tag) + { + var channel = imsg.Channel as IGuildChannel; + + tag = tag?.Trim() ?? ""; + var link = await GetDanbooruImageLink(tag).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(link)) + await imsg.Channel.SendMessageAsync("Search yielded no results ;("); + else + await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Gelbooru(IMessage imsg, [Remainder] string tag) + { + var channel = imsg.Channel as IGuildChannel; + + tag = tag?.Trim() ?? ""; + var link = await GetRule34ImageLink(tag).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(link)) + await imsg.Channel.SendMessageAsync("Search yielded no results ;("); + else + await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Rule34(IMessage imsg, [Remainder] string tag) + { + var channel = imsg.Channel as IGuildChannel; + + tag = tag?.Trim() ?? ""; + var link = await GetGelbooruImageLink(tag).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(link)) + await imsg.Channel.SendMessageAsync("Search yielded no results ;("); + else + await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task E621(IMessage imsg, [Remainder] string tag) + { + var channel = imsg.Channel as IGuildChannel; + + tag = tag?.Trim() ?? ""; + var link = await GetE621ImageLink(tag).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(link)) + await imsg.Channel.SendMessageAsync("Search yielded no results ;("); + else + await imsg.Channel.SendMessageAsync(link).ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Cp(IMessage imsg) + { + var channel = imsg.Channel as IGuildChannel; + + await imsg.Channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Boobs(IMessage imsg) + { + var channel = imsg.Channel as IGuildChannel; + try + { + JToken obj; + using (var http = new HttpClient()) + { + obj = JArray.Parse(await http.GetStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}").ConfigureAwait(false))[0]; + } + await imsg.Channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + } + catch (Exception ex) + { + await imsg.Channel.SendMessageAsync($"💢 {ex.Message}").ConfigureAwait(false); + } + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Butts(IMessage imsg) + { + var channel = imsg.Channel as IGuildChannel; + + try + { + JToken obj; + using (var http = new HttpClient()) + { + obj = JArray.Parse(await http.GetStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}").ConfigureAwait(false))[0]; + } + await imsg.Channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + } + catch (Exception ex) + { + await imsg.Channel.SendMessageAsync($"💢 {ex.Message}").ConfigureAwait(false); + } + } + + public static async Task GetDanbooruImageLink(string tag) + { + var rng = new Random(); + + if (tag == "loli") //loli doesn't work for some reason atm + tag = "flat_chest"; + + var link = $"http://danbooru.donmai.us/posts?" + + $"page={rng.Next(0, 15)}"; + if (!string.IsNullOrWhiteSpace(tag)) + link += $"&tags={tag.Replace(" ", "_")}"; + using (var http = new HttpClient()) + { + var webpage = await http.GetStringAsync(link).ConfigureAwait(false); + var matches = Regex.Matches(webpage, "data-large-file-url=\"(?.*?)\""); + + if (matches.Count == 0) + return null; + return $"http://danbooru.donmai.us" + + $"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}"; + } + } + + public static async Task GetGelbooruImageLink(string tag) + { + var headers = new Dictionary() { + {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, + {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, + }; + var url = + $"http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; + var webpage = await GetResponseStringAsync(url, headers).ConfigureAwait(false); + var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); + if (matches.Count == 0) + return null; + var rng = new Random(); + var match = matches[rng.Next(0, matches.Count)]; + return matches[rng.Next(0, matches.Count)].Groups["url"].Value; + } + + public static async Task GetSafebooruImageLink(string tag) + { + var rng = new Random(); + var url = + $"http://safebooru.org/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; + var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); + var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); + if (matches.Count == 0) + return null; + var match = matches[rng.Next(0, matches.Count)]; + return matches[rng.Next(0, matches.Count)].Groups["url"].Value; + } + + public static async Task GetRule34ImageLink(string tag) + { + var rng = new Random(); + var url = + $"http://rule34.xxx/index.php?page=dapi&s=post&q=index&limit=100&tags={tag.Replace(" ", "_")}"; + var webpage = await GetResponseStringAsync(url).ConfigureAwait(false); + var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); + if (matches.Count == 0) + return null; + var match = matches[rng.Next(0, matches.Count)]; + return "http:" + matches[rng.Next(0, matches.Count)].Groups["url"].Value; + } + + + internal static async Task GetE621ImageLink(string tags) + { + try + { + var headers = new Dictionary() { + {"User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"}, + {"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" }, + }; + var data = await GetResponseStreamAsync( + "http://e621.net/post/index.xml?tags=" + Uri.EscapeUriString(tags) + "%20order:random&limit=1", + headers); + var doc = XDocument.Load(data); + return doc.Descendants("file_url").FirstOrDefault().Value; + } + catch (Exception ex) + { + Console.WriteLine("Error in e621 search: \n" + ex); + return "Error, do you have too many tags?"; + } + } + } +} diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index d196bc9d..1c242b45 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -1,99 +1,86 @@ -//using Discord; -//using Discord.Commands; -//using NadekoBot.Classes; -//using NadekoBot.Extensions; -//using System; -//using System.Linq; -//using System.Text; +using Discord; +using Discord.Commands; +using NadekoBot.Attributes; +using NadekoBot.Extensions; +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -//namespace NadekoBot.Modules.Utility.Commands -//{ -// class InfoCommands : DiscordCommand -// { -// public InfoCommands(DiscordModule module) : base(module) -// { -// } +namespace NadekoBot.Modules.Utility +{ + partial class UtilityModule : DiscordModule + { + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ServerInfo(IMessage msg, string guild = null) + { + var channel = msg.Channel as IGuildChannel; + guild = guild?.ToUpperInvariant(); + IGuild server; + if (guild == null) + server = channel.Guild; + else + server = (await _client.GetGuildsAsync()).Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault(); + if (server == null) + return; -// internal override void Init(CommandGroupBuilder cgb) -// { -// cgb.CreateCommand(Module.Prefix + "serverinfo") -// .Alias(Module.Prefix + "sinfo") -// .Description($"Shows info about the server the bot is on. If no channel is supplied, it defaults to current one. |`{Module.Prefix}sinfo Some Server`") -// .Parameter("server", ParameterType.Optional) -// .Do(async e => -// { -// var servText = e.GetArg("server")?.Trim(); -// var server = string.IsNullOrWhiteSpace(servText) -// ? e.Server -// : NadekoBot.Client.FindServers(servText).FirstOrDefault(); -// if (server == null) -// return; -// var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(server.Id >> 22); -// var sb = new StringBuilder(); -// sb.AppendLine($"`Name:` **#{server.Name}**"); -// sb.AppendLine($"`Owner:` **{server.Owner}**"); -// sb.AppendLine($"`Id:` **{server.Id}**"); -// sb.AppendLine($"`Icon Url:` **{await server.IconUrl.ShortenUrl().ConfigureAwait(false)}**"); -// sb.AppendLine($"`TextChannels:` **{server.TextChannels.Count()}** `VoiceChannels:` **{server.VoiceChannels.Count()}**"); -// sb.AppendLine($"`Members:` **{server.UserCount}** `Online:` **{server.Users.Count(u => u.Status == UserStatus.Online)}** (may be incorrect)"); -// sb.AppendLine($"`Roles:` **{server.Roles.Count()}**"); -// sb.AppendLine($"`Created At:` **{createdAt}**"); -// if (server.CustomEmojis.Count() > 0) -// sb.AppendLine($"`Custom Emojis:` **{string.Join(", ", server.CustomEmojis)}**"); -// if (server.Features.Count() > 0) -// sb.AppendLine($"`Features:` **{string.Join(", ", server.Features)}**"); -// if (!string.IsNullOrWhiteSpace(server.SplashId)) -// sb.AppendLine($"`Region:` **{server.Region.Name}**"); -// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); -// }); + var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(server.Id >> 22); + var sb = new StringBuilder(); + var users = await server.GetUsersAsync(); + sb.AppendLine($@"`Name:` **{server.Name}** +`Owner:` **{await server.GetUserAsync(server.OwnerId)}** +`Id:` **{server.Id}** +`Icon Url:` **{ server.IconUrl}** +`TextChannels:` **{(await server.GetTextChannelsAsync()).Count()}** `VoiceChannels:` **{(await server.GetVoiceChannelsAsync()).Count()}** +`Members:` **{users.Count}** `Online:` **{users.Count(u => u.Status == UserStatus.Online)}** +`Roles:` **{server.Roles.Count()}** +`Created At:` **{createdAt}**"); + if (server.Emojis.Count() > 0) + sb.AppendLine($"`Custom Emojis:` **{string.Join(", ", server.Emojis)}**"); + if (server.Features.Count() > 0) + sb.AppendLine($"`Features:` **{string.Join(", ", server.Features)}**"); + if (!string.IsNullOrWhiteSpace(server.SplashUrl)) + sb.AppendLine($"`Region:` **{server.VoiceRegionId}**"); + await msg.Reply(sb.ToString()).ConfigureAwait(false); + } -// cgb.CreateCommand(Module.Prefix + "channelinfo") -// .Alias(Module.Prefix + "cinfo") -// .Description($"Shows info about the channel. If no channel is supplied, it defaults to current one. |`{Module.Prefix}cinfo #some-channel`") -// .Parameter("channel", ParameterType.Optional) -// .Do(async e => -// { -// var chText = e.GetArg("channel")?.Trim(); -// var ch = string.IsNullOrWhiteSpace(chText) -// ? e.Channel -// : e.Server.FindChannels(chText, Discord.ChannelType.Text).FirstOrDefault(); -// if (ch == null) -// return; -// var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); -// var sb = new StringBuilder(); -// sb.AppendLine($"`Name:` **#{ch.Name}**"); -// sb.AppendLine($"`Id:` **{ch.Id}**"); -// sb.AppendLine($"`Created At:` **{createdAt}**"); -// sb.AppendLine($"`Topic:` **{ch.Topic}**"); -// sb.AppendLine($"`Users:` **{ch.Users.Count()}**"); -// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); -// }); + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ChannelInfo(IMessage msg, ITextChannel channel = null) + { + var ch = channel ?? msg.Channel as ITextChannel; + if (ch == null) + return; + var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); + var sb = new StringBuilder(); + sb.AppendLine($"`Name:` **#{ch.Name}**"); + sb.AppendLine($"`Id:` **{ch.Id}**"); + sb.AppendLine($"`Created At:` **{createdAt}**"); + sb.AppendLine($"`Topic:` **{ch.Topic}**"); + sb.AppendLine($"`Users:` **{(await ch.GetUsersAsync()).Count()}**"); + await msg.Reply(sb.ToString()).ConfigureAwait(false); + } -// cgb.CreateCommand(Module.Prefix + "userinfo") -// .Alias(Module.Prefix + "uinfo") -// .Description($"Shows info about the user. If no user is supplied, it defaults a user running the command. |`{Module.Prefix}uinfo @SomeUser`") -// .Parameter("user", ParameterType.Optional) -// .Do(async e => -// { -// var userText = e.GetArg("user")?.Trim(); -// var user = string.IsNullOrWhiteSpace(userText) -// ? e.User -// : e.Server.FindUsers(userText).FirstOrDefault(); -// if (user == null) -// return; -// var sb = new StringBuilder(); -// sb.AppendLine($"`Name#Discrim:` **#{user.Name}#{user.Discriminator}**"); -// if (!string.IsNullOrWhiteSpace(user.Nickname)) -// sb.AppendLine($"`Nickname:` **{user.Nickname}**"); -// sb.AppendLine($"`Id:` **{user.Id}**"); -// sb.AppendLine($"`Current Game:` **{(user.CurrentGame?.Name == null ? "-" : user.CurrentGame.Value.Name)}**"); -// if (user.LastOnlineAt != null) -// sb.AppendLine($"`Last Online:` **{user.LastOnlineAt:HH:mm:ss}**"); -// sb.AppendLine($"`Joined At:` **{user.JoinedAt}**"); -// sb.AppendLine($"`Roles:` **({user.Roles.Count()}) - {string.Join(", ", user.Roles.Select(r => r.Name))}**"); -// sb.AppendLine($"`AvatarUrl:` **{await user.AvatarUrl.ShortenUrl().ConfigureAwait(false)}**"); -// await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); -// }); -// } -// } -//} + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task UserInfo(IMessage msg, IGuildUser usr = null) + { + var channel = msg.Channel as IGuildChannel; + var user = usr ?? msg.Author as IGuildUser; + if (user == null) + return; + var sb = new StringBuilder(); + sb.AppendLine($"`Name#Discrim:` **#{user.Username}#{user.Discriminator}**"); + if (!string.IsNullOrWhiteSpace(user.Nickname)) + sb.AppendLine($"`Nickname:` **{user.Nickname}**"); + sb.AppendLine($"`Id:` **{user.Id}**"); + sb.AppendLine($"`Current Game:` **{(user.Game?.Name == null ? "-" : user.Game.Name)}**"); + sb.AppendLine($"`Joined At:` **{user.JoinedAt}**"); + sb.AppendLine($"`Roles:` **({user.Roles.Count()}) - {string.Join(", ", user.Roles.Select(r => r.Name))}**"); + sb.AppendLine($"`AvatarUrl:` **{user.AvatarUrl}**"); + await msg.Reply(sb.ToString()).ConfigureAwait(false); + } + + } +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index 818ce080..4f4bea7f 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -113,7 +113,7 @@ // if (ch == null) // { -// await e.Channel.SendMessage($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); +// await channel.SendMessageAsync($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); // return; // } @@ -123,7 +123,7 @@ // if (m.Length == 0) // { -// await e.Channel.SendMessage("Not a valid time format blablabla").ConfigureAwait(false); +// await channel.SendMessageAsync("Not a valid time format blablabla").ConfigureAwait(false); // return; // } @@ -148,7 +148,7 @@ // (groupName == "hours" && value > 23) || // (groupName == "minutes" && value > 59)) // { -// await e.Channel.SendMessage($"Invalid {groupName} value.").ConfigureAwait(false); +// await channel.SendMessageAsync($"Invalid {groupName} value.").ConfigureAwait(false); // return; // } // else @@ -175,7 +175,7 @@ // reminders.Add(StartNewReminder(rem)); -// await e.Channel.SendMessage($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false); +// await channel.SendMessageAsync($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false); // }); // cgb.CreateCommand(Module.Prefix + "remindmsg") // .Description("Sets message for when the remind is triggered. " + @@ -190,7 +190,7 @@ // return; // NadekoBot.Config.RemindMessageFormat = arg; -// await e.Channel.SendMessage("`New remind message set.`"); +// await channel.SendMessageAsync("`New remind message set.`"); // }); // } // } diff --git a/src/NadekoBot/Modules/Utility/UtilityModule.cs b/src/NadekoBot/Modules/Utility/UtilityModule.cs index 640db153..1e87e91f 100644 --- a/src/NadekoBot/Modules/Utility/UtilityModule.cs +++ b/src/NadekoBot/Modules/Utility/UtilityModule.cs @@ -4,16 +4,24 @@ using NadekoBot.Attributes; using System; using System.Linq; using System.Threading.Tasks; +using NadekoBot.Services; +using System.Text; +using NadekoBot.Extensions; +using System.Text.RegularExpressions; +using System.Collections.Generic; +using System.Reflection; namespace NadekoBot.Modules.Utility { [Module(".", AppendSpace = false)] - public class UtilityModule + public partial class UtilityModule : DiscordModule { - [LocalizedCommand] - [LocalizedDescription] - [LocalizedSummary] + public UtilityModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client) + { + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] [RequireContext(ContextType.Guild)] public async Task WhoPlays(IMessage imsg, [Remainder] string game) { @@ -22,154 +30,161 @@ namespace NadekoBot.Modules.Utility if (string.IsNullOrWhiteSpace(game)) return; var arr = (await chnl.Guild.GetUsersAsync()) - .Where(u => u.Game?.Name.ToUpperInvariant() == game) + .Where(u => u.Game?.Name?.ToUpperInvariant() == game) .Select(u => u.Username) .ToList(); int i = 0; if (!arr.Any()) - await imsg.Channel.SendMessageAsync("`Noone is playing that game.`").ConfigureAwait(false); + await imsg.Channel.SendMessageAsync(_l["`Nobody is playing that game.`"]).ConfigureAwait(false); else await imsg.Channel.SendMessageAsync("```xl\n" + string.Join("\n", arr.GroupBy(item => (i++) / 3).Select(ig => string.Concat(ig.Select(el => $"• {el,-35}")))) + "\n```").ConfigureAwait(false); } - [LocalizedCommand] - [LocalizedDescription] - [LocalizedSummary] + [LocalizedCommand, LocalizedDescription, LocalizedSummary] [RequireContext(ContextType.Guild)] - public async Task InRole(IMessage imsg, [Remainder] string roles) { + public async Task InRole(IMessage imsg, [Remainder] string roles) + { if (string.IsNullOrWhiteSpace(roles)) return; var channel = imsg.Channel as IGuildChannel; var arg = roles.Split(',').Select(r => r.Trim().ToUpperInvariant()); - string send = $"`Here is a list of users in a specfic role:`"; + string send = _l["`Here is a list of users in a specfic role:`"]; 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(); if (role == null) continue; send += $"\n`{role.Name}`\n"; - send += string.Join(", ", (await channel.Guild.GetUsersAsync()).Where(u=>u.Roles.Contains(role)).Select(u => u.ToString())); + send += string.Join(", ", (await channel.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Select(u => u.ToString())); } - - //todo - - - //while (send.Length > 2000) - //{ - // if (!) - // { - // await e.Channel.SendMessage($"{e.User.Mention} you are not allowed to use this command on roles with a lot of users in them to prevent abuse."); - // return; - // } - // var curstr = send.Substring(0, 2000); - // await imsg.Channel.SendMessageAsync(curstr.Substring(0, - // curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); - // send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + - // send.Substring(2000); - //} - //await e.Channel.Send(send).ConfigureAwait(false); + var usr = imsg.Author as IGuildUser; + while (send.Length > 2000) + { + if (!usr.GetPermissions(channel).ManageMessages) + { + await imsg.Channel.SendMessageAsync($"{usr.Mention} you are not allowed to use this command on roles with a lot of users in them to prevent abuse."); + return; + } + var curstr = send.Substring(0, 2000); + await imsg.Channel.SendMessageAsync(curstr.Substring(0, + curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); + send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + + send.Substring(2000); + } + await imsg.Channel.SendMessageAsync(send).ConfigureAwait(false); } + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task CheckMyPerms(IMessage msg) + { + StringBuilder builder = new StringBuilder("```\n"); + var user = msg.Author as IGuildUser; + var perms = user.GetPermissions(msg.Channel as ITextChannel); + foreach (var p in perms.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) + { + builder.AppendLine($"{p.Name} : {p.GetValue(perms, null).ToString()}"); + } + builder.Append("```"); + await msg.Reply(builder.ToString()); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task UserId(IMessage msg, IGuildUser target = null) + { + var usr = target ?? msg.Author; + await msg.Reply($"Id of the user { usr.Username } is { usr.Id })"); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + public async Task ChannelId(IMessage msg) + { + await msg.Reply($"This Channel's ID is {msg.Channel.Id}"); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task ServerId(IMessage msg) + { + await msg.Reply($"This server's ID is {(msg.Channel as IGuildChannel).Guild.Id}"); + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Roles(IMessage msg, IGuildUser target = null) + { + var guild = (msg.Channel as IGuildChannel).Guild; + if (target != null) + { + await msg.Reply($"`List of roles for **{target.Username}**:` \n• " + string.Join("\n• ", target.Roles.Except(new[] { guild.EveryoneRole }))); + } + else + { + await msg.Reply("`List of roles:` \n• " + string.Join("\n• ", (msg.Channel as IGuildChannel).Guild.Roles.Except(new[] { guild.EveryoneRole }))); + } + } + + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Prune(IMessage msg, [Remainder] string target = null) + { + var channel = msg.Channel as IGuildChannel; + + var user = await channel.Guild.GetCurrentUserAsync(); + if (string.IsNullOrWhiteSpace(target)) + { + + var enumerable = (await msg.Channel.GetMessagesAsync(limit: 100)).Where(x => x.Author.Id == user.Id); + await msg.Channel.DeleteMessagesAsync(enumerable); + return; + } + target = target.Trim(); + if (!user.GetPermissions(channel).ManageMessages) + { + await msg.Reply("Don't have permissions to manage messages in channel"); + return; + } + int count; + if (int.TryParse(target, out count)) + { + while (count > 0) + { + int limit = (count < 100) ? count : 100; + var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit)); + await msg.Channel.DeleteMessagesAsync(enumerable); + if (enumerable.Count < limit) break; + count -= limit; + } + } + else if (msg.MentionedUsers.Count > 0) + { + var toDel = new List(); + + var match = Regex.Match(target, @"\s(\d+)\s"); + if (match.Success) + { + int.TryParse(match.Groups[1].Value, out count); + var messages = new List(count); + + while (count > 0) + { + var toAdd = await msg.Channel.GetMessagesAsync(limit: count < 100 ? count : 100); + messages.AddRange(toAdd); + count -= toAdd.Count; + } + + foreach (var mention in msg.MentionedUsers) + { + toDel.AddRange(messages.Where(m => m.Author.Id == mention.Id)); + } + //TODO check if limit == 100 or there is no limit + await msg.Channel.DeleteMessagesAsync(toDel); + } + } + } } } - //public void Install() - //{ - // manager.CreateCommands("", cgb => - // { - // cgb.AddCheck(PermissionChecker.Instance); - - // var client = manager.Client; - - // commands.ForEach(cmd => cmd.Init(cgb)); - - // cgb.CreateCommand(Prefix + "whoplays") - // .Description() - // .Parameter("game", ParameterType.Unparsed) - // .Do(async e => - // { - - // }); - - - - // cgb.CreateCommand(Prefix + "checkmyperms") - // .Description($"Checks your userspecific permissions on this channel. | `{Prefix}checkmyperms`") - // .Do(async e => - // { - // var output = "```\n"; - // foreach (var p in e.User.ServerPermissions.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) - // { - // output += p.Name + ": " + p.GetValue(e.User.ServerPermissions, null).ToString() + "\n"; - // } - // output += "```"; - // await e.User.SendMessage(output).ConfigureAwait(false); - // }); - - // cgb.CreateCommand(Prefix + "stats") - // .Description($"Shows some basic stats for Nadeko. | `{Prefix}stats`") - // .Do(async e => - // { - // await e.Channel.SendMessage(await NadekoStats.Instance.GetStats()).ConfigureAwait(false); - // }); - - // cgb.CreateCommand(Prefix + "dysyd") - // .Description($"Shows some basic stats for Nadeko. | `{Prefix}dysyd`") - // .Do(async e => - // { - // await e.Channel.SendMessage((await NadekoStats.Instance.GetStats()).Matrix().TrimTo(1990)).ConfigureAwait(false); - // }); - - // cgb.CreateCommand(Prefix + "userid").Alias(Prefix + "uid") - // .Description($"Shows user ID. | `{Prefix}uid` or `{Prefix}uid \"@SomeGuy\"`") - // .Parameter("user", ParameterType.Unparsed) - // .Do(async e => - // { - // var usr = e.User; - // if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault(); - // if (usr == null) - // return; - // await e.Channel.SendMessage($"Id of the user { usr.Name } is { usr.Id }").ConfigureAwait(false); - // }); - - // cgb.CreateCommand(Prefix + "channelid").Alias(Prefix + "cid") - // .Description($"Shows current channel ID. | `{Prefix}cid`") - // .Do(async e => await e.Channel.SendMessage("This channel's ID is " + e.Channel.Id).ConfigureAwait(false)); - - // cgb.CreateCommand(Prefix + "serverid").Alias(Prefix + "sid") - // .Description($"Shows current server ID. | `{Prefix}sid`") - // .Do(async e => await e.Channel.SendMessage("This server's ID is " + e.Server.Id).ConfigureAwait(false)); - - // cgb.CreateCommand(Prefix + "roles") - // .Description("List all roles on this server or a single user if specified. | `{Prefix}roles`") - // .Parameter("user", ParameterType.Unparsed) - // .Do(async e => - // { - // if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) - // { - // var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault(); - // if (usr == null) return; - - // await e.Channel.SendMessage($"`List of roles for **{usr.Name}**:` \n• " + string.Join("\n• ", usr.Roles)).ConfigureAwait(false); - // return; - // } - // await e.Channel.SendMessage("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles)).ConfigureAwait(false); - // }); - - - // cgb.CreateCommand(Prefix + "channeltopic") - // .Alias(Prefix + "ct") - // .Description($"Sends current channel's topic as a message. | `{Prefix}ct`") - // .Do(async e => - // { - // var topic = e.Channel.Topic; - // if (string.IsNullOrWhiteSpace(topic)) - // return; - // await e.Channel.SendMessage(topic).ConfigureAwait(false); - // }); - // }); -// } -// } -//} diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 71d8880e..c9eb20b3 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -1,6 +1,9 @@ -using Discord.Commands; +using Discord; +using Discord.Commands; using Discord.WebSocket; using NadekoBot.Modules.Utility; +using NadekoBot.Services; +using NadekoBot.Services.Impl; using System; using System.Collections.Generic; using System.Linq; @@ -13,30 +16,50 @@ namespace NadekoBot { public static CommandService Commands { get; private set; } public static DiscordSocketClient Client { get; private set; } + public BotConfiguration Config { get; private set; } + public Localization Localizer { get; private set; } public async Task RunAsync(string[] args) { - Client = new DiscordSocketClient(new Discord.DiscordSocketConfig + //create client + Client = new DiscordSocketClient(new DiscordSocketConfig { AudioMode = Discord.Audio.AudioMode.Incoming, LargeThreshold = 200, - LogLevel = Discord.LogSeverity.Warning, + LogLevel = LogSeverity.Warning, MessageCacheSize = 10, }); + //initialize Services Commands = new CommandService(); + Config = new BotConfiguration(); + Localizer = new Localization(); + + //setup DI + var depMap = new DependencyMap(); + depMap.Add(Localizer); + depMap.Add(Config); + depMap.Add(Client); + depMap.Add(Commands); - //Client.MessageReceived += Client_MessageReceived; - - //await Commands.Load(new UtilityModule()); - await Commands.LoadAssembly(Assembly.GetEntryAssembly()); - - await Client.LoginAsync(Discord.TokenType.Bot, "MTE5Nzc3MDIxMzE5NTc3NjEw.CmxGHA.nk1KyvR6y05nntj-J0W_Zvu-2kk"); + //connect + await Client.LoginAsync(TokenType.Bot, "MTE5Nzc3MDIxMzE5NTc3NjEw.CpGoCA.yQBJbLWurrjSk7IlGpGzBm-tPTg"); await Client.ConnectAsync(); + + //load commands + await Commands.LoadAssembly(Assembly.GetEntryAssembly(), depMap); + Client.MessageReceived += Client_MessageReceived; Console.WriteLine(Commands.Commands.Count()); await Task.Delay(-1); } + + private async Task Client_MessageReceived(IMessage arg) + { + var t = await Commands.Execute(arg, 0); + if(!t.IsSuccess) + Console.WriteLine(t.ErrorReason); + } } } diff --git a/src/NadekoBot/Resources/Strings.Designer.cs b/src/NadekoBot/Resources/CommandStrings.Designer.cs similarity index 99% rename from src/NadekoBot/Resources/Strings.Designer.cs rename to src/NadekoBot/Resources/CommandStrings.Designer.cs index 1f48b5cc..e3fe9537 100644 --- a/src/NadekoBot/Resources/Strings.Designer.cs +++ b/src/NadekoBot/Resources/CommandStrings.Designer.cs @@ -22,13 +22,13 @@ namespace NadekoBot.Resources { // with the /str option, or rebuild your VS project. [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - public class Strings { + public class CommandStrings { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; - internal Strings() { + internal CommandStrings() { } /// @@ -38,7 +38,7 @@ namespace NadekoBot.Resources { public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.Strings", typeof(Strings).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.CommandStrings", typeof(CommandStrings).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; diff --git a/src/NadekoBot/Resources/Strings.resx b/src/NadekoBot/Resources/CommandStrings.resx similarity index 100% rename from src/NadekoBot/Resources/Strings.resx rename to src/NadekoBot/Resources/CommandStrings.resx diff --git a/src/NadekoBot/Resources/ResponseStrings.Designer.cs b/src/NadekoBot/Resources/ResponseStrings.Designer.cs new file mode 100644 index 00000000..15ceb39d --- /dev/null +++ b/src/NadekoBot/Resources/ResponseStrings.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace NadekoBot.Resources { + using System; + using System.Reflection; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class ResponseStrings { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + internal ResponseStrings() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("NadekoBot.Resources.ResponseStrings", typeof(ResponseStrings).GetTypeInfo().Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to TESTING. + /// + public static string test { + get { + return ResourceManager.GetString("test", resourceCulture); + } + } + } +} diff --git a/src/NadekoBot/Resources/ResponseStrings.resx b/src/NadekoBot/Resources/ResponseStrings.resx new file mode 100644 index 00000000..188ec335 --- /dev/null +++ b/src/NadekoBot/Resources/ResponseStrings.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + TESTING + + \ No newline at end of file diff --git a/src/NadekoBot/Services/ILocalization.cs b/src/NadekoBot/Services/ILocalization.cs new file mode 100644 index 00000000..9b18f0a7 --- /dev/null +++ b/src/NadekoBot/Services/ILocalization.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace NadekoBot.Services +{ + public interface ILocalization + { + string this[string key] { get; } + } +} diff --git a/src/NadekoBot/Localization.cs b/src/NadekoBot/Services/Impl/Localization.cs similarity index 66% rename from src/NadekoBot/Localization.cs rename to src/NadekoBot/Services/Impl/Localization.cs index 3cd33e42..3d36e0da 100644 --- a/src/NadekoBot/Localization.cs +++ b/src/NadekoBot/Services/Impl/Localization.cs @@ -7,13 +7,34 @@ using System.Resources; namespace NadekoBot.Services { - public class Localization + public class Localization : ILocalization { - public static string LoadString(string key) => GetOrAddResourceKey(key); + public string this[string key] { + get { + try + { + return Resources.ResponseStrings.ResourceManager.GetString(key); + } + catch (Exception) { + return key; + } + } + } - private static string GetOrAddResourceKey(string key) + public static string LoadCommandString(string key) { - return Resources.Strings.ResourceManager.GetString(key); + try + { + return Resources.CommandStrings.ResourceManager.GetString(key); + } + catch (Exception) { + return key; + } + } + + //private static string GetCommandString(string key) + //{ + // return key; //var resx = new List(); //var fs = new StreamReader(File.OpenRead("./Strings.resx")); //Console.WriteLine(fs.ReadToEnd()); @@ -41,6 +62,6 @@ namespace NadekoBot.Services // writer.Generate(); //} //return key; - } + //} } } diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs new file mode 100644 index 00000000..1b08c734 --- /dev/null +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -0,0 +1,51 @@ +using Discord; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace NadekoBot.Extensions +{ + public static class Extensions + { + public static async Task Reply(this IMessage msg, string content) => await msg.Channel.SendMessageAsync(content); + + public static async Task ReplyLong(this IMessage msg, string content, string breakOn = "\n", string addToEnd = "", string addToStart = "") + { + + if (content.Length < 2000) return new[] { await msg.Channel.SendMessageAsync(content) }; + var list = new List(); + + var temp = Regex.Split(content, breakOn).Select(x => x += breakOn).ToList(); + string toolong; + //while ((toolong = temp.FirstOrDefault(x => x.Length > 2000)) != null) + //{ + // //TODO more desperate measures == split on whitespace? + //} + + StringBuilder builder = new StringBuilder(); + //TODO make this less crappy to look at, maybe it's bugged + for (int i = 0; i < temp.Count; i++) + { + var addition = temp[i]; + //we append + + if (builder.Length == 0 && i != 0) builder.Append(addToStart + addition); + else builder.Append(addition); + + //Check if the next would have room + if (i + 1 >= temp.Count || temp[i + 1].Length + builder.Length + addToEnd.Length > 2000) + { + if (i + 1 < temp.Count) builder.Append(addToEnd); + list.Add(await msg.Channel.SendMessageAsync(builder.ToString())); + builder.Clear(); + } + } + + return list.ToArray(); + } + + } +} \ No newline at end of file diff --git a/src/NadekoBot/_Modules/Administration/AdministrationModule.cs b/src/NadekoBot/_Modules/Administration/AdministrationModule.cs index 23402c81..ecd118f9 100644 --- a/src/NadekoBot/_Modules/Administration/AdministrationModule.cs +++ b/src/NadekoBot/_Modules/Administration/AdministrationModule.cs @@ -72,9 +72,9 @@ namespace NadekoBot.Modules.Administration conf.AutoDeleteMessagesOnCommand = !conf.AutoDeleteMessagesOnCommand; await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); if (conf.AutoDeleteMessagesOnCommand) - await e.Channel.SendMessage("❗`Now automatically deleting successfull command invokations.`"); + await channel.SendMessageAsync("❗`Now automatically deleting successfull command invokations.`"); else - await e.Channel.SendMessage("❗`Stopped automatic deletion of successfull command invokations.`"); + await channel.SendMessageAsync("❗`Stopped automatic deletion of successfull command invokations.`"); }); @@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Administration .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { - await e.Channel.SendMessage("`Restarting in 2 seconds...`"); + await channel.SendMessageAsync("`Restarting in 2 seconds...`"); await Task.Delay(2000); System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location); Environment.Exit(0); @@ -103,31 +103,31 @@ namespace NadekoBot.Modules.Administration if (!e.User.ServerPermissions.ManageRoles) { - await e.Channel.SendMessage("You have insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("You have insufficient permissions.").ConfigureAwait(false); } var usr = e.Server.FindUsers(userName).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); + await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false); return; } var role = e.Server.FindRoles(roleName).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false); + await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false); return; } try { await usr.AddRoles(role).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false); Console.WriteLine(ex.ToString()); } }); @@ -147,25 +147,25 @@ namespace NadekoBot.Modules.Administration var usr = e.Server.FindUsers(userName).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); + await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false); return; } var role = e.Server.FindRoles(roleName).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage("You failed to supply a valid role").ConfigureAwait(false); + await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false); return; } try { await usr.RemoveRoles(role).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); } }); @@ -183,7 +183,7 @@ namespace NadekoBot.Modules.Administration var roleToEdit = e.Server.FindRoles(r1).FirstOrDefault(); if (roleToEdit == null) { - await e.Channel.SendMessage("Can't find that role.").ConfigureAwait(false); + await channel.SendMessageAsync("Can't find that role.").ConfigureAwait(false); return; } @@ -191,15 +191,15 @@ namespace NadekoBot.Modules.Administration { if (roleToEdit.Position > e.Server.CurrentUser.Roles.Max(r => r.Position)) { - await e.Channel.SendMessage("I can't edit roles higher than my highest role.").ConfigureAwait(false); + await channel.SendMessageAsync("I can't edit roles higher than my highest role.").ConfigureAwait(false); return; } await roleToEdit.Edit(r2); - await e.Channel.SendMessage("Role renamed.").ConfigureAwait(false); + await channel.SendMessageAsync("Role renamed.").ConfigureAwait(false); } catch (Exception) { - await e.Channel.SendMessage("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false); } }); @@ -214,18 +214,18 @@ namespace NadekoBot.Modules.Administration var usr = e.Server.FindUsers(userName).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("You failed to supply a valid username").ConfigureAwait(false); + await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false); return; } try { await usr.RemoveRoles(usr.Roles.ToArray()).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false); } }); @@ -240,11 +240,11 @@ namespace NadekoBot.Modules.Administration try { var r = await e.Server.CreateRole(e.GetArg("role_name")).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully created role **{r.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully created role **{r.Name}**.").ConfigureAwait(false); } catch (Exception) { - await e.Channel.SendMessage(":warning: Unspecified error.").ConfigureAwait(false); + await channel.SendMessageAsync(":warning: Unspecified error.").ConfigureAwait(false); } }); @@ -258,7 +258,7 @@ namespace NadekoBot.Modules.Administration { if (!e.User.ServerPermissions.ManageRoles) { - await e.Channel.SendMessage("You don't have permission to use this!").ConfigureAwait(false); + await channel.SendMessageAsync("You don't have permission to use this!").ConfigureAwait(false); return; } @@ -266,7 +266,7 @@ namespace NadekoBot.Modules.Administration if (args.Count() != 2 && args.Count() != 4) { - await e.Channel.SendMessage("The parameters are invalid.").ConfigureAwait(false); + await channel.SendMessageAsync("The parameters are invalid.").ConfigureAwait(false); return; } @@ -274,7 +274,7 @@ namespace NadekoBot.Modules.Administration if (role == null) { - await e.Channel.SendMessage("That role does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync("That role does not exist.").ConfigureAwait(false); return; } try @@ -287,11 +287,11 @@ namespace NadekoBot.Modules.Administration var blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16)); await role.Edit(color: new Color(red, green, blue)).ConfigureAwait(false); - await e.Channel.SendMessage($"Role {role.Name}'s color has been changed.").ConfigureAwait(false); + await channel.SendMessageAsync($"Role {role.Name}'s color has been changed.").ConfigureAwait(false); } catch (Exception) { - await e.Channel.SendMessage("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false); } }); @@ -308,7 +308,7 @@ namespace NadekoBot.Modules.Administration var usr = e.Server.FindUsers(user).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("User not found.").ConfigureAwait(false); + await channel.SendMessageAsync("User not found.").ConfigureAwait(false); return; } if (!string.IsNullOrWhiteSpace(msg)) @@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration { await e.Server.Ban(usr, 7).ConfigureAwait(false); - await e.Channel.SendMessage("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); + await channel.SendMessageAsync("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } }); @@ -343,7 +343,7 @@ namespace NadekoBot.Modules.Administration var usr = e.Server.FindUsers(user).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("User not found.").ConfigureAwait(false); + await channel.SendMessageAsync("User not found.").ConfigureAwait(false); return; } if (!string.IsNullOrWhiteSpace(msg)) @@ -357,11 +357,11 @@ namespace NadekoBot.Modules.Administration await e.Server.Ban(usr, 7).ConfigureAwait(false); await e.Server.Unban(usr).ConfigureAwait(false); - await e.Channel.SendMessage("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); + await channel.SendMessageAsync("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } }); @@ -379,7 +379,7 @@ namespace NadekoBot.Modules.Administration var usr = e.Server.FindUsers(user).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("User not found.").ConfigureAwait(false); + await channel.SendMessageAsync("User not found.").ConfigureAwait(false); return; } if (!string.IsNullOrWhiteSpace(msg)) @@ -391,11 +391,11 @@ namespace NadekoBot.Modules.Administration try { await usr.Kick().ConfigureAwait(false); - await e.Channel.SendMessage("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); + await channel.SendMessageAsync("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } }); @@ -406,7 +406,7 @@ namespace NadekoBot.Modules.Administration { if (!e.User.ServerPermissions.MuteMembers) { - await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false); return; } if (!e.Message.MentionedUsers.Any()) @@ -417,11 +417,11 @@ namespace NadekoBot.Modules.Administration { await u.Edit(isMuted: true).ConfigureAwait(false); } - await e.Channel.SendMessage("Mute successful").ConfigureAwait(false); + await channel.SendMessageAsync("Mute successful").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }); @@ -432,7 +432,7 @@ namespace NadekoBot.Modules.Administration { if (!e.User.ServerPermissions.MuteMembers) { - await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); + await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false); return; } if (!e.Message.MentionedUsers.Any()) @@ -443,11 +443,11 @@ namespace NadekoBot.Modules.Administration { await u.Edit(isMuted: false).ConfigureAwait(false); } - await e.Channel.SendMessage("Unmute successful").ConfigureAwait(false); + await channel.SendMessageAsync("Unmute successful").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }); @@ -459,7 +459,7 @@ namespace NadekoBot.Modules.Administration { if (!e.User.ServerPermissions.DeafenMembers) { - await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); + await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false); return; } if (!e.Message.MentionedUsers.Any()) @@ -470,11 +470,11 @@ namespace NadekoBot.Modules.Administration { await u.Edit(isDeafened: true).ConfigureAwait(false); } - await e.Channel.SendMessage("Deafen successful").ConfigureAwait(false); + await channel.SendMessageAsync("Deafen successful").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }); @@ -486,7 +486,7 @@ namespace NadekoBot.Modules.Administration { if (!e.User.ServerPermissions.DeafenMembers) { - await e.Channel.SendMessage("You do not have permission to do that.").ConfigureAwait(false); + await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false); return; } if (!e.Message.MentionedUsers.Any()) @@ -497,11 +497,11 @@ namespace NadekoBot.Modules.Administration { await u.Edit(isDeafened: false).ConfigureAwait(false); } - await e.Channel.SendMessage("Undeafen successful").ConfigureAwait(false); + await channel.SendMessageAsync("Undeafen successful").ConfigureAwait(false); } catch { - await e.Channel.SendMessage("I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false); } }); @@ -519,12 +519,12 @@ namespace NadekoBot.Modules.Administration if (ch == null) return; await ch.Delete().ConfigureAwait(false); - await e.Channel.SendMessage($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); } } catch { - await e.Channel.SendMessage("Insufficient permissions."); + await channel.SendMessageAsync("Insufficient permissions."); } }); @@ -539,12 +539,12 @@ namespace NadekoBot.Modules.Administration if (e.User.ServerPermissions.ManageChannels) { await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice).ConfigureAwait(false); - await e.Channel.SendMessage($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); } } catch { - await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false); } }); @@ -561,12 +561,12 @@ namespace NadekoBot.Modules.Administration var channel = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault(); if (channel == null) return; await channel.Delete().ConfigureAwait(false); - await e.Channel.SendMessage($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); } } catch { - await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false); } }); @@ -581,12 +581,12 @@ namespace NadekoBot.Modules.Administration if (e.User.ServerPermissions.ManageChannels) { await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text).ConfigureAwait(false); - await e.Channel.SendMessage($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false); } } catch { - await e.Channel.SendMessage("Insufficient permissions.").ConfigureAwait(false); + await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false); } }); @@ -599,7 +599,7 @@ namespace NadekoBot.Modules.Administration { var topic = e.GetArg("topic")?.Trim() ?? ""; await e.Channel.Edit(topic: topic).ConfigureAwait(false); - await e.Channel.SendMessage(":ok: **New channel topic set.**").ConfigureAwait(false); + await channel.SendMessageAsync(":ok: **New channel topic set.**").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "setchanlname") @@ -613,7 +613,7 @@ namespace NadekoBot.Modules.Administration if (string.IsNullOrWhiteSpace(name)) return; await e.Channel.Edit(name: name).ConfigureAwait(false); - await e.Channel.SendMessage(":ok: **New channel name set.**").ConfigureAwait(false); + await channel.SendMessageAsync(":ok: **New channel name set.**").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "heap") @@ -622,7 +622,7 @@ namespace NadekoBot.Modules.Administration .Do(async e => { var heap = await Task.Run(() => NadekoStats.Instance.Heap()).ConfigureAwait(false); - await e.Channel.SendMessage($"`Heap Size:` {heap}").ConfigureAwait(false); + await channel.SendMessageAsync($"`Heap Size:` {heap}").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "prune") @@ -647,7 +647,7 @@ namespace NadekoBot.Modules.Administration return; else if (!e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages) { - await e.Channel.SendMessage("💢I don't have the permission to manage messages."); + await channel.SendMessageAsync("💢I don't have the permission to manage messages."); return; } int val; @@ -678,7 +678,7 @@ namespace NadekoBot.Modules.Administration .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { - await e.Channel.SendMessage("`Shutting down.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Shutting down.`").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); Environment.Exit(0); }); @@ -711,7 +711,7 @@ namespace NadekoBot.Modules.Administration await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false); // Send confirm. - await e.Channel.SendMessage("New avatar set.").ConfigureAwait(false); + await channel.SendMessageAsync("New avatar set.").ConfigureAwait(false); // Save the image to disk. image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png); @@ -770,7 +770,7 @@ namespace NadekoBot.Modules.Administration } else { - await e.Channel.SendMessage("`Invalid format.`"); + await channel.SendMessageAsync("`Invalid format.`"); } }); @@ -824,7 +824,7 @@ namespace NadekoBot.Modules.Administration var donatorsOrdered = rows.OrderByDescending(d => d.Amount); string str = $"**Thanks to the people listed below for making this project happen!**\n"; - await e.Channel.SendMessage(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); + await channel.SendMessageAsync(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false); }).ConfigureAwait(false); }); @@ -848,7 +848,7 @@ namespace NadekoBot.Modules.Administration UserName = donator.Name, UserId = (long)donator.Id }); - e.Channel.SendMessage("Successfuly added a new donator. 👑").ConfigureAwait(false); + channel.SendMessageAsync("Successfuly added a new donator. 👑").ConfigureAwait(false); } catch { } }).ConfigureAwait(false); @@ -865,7 +865,7 @@ namespace NadekoBot.Modules.Administration await ch.SendMessage(e.GetArg("msg")).ConfigureAwait(false); } - await e.Channel.SendMessage(":ok:").ConfigureAwait(false); + await channel.SendMessageAsync(":ok:").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "savechat") diff --git a/src/NadekoBot/_Modules/Administration/Commands/AutoAssignRole.cs b/src/NadekoBot/_Modules/Administration/Commands/AutoAssignRole.cs index 38084dfa..89f64c3a 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/AutoAssignRole.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/AutoAssignRole.cs @@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands { if (!e.Server.CurrentUser.ServerPermissions.ManageRoles) { - await e.Channel.SendMessage("I do not have the permission to manage roles.").ConfigureAwait(false); + await channel.SendMessageAsync("I do not have the permission to manage roles.").ConfigureAwait(false); return; } var r = e.GetArg("role")?.Trim(); @@ -52,19 +52,19 @@ namespace NadekoBot.Modules.Administration.Commands { config.AutoAssignedRole = 0; - await e.Channel.SendMessage("`Auto assign role on user join is now disabled.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Auto assign role on user join is now disabled.`").ConfigureAwait(false); return; } var role = e.Server.FindRoles(r).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage("💢 `Role not found.`").ConfigureAwait(false); + await channel.SendMessageAsync("💢 `Role not found.`").ConfigureAwait(false); return; } config.AutoAssignedRole = role.Id; - await e.Channel.SendMessage("`Auto assigned role is set.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Auto assigned role is set.`").ConfigureAwait(false); }); } diff --git a/src/NadekoBot/_Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/_Modules/Administration/Commands/CrossServerTextChannel.cs index c08c34ef..512440e3 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/CrossServerTextChannel.cs @@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Administration.Commands if (!Subscribers.TryGetValue(token, out set)) return; set.Add(e.Channel); - await e.Channel.SendMessage(":ok:").ConfigureAwait(false); + await channel.SendMessageAsync(":ok:").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "lcsc") @@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Administration.Commands { subscriber.Value.Remove(e.Channel); } - await e.Channel.SendMessage(":ok:").ConfigureAwait(false); + await channel.SendMessageAsync(":ok:").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Administration/Commands/CustomReactionsCommands.cs b/src/NadekoBot/_Modules/Administration/Commands/CustomReactionsCommands.cs index 2725e196..d0db8dee 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/CustomReactionsCommands.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/CustomReactionsCommands.cs @@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Administration.Commands var message = e.GetArg("message")?.Trim(); if (string.IsNullOrWhiteSpace(message)) { - await e.Channel.SendMessage($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false); + await channel.SendMessageAsync($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false); return; } if (NadekoBot.Config.CustomReactions.ContainsKey(name)) @@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands else NadekoBot.Config.CustomReactions.Add(name, new System.Collections.Generic.List() { message }); await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"Added {name} : {message}").ConfigureAwait(false); + await channel.SendMessageAsync($"Added {name} : {message}").ConfigureAwait(false); }); @@ -69,12 +69,12 @@ namespace NadekoBot.Modules.Administration.Commands var cmds = GetCustomsOnPage(num - 1); if (!cmds.Any()) { - await e.Channel.SendMessage("`There are no custom reactions.`"); + await channel.SendMessageAsync("`There are no custom reactions.`"); } else { string result = SearchHelper.ShowInPrettyCode(cmds, s => $"{s,-25}"); //People prefer starting with 1 - await e.Channel.SendMessage($"`Showing page {num}:`\n" + result).ConfigureAwait(false); + await channel.SendMessageAsync($"`Showing page {num}:`\n" + result).ConfigureAwait(false); } }); @@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands return; if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) { - await e.Channel.SendMessage("`Can't find that custom reaction.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Can't find that custom reaction.`").ConfigureAwait(false); return; } var items = NadekoBot.Config.CustomReactions[name]; @@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration.Commands { message.AppendLine($"[{i++}] " + Format.Code(Format.Escape(reaction))); } - await e.Channel.SendMessage(message.ToString()); + await channel.SendMessageAsync(message.ToString()); }); cgb.CreateCommand(Prefix + "editcustreact") @@ -127,21 +127,21 @@ namespace NadekoBot.Modules.Administration.Commands if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) { - await e.Channel.SendMessage("`Could not find given commandname`").ConfigureAwait(false); + await channel.SendMessageAsync("`Could not find given commandname`").ConfigureAwait(false); return; } int index; if (!int.TryParse(indexstr, out index) || index < 1 || index > NadekoBot.Config.CustomReactions[name].Count) { - await e.Channel.SendMessage("`Invalid index.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Invalid index.`").ConfigureAwait(false); return; } index = index - 1; NadekoBot.Config.CustomReactions[name][index] = msg; await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "delcustreact") @@ -157,7 +157,7 @@ namespace NadekoBot.Modules.Administration.Commands return; if (!NadekoBot.Config.CustomReactions.ContainsKey(name)) { - await e.Channel.SendMessage("Could not find given commandname").ConfigureAwait(false); + await channel.SendMessageAsync("Could not find given commandname").ConfigureAwait(false); return; } string message = ""; @@ -167,7 +167,7 @@ namespace NadekoBot.Modules.Administration.Commands index = index - 1; if (index < 0 || index > NadekoBot.Config.CustomReactions[name].Count) { - await e.Channel.SendMessage("Given index was out of range").ConfigureAwait(false); + await channel.SendMessageAsync("Given index was out of range").ConfigureAwait(false); return; } @@ -184,7 +184,7 @@ namespace NadekoBot.Modules.Administration.Commands message = $"Deleted custom reaction: `{name}`"; } await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage(message).ConfigureAwait(false); + await channel.SendMessageAsync(message).ConfigureAwait(false); }); } diff --git a/src/NadekoBot/_Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/_Modules/Administration/Commands/LogCommand.cs index b5f19eb1..c5f144b5 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/LogCommand.cs @@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Administration.Commands var usr = e.Message.MentionedUsers.FirstOrDefault(u => u != e.User); if (usr?.Status != UserStatus.Offline) return; - await e.Channel.SendMessage($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false); + await channel.SendMessageAsync($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false); await usr.SendMessage( $"User `{e.User.Name}` mentioned you on " + $"`{e.Server.Name}` server while you were offline.\n" + @@ -383,10 +383,10 @@ namespace NadekoBot.Modules.Administration.Commands specificConfig.SendPrivateMessageOnMention = !specificConfig.SendPrivateMessageOnMention; if (specificConfig.SendPrivateMessageOnMention) - await e.Channel.SendMessage(":ok: I will send private messages " + + await channel.SendMessageAsync(":ok: I will send private messages " + "to mentioned offline users.").ConfigureAwait(false); else - await e.Channel.SendMessage(":ok: I won't send private messages " + + await channel.SendMessageAsync(":ok: I won't send private messages " + "to mentioned offline users anymore.").ConfigureAwait(false); }); @@ -400,7 +400,7 @@ namespace NadekoBot.Modules.Administration.Commands if (chId == null) { SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = e.Channel.Id; - await e.Channel.SendMessage($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false); + await channel.SendMessageAsync($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false); return; } Channel ch; @@ -408,7 +408,7 @@ namespace NadekoBot.Modules.Administration.Commands return; SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = null; - await e.Channel.SendMessage($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false); + await channel.SendMessageAsync($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false); }); @@ -421,12 +421,12 @@ namespace NadekoBot.Modules.Administration.Commands var config = SpecificConfigurations.Default.Of(e.Server.Id); if (config.LogserverIgnoreChannels.Remove(e.Channel.Id)) { - await e.Channel.SendMessage($"`{Prefix}logserver will stop ignoring this channel.`"); + await channel.SendMessageAsync($"`{Prefix}logserver will stop ignoring this channel.`"); } else { config.LogserverIgnoreChannels.Add(e.Channel.Id); - await e.Channel.SendMessage($"`{Prefix}logserver will ignore this channel.`"); + await channel.SendMessageAsync($"`{Prefix}logserver will ignore this channel.`"); } }); @@ -439,11 +439,11 @@ namespace NadekoBot.Modules.Administration.Commands if (chId == null) { SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = e.Channel.Id; - await e.Channel.SendMessage($"**User presence notifications enabled.**").ConfigureAwait(false); + await channel.SendMessageAsync($"**User presence notifications enabled.**").ConfigureAwait(false); return; } SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = null; - await e.Channel.SendMessage($"**User presence notifications disabled.**").ConfigureAwait(false); + await channel.SendMessageAsync($"**User presence notifications disabled.**").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "voicepresence") @@ -460,23 +460,23 @@ namespace NadekoBot.Modules.Administration.Commands { config.VoiceChannelLog.TryAdd(voiceChannel.Id, e.Channel.Id); } - await e.Channel.SendMessage("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false); + await channel.SendMessageAsync("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false); return; } if (e.User.VoiceChannel == null) { - await e.Channel.SendMessage("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false); return; } ulong throwaway; if (!config.VoiceChannelLog.TryRemove(e.User.VoiceChannel.Id, out throwaway)) { config.VoiceChannelLog.TryAdd(e.User.VoiceChannel.Id, e.Channel.Id); - await e.Channel.SendMessage($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); } else - await e.Channel.SendMessage($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/_Modules/Administration/Commands/MessageRepeater.cs index e87f5555..99f8ab4f 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/MessageRepeater.cs @@ -64,7 +64,7 @@ namespace NadekoBot.Modules.Administration.Commands Repeater rep; if (!repeaters.TryGetValue(e.Server, out rep)) { - await e.Channel.SendMessage("`No repeating message found on this server.`"); + await channel.SendMessageAsync("`No repeating message found on this server.`"); return; } @@ -90,13 +90,13 @@ namespace NadekoBot.Modules.Administration.Commands if (!repeaters.TryRemove(e.Server, out rep)) return; rep.MessageTimer.Stop(); - await e.Channel.SendMessage("Repeating disabled").ConfigureAwait(false); + await channel.SendMessageAsync("Repeating disabled").ConfigureAwait(false); return; } int minutes; if (!int.TryParse(minutesStr, out minutes) || minutes < 1 || minutes > 1440) { - await e.Channel.SendMessage("Invalid value").ConfigureAwait(false); + await channel.SendMessageAsync("Invalid value").ConfigureAwait(false); return; } @@ -117,7 +117,7 @@ namespace NadekoBot.Modules.Administration.Commands repeater.MessageTimer.Stop(); repeater.MessageTimer.Start(); - await e.Channel.SendMessage(String.Format("👌 Repeating `{0}` every " + + await channel.SendMessageAsync(String.Format("👌 Repeating `{0}` every " + "**{1}** minutes on {2} channel.", repeater.RepeatingMessage, minutes, repeater.RepeatingChannel)) .ConfigureAwait(false); diff --git a/src/NadekoBot/_Modules/Administration/Commands/PlayingRotate.cs b/src/NadekoBot/_Modules/Administration/Commands/PlayingRotate.cs index c1caa0bc..cc48fb10 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/PlayingRotate.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/PlayingRotate.cs @@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands finally { playingPlaceholderLock.Release(); } - await e.Channel.SendMessage($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false); + await channel.SendMessageAsync($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false); }; internal override void Init(CommandGroupBuilder cgb) @@ -121,7 +121,7 @@ namespace NadekoBot.Modules.Administration.Commands { playingPlaceholderLock.Release(); } - await e.Channel.SendMessage("🆗 `Added a new playing string.`").ConfigureAwait(false); + await channel.SendMessageAsync("🆗 `Added a new playing string.`").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "listplaying") @@ -131,14 +131,14 @@ namespace NadekoBot.Modules.Administration.Commands .Do(async e => { if (NadekoBot.Config.RotatingStatuses.Count == 0) - await e.Channel.SendMessage("`There are no playing strings. " + + await channel.SendMessageAsync("`There are no playing strings. " + "Add some with .addplaying [text] command.`").ConfigureAwait(false); var sb = new StringBuilder(); for (var i = 0; i < NadekoBot.Config.RotatingStatuses.Count; i++) { sb.AppendLine($"`{i + 1}.` {NadekoBot.Config.RotatingStatuses[i]}"); } - await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "removeplaying") @@ -160,7 +160,7 @@ namespace NadekoBot.Modules.Administration.Commands await ConfigHandler.SaveConfig().ConfigureAwait(false); } finally { playingPlaceholderLock.Release(); } - await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false); + await channel.SendMessageAsync($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/_Modules/Administration/Commands/RatelimitCommand.cs index d1f62bd9..89f26aab 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/RatelimitCommand.cs @@ -48,12 +48,12 @@ namespace NadekoBot.Modules.Administration.Commands ConcurrentDictionary throwaway; if (RatelimitingChannels.TryRemove(e.Channel.Id, out throwaway)) { - await e.Channel.SendMessage("Slow mode disabled.").ConfigureAwait(false); + await channel.SendMessageAsync("Slow mode disabled.").ConfigureAwait(false); return; } if (RatelimitingChannels.TryAdd(e.Channel.Id, new ConcurrentDictionary())) { - await e.Channel.SendMessage("Slow mode initiated. " + + await channel.SendMessageAsync("Slow mode initiated. " + "Users can't send more than 1 message every 5 seconds.") .ConfigureAwait(false); } diff --git a/src/NadekoBot/_Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/_Modules/Administration/Commands/SelfAssignedRolesCommand.cs index 8e5e54fb..a7fafcb6 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -40,7 +40,7 @@ namespace NadekoBot.Modules.Administration.Commands msg.AppendLine($":ok:Role **{role.Name}** added to the list."); } } - await e.Channel.SendMessage(msg.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "rsar") @@ -55,17 +55,17 @@ namespace NadekoBot.Modules.Administration.Commands var role = e.Server.FindRoles(roleName).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false); return; } var config = SpecificConfigurations.Default.Of(e.Server.Id); if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) { - await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false); return; } config.ListOfSelfAssignableRoles.Remove(role.Id); - await e.Channel.SendMessage($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false); + await channel.SendMessageAsync($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "lsar") @@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Administration.Commands { config.ListOfSelfAssignableRoles.Remove(id); } - await e.Channel.SendMessage(msg.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false); }); @@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Administration.Commands var config = SpecificConfigurations.Default.Of(e.Server.Id); config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles; string exl = config.ExclusiveSelfAssignedRoles ? "exclusive" : "not exclusive"; - await e.Channel.SendMessage("Self assigned roles are now " + exl); + await channel.SendMessageAsync("Self assigned roles are now " + exl); }); cgb.CreateCommand(Module.Prefix + "iam") @@ -122,24 +122,24 @@ namespace NadekoBot.Modules.Administration.Commands var role = e.Server.FindRoles(roleName).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false); return; } var config = SpecificConfigurations.Default.Of(e.Server.Id); if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) { - await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false); return; } if (e.User.HasRole(role)) { - await e.Channel.SendMessage($":anger:You already have {role.Name} role.").ConfigureAwait(false); + await channel.SendMessageAsync($":anger:You already have {role.Name} role.").ConfigureAwait(false); return; } var sameRoles = e.User.Roles.Where(r => config.ListOfSelfAssignableRoles.Contains(r.Id)); if (config.ExclusiveSelfAssignedRoles && sameRoles.Any()) { - await e.Channel.SendMessage($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false); + await channel.SendMessageAsync($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false); return; } try @@ -151,10 +151,10 @@ namespace NadekoBot.Modules.Administration.Commands } catch (Exception ex) { - await e.Channel.SendMessage($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); + await channel.SendMessageAsync($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); return; } - var msg = await e.Channel.SendMessage($":ok:You now have {role.Name} role.").ConfigureAwait(false); + var msg = await channel.SendMessageAsync($":ok:You now have {role.Name} role.").ConfigureAwait(false); await Task.Delay(3000).ConfigureAwait(false); await msg.Delete().ConfigureAwait(false); try @@ -178,22 +178,22 @@ namespace NadekoBot.Modules.Administration.Commands var role = e.Server.FindRoles(roleName).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage(":anger:That role does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false); return; } var config = SpecificConfigurations.Default.Of(e.Server.Id); if (!config.ListOfSelfAssignableRoles.Contains(role.Id)) { - await e.Channel.SendMessage(":anger:That role is not self-assignable.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false); return; } if (!e.User.HasRole(role)) { - await e.Channel.SendMessage($":anger:You don't have {role.Name} role.").ConfigureAwait(false); + await channel.SendMessageAsync($":anger:You don't have {role.Name} role.").ConfigureAwait(false); return; } await e.User.RemoveRoles(role).ConfigureAwait(false); - var msg = await e.Channel.SendMessage($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false); + var msg = await channel.SendMessageAsync($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false); await Task.Delay(3000).ConfigureAwait(false); await msg.Delete().ConfigureAwait(false); try diff --git a/src/NadekoBot/_Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/_Modules/Administration/Commands/SelfCommands.cs index f8019ac9..b1effafb 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/SelfCommands.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Administration.Commands NadekoBot.Client.FindServers(arg).FirstOrDefault(); if (server == null) { - await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); + await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false); return; } if (!server.IsOwner) diff --git a/src/NadekoBot/_Modules/Administration/Commands/ServerGreetCommand.cs b/src/NadekoBot/_Modules/Administration/Commands/ServerGreetCommand.cs index b2cdf3b4..85bb1ba3 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/ServerGreetCommand.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/ServerGreetCommand.cs @@ -226,9 +226,9 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (ann.ToggleDelete()) - await e.Channel.SendMessage("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false); else - await e.Channel.SendMessage("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "greet") @@ -239,9 +239,9 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (ann.ToggleGreet(e.Channel.Id)) - await e.Channel.SendMessage("Greet announcements enabled on this channel.").ConfigureAwait(false); + await channel.SendMessageAsync("Greet announcements enabled on this channel.").ConfigureAwait(false); else - await e.Channel.SendMessage("Greet announcements disabled.").ConfigureAwait(false); + await channel.SendMessageAsync("Greet announcements disabled.").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "greetmsg") @@ -253,15 +253,15 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) { - await e.Channel.SendMessage("`Current greet message:` " + ann.GreetText); + await channel.SendMessageAsync("`Current greet message:` " + ann.GreetText); return; } ann.GreetText = e.GetArg("msg"); - await e.Channel.SendMessage("New greet message set.").ConfigureAwait(false); + await channel.SendMessageAsync("New greet message set.").ConfigureAwait(false); if (!ann.Greet) - await e.Channel.SendMessage("Enable greet messsages by typing `.greet`").ConfigureAwait(false); + await channel.SendMessageAsync("Enable greet messsages by typing `.greet`").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "bye") @@ -272,9 +272,9 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (ann.ToggleBye(e.Channel.Id)) - await e.Channel.SendMessage("Bye announcements enabled on this channel.").ConfigureAwait(false); + await channel.SendMessageAsync("Bye announcements enabled on this channel.").ConfigureAwait(false); else - await e.Channel.SendMessage("Bye announcements disabled.").ConfigureAwait(false); + await channel.SendMessageAsync("Bye announcements disabled.").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "byemsg") @@ -286,14 +286,14 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) { - await e.Channel.SendMessage("`Current bye message:` " + ann.ByeText); + await channel.SendMessageAsync("`Current bye message:` " + ann.ByeText); return; } ann.ByeText = e.GetArg("msg"); - await e.Channel.SendMessage("New bye message set.").ConfigureAwait(false); + await channel.SendMessageAsync("New bye message set.").ConfigureAwait(false); if (!ann.Bye) - await e.Channel.SendMessage("Enable bye messsages by typing `.bye`.").ConfigureAwait(false); + await channel.SendMessageAsync("Enable bye messsages by typing `.bye`.").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "byepm") @@ -305,11 +305,11 @@ namespace NadekoBot.Modules.Administration.Commands if (ann.ToggleByePM()) - await e.Channel.SendMessage("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false); + await channel.SendMessageAsync("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false); else - await e.Channel.SendMessage("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false); + await channel.SendMessageAsync("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false); if (!ann.Bye) - await e.Channel.SendMessage("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false); + await channel.SendMessageAsync("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "greetpm") @@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration.Commands var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); if (ann.ToggleGreetPM()) - await e.Channel.SendMessage("Greet messages will be sent in a PM from now on.").ConfigureAwait(false); + await channel.SendMessageAsync("Greet messages will be sent in a PM from now on.").ConfigureAwait(false); else - await e.Channel.SendMessage("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false); + await channel.SendMessageAsync("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false); if (!ann.Greet) - await e.Channel.SendMessage("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false); + await channel.SendMessageAsync("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Administration/Commands/VoicePlusTextCommand.cs b/src/NadekoBot/_Modules/Administration/Commands/VoicePlusTextCommand.cs index 4c6a948c..507706a1 100644 --- a/src/NadekoBot/_Modules/Administration/Commands/VoicePlusTextCommand.cs +++ b/src/NadekoBot/_Modules/Administration/Commands/VoicePlusTextCommand.cs @@ -95,7 +95,7 @@ namespace NadekoBot.Modules.Administration.Commands { if (!e.Server.CurrentUser.ServerPermissions.ManageChannels) { - await e.Channel.SendMessage("`I have insufficient permission to do that.`"); + await channel.SendMessageAsync("`I have insufficient permission to do that.`"); return; } @@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Administration.Commands await Task.Delay(500); } - await e.Channel.SendMessage("`Done.`"); + await channel.SendMessageAsync("`Done.`"); }); cgb.CreateCommand(Module.Prefix + "voice+text") @@ -139,24 +139,24 @@ namespace NadekoBot.Modules.Administration.Commands } catch { - await e.Channel.SendMessage( + await channel.SendMessageAsync( ":anger: Error: Most likely i don't have permissions to do this.") .ConfigureAwait(false); return; } } - await e.Channel.SendMessage("Successfuly removed voice + text feature.").ConfigureAwait(false); + await channel.SendMessageAsync("Successfuly removed voice + text feature.").ConfigureAwait(false); return; } config.VoicePlusTextEnabled = true; - await e.Channel.SendMessage("Successfuly enabled voice + text feature. " + + await channel.SendMessageAsync("Successfuly enabled voice + text feature. " + "**Make sure the bot has manage roles and manage channels permissions**") .ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage(ex.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(ex.ToString()).ConfigureAwait(false); } }); } diff --git a/src/NadekoBot/_Modules/ClashOfClans/ClashOfClansModule.cs b/src/NadekoBot/_Modules/ClashOfClans/ClashOfClansModule.cs deleted file mode 100644 index 449c4da6..00000000 --- a/src/NadekoBot/_Modules/ClashOfClans/ClashOfClansModule.cs +++ /dev/null @@ -1,418 +0,0 @@ -using Discord.Commands; -using Discord.Modules; -using NadekoBot.Classes.ClashOfClans; -using NadekoBot.Modules.Permissions.Classes; -using Newtonsoft.Json; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.ClashOfClans -{ - internal class ClashOfClansModule : DiscordModule - { - public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.ClashOfClans; - - public static ConcurrentDictionary> ClashWars { get; set; } = new ConcurrentDictionary>(); - - private readonly object writeLock = new object(); - - public ClashOfClansModule() - { - NadekoBot.OnReady += () => Task.Run(async () => - { - if (File.Exists("data/clashofclans/wars.json")) - { - try - { - var content = File.ReadAllText("data/clashofclans/wars.json"); - - var dict = JsonConvert.DeserializeObject>>(content); - - foreach (var cw in dict) - { - cw.Value.ForEach(war => - { - war.Channel = NadekoBot.Client.GetServer(war.ServerId)?.GetChannel(war.ChannelId); - if (war.Channel == null) - { - cw.Value.Remove(war); - } - } - ); - } - //urgh - ClashWars = new ConcurrentDictionary>(dict); - } - catch (Exception e) - { - Console.WriteLine("Could not load coc wars: " + e.Message); - } - - - } - //Can't this be disabled if the modules is disabled too :) - var callExpire = new TimeSpan(2, 0, 0); - var warExpire = new TimeSpan(23, 0, 0); - while (true) - { - try - { - var hash = ClashWars.GetHashCode(); - foreach (var cw in ClashWars) - { - foreach (var war in cw.Value) - { - await CheckWar(callExpire, war); - } - List newVal = new List(); - foreach (var w in cw.Value) - { - //We add when A: the war is not ended - if (w.WarState != WarState.Ended) - { - //and B: the war has not expired - if ((w.WarState == WarState.Started && DateTime.UtcNow - w.StartedAt <= warExpire) || w.WarState == WarState.Created) - { - newVal.Add(w); - } - } - } - //var newVal = cw.Value.Where(w => !(w.Ended || DateTime.UtcNow - w.StartedAt >= warExpire)).ToList(); - foreach (var exWar in cw.Value.Except(newVal)) - { - await exWar.Channel.SendMessage($"War against {exWar.EnemyClan} ({exWar.Size}v{exWar.Size}) has ended"); - } - - if (newVal.Count == 0) - { - List obj; - ClashWars.TryRemove(cw.Key, out obj); - } - else - { - ClashWars.AddOrUpdate(cw.Key, newVal, (x, s) => newVal); - } - } - if (hash != ClashWars.GetHashCode()) //something changed - { - Save(); - } - - - } - catch { } - await Task.Delay(5000); - } - }); - } - - private static void Save() - { - try - { - Directory.CreateDirectory("data/clashofclans"); - File.WriteAllText("data/clashofclans/wars.json", JsonConvert.SerializeObject(ClashWars, Formatting.Indented)); - } - catch (Exception e) - { - Console.WriteLine(e.Message); - } - } - - private static async Task CheckWar(TimeSpan callExpire, ClashWar war) - { - var Bases = war.Bases; - for (var i = 0; i < Bases.Length; i++) - { - if (Bases[i] == null) continue; - if (!Bases[i].BaseDestroyed && DateTime.UtcNow - Bases[i].TimeAdded >= callExpire) - { - await war.Channel.SendMessage($"❗🔰**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false); - Bases[i] = null; - } - } - } - - #region commands - public override void Install(ModuleManager manager) - { - manager.CreateCommands("", cgb => - { - - cgb.AddCheck(PermissionChecker.Instance); - - cgb.CreateCommand(Prefix + "createwar") - .Alias(Prefix + "cw") - .Description($"Creates a new war by specifying a size (>10 and multiple of 5) and enemy clan name. | `{Prefix}cw 15 The Enemy Clan`") - .Parameter("size") - .Parameter("enemy_clan", ParameterType.Unparsed) - .Do(async e => - { - if (!e.User.ServerPermissions.ManageChannels) - return; - var enemyClan = e.GetArg("enemy_clan"); - if (string.IsNullOrWhiteSpace(enemyClan)) - { - return; - } - int size; - if (!int.TryParse(e.GetArg("size"), out size) || size < 10 || size > 50 || size % 5 != 0) - { - await e.Channel.SendMessage("💢🔰 Not a Valid war size").ConfigureAwait(false); - return; - } - List wars; - if (!ClashWars.TryGetValue(e.Server.Id, out wars)) - { - wars = new List(); - if (!ClashWars.TryAdd(e.Server.Id, wars)) - return; - } - - - var cw = new ClashWar(enemyClan, size, e.Server.Id, e.Channel.Id); - //cw.Start(); - - wars.Add(cw); - await e.Channel.SendMessage($"❗🔰**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); - Save(); - //war with the index X started. - }); - - cgb.CreateCommand(Prefix + "startwar") - .Alias(Prefix + "sw") - .Description("Starts a war with a given number. | `{Prefix}sw 15`") - .Parameter("number", ParameterType.Required) - .Do(async e => - { - var warsInfo = GetInfo(e); - if (warsInfo == null) - { - await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false); - return; - } - var war = warsInfo.Item1[warsInfo.Item2]; - try - { - war.Start(); - await e.Channel.SendMessage($"🔰**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false); - } - catch - { - await e.Channel.SendMessage($"🔰**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false); - } - Save(); - }); - - cgb.CreateCommand(Prefix + "listwar") - .Alias(Prefix + "lw") - .Description($"Shows the active war claims by a number. Shows all wars in a short way if no number is specified. | `{Prefix}lw [war_number] or {Prefix}lw`") - .Parameter("number", ParameterType.Optional) - .Do(async e => - { - // if number is null, print all wars in a short way - if (string.IsNullOrWhiteSpace(e.GetArg("number"))) - { - //check if there are any wars - List wars = null; - ClashWars.TryGetValue(e.Server.Id, out wars); - if (wars == null || wars.Count == 0) - { - await e.Channel.SendMessage("🔰 **No active wars.**").ConfigureAwait(false); - return; - } - - var sb = new StringBuilder(); - sb.AppendLine("🔰 **LIST OF ACTIVE WARS**"); - sb.AppendLine("**-------------------------**"); - for (var i = 0; i < wars.Count; i++) - { - sb.AppendLine($"**#{i + 1}.** `Enemy:` **{wars[i].EnemyClan}**"); - sb.AppendLine($"\t\t`Size:` **{wars[i].Size} v {wars[i].Size}**"); - sb.AppendLine("**-------------------------**"); - } - await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); - return; - - } - //if number is not null, print the war needed - var warsInfo = GetInfo(e); - if (warsInfo == null) - { - await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false); - return; - } - await e.Channel.SendMessage(warsInfo.Item1[warsInfo.Item2].ToString()).ConfigureAwait(false); - }); - - cgb.CreateCommand(Prefix + "claim") - .Alias(Prefix + "call") - .Alias(Prefix + "c") - .Description($"Claims a certain base from a certain war. You can supply a name in the third optional argument to claim in someone else's place. | `{Prefix}call [war_number] [base_number] [optional_other_name]`") - .Parameter("number") - .Parameter("baseNumber") - .Parameter("other_name", ParameterType.Unparsed) - .Do(async e => - { - var warsInfo = GetInfo(e); - if (warsInfo == null || warsInfo.Item1.Count == 0) - { - await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false); - return; - } - int baseNum; - if (!int.TryParse(e.GetArg("baseNumber"), out baseNum)) - { - await e.Channel.SendMessage("💢🔰 **Invalid base number.**").ConfigureAwait(false); - return; - } - var usr = - string.IsNullOrWhiteSpace(e.GetArg("other_name")) ? - e.User.Name : - e.GetArg("other_name"); - try - { - var war = warsInfo.Item1[warsInfo.Item2]; - war.Call(usr, baseNum - 1); - await e.Channel.SendMessage($"🔰**{usr}** claimed a base #{baseNum} for a war against {war.ShortPrint()}").ConfigureAwait(false); - Save(); - } - catch (Exception ex) - { - await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false); - } - }); - - cgb.CreateCommand(Prefix + "claimfinish") - .Alias(Prefix + "cf") - .Alias(Prefix + "cf3") - .Alias(Prefix + "claimfinish3") - .Description($"Finish your claim with 3 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`") - .Parameter("number", ParameterType.Required) - .Parameter("other_name", ParameterType.Unparsed) - .Do(e => FinishClaim(e)); - - cgb.CreateCommand(Prefix + "claimfinish2") - .Alias(Prefix + "cf2") - .Description($"Finish your claim with 2 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`") - .Parameter("number", ParameterType.Required) - .Parameter("other_name", ParameterType.Unparsed) - .Do(e => FinishClaim(e, 2)); - - cgb.CreateCommand(Prefix + "claimfinish1") - .Alias(Prefix + "cf1") - .Description($"Finish your claim with 1 stars if you destroyed a base. Optional second argument finishes for someone else. | `{Prefix}cf [war_number] [optional_other_name]`") - .Parameter("number", ParameterType.Required) - .Parameter("other_name", ParameterType.Unparsed) - .Do(e => FinishClaim(e, 1)); - - cgb.CreateCommand(Prefix + "unclaim") - .Alias(Prefix + "uncall") - .Alias(Prefix + "uc") - .Description($"Removes your claim from a certain war. Optional second argument denotes a person in whose place to unclaim | `{Prefix}uc [war_number] [optional_other_name]`") - .Parameter("number", ParameterType.Required) - .Parameter("other_name", ParameterType.Unparsed) - .Do(async e => - { - var warsInfo = GetInfo(e); - if (warsInfo == null || warsInfo.Item1.Count == 0) - { - await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false); - return; - } - var usr = - string.IsNullOrWhiteSpace(e.GetArg("other_name")) ? - e.User.Name : - e.GetArg("other_name"); - try - { - var war = warsInfo.Item1[warsInfo.Item2]; - var baseNumber = war.Uncall(usr); - await e.Channel.SendMessage($"🔰 @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false); - Save(); - } - catch (Exception ex) - { - await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false); - } - }); - - cgb.CreateCommand(Prefix + "endwar") - .Alias(Prefix + "ew") - .Description($"Ends the war with a given index. | `{Prefix}ew [war_number]`") - .Parameter("number") - .Do(async e => - { - var warsInfo = GetInfo(e); - if (warsInfo == null) - { - await e.Channel.SendMessage("💢🔰 That war does not exist.").ConfigureAwait(false); - return; - } - warsInfo.Item1[warsInfo.Item2].End(); - await e.Channel.SendMessage($"❗🔰**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false); - - var size = warsInfo.Item1[warsInfo.Item2].Size; - warsInfo.Item1.RemoveAt(warsInfo.Item2); - Save(); - }); - }); - - } - #endregion - - - private async Task FinishClaim(CommandEventArgs e, int stars = 3) - { - var warInfo = GetInfo(e); - if (warInfo == null || warInfo.Item1.Count == 0) - { - await e.Channel.SendMessage("💢🔰 **That war does not exist.**").ConfigureAwait(false); - return; - } - var usr = - string.IsNullOrWhiteSpace(e.GetArg("other_name")) ? - e.User.Name : - e.GetArg("other_name"); - - var war = warInfo.Item1[warInfo.Item2]; - try - { - var baseNum = war.FinishClaim(usr, stars); - await e.Channel.SendMessage($"❗🔰{e.User.Mention} **DESTROYED** a base #{baseNum + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); - Save(); - } - catch (Exception ex) - { - await e.Channel.SendMessage($"💢🔰 {ex.Message}").ConfigureAwait(false); - } - } - - private static Tuple, int> GetInfo(CommandEventArgs e) - { - //check if there are any wars - List wars = null; - ClashWars.TryGetValue(e.Server.Id, out wars); - if (wars == null || wars.Count == 0) - { - return null; - } - // get the number of the war - int num; - if (string.IsNullOrWhiteSpace(e.GetArg("number"))) - num = 0; - else if (!int.TryParse(e.GetArg("number"), out num) || num > wars.Count) - { - return null; - } - num -= 1; - //get the actual war - return new Tuple, int>(wars, num); - } - } -} diff --git a/src/NadekoBot/_Modules/Conversations/Commands/RipCommand.cs b/src/NadekoBot/_Modules/Conversations/Commands/RipCommand.cs deleted file mode 100644 index 9c4842bf..00000000 --- a/src/NadekoBot/_Modules/Conversations/Commands/RipCommand.cs +++ /dev/null @@ -1,120 +0,0 @@ -using NadekoBot.Classes; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Discord.Commands; -using System.Drawing; -using System.Drawing.Drawing2D; -using NadekoBot.Properties; -using System.IO; -using System.Drawing.Imaging; -using NadekoBot.Extensions; - -namespace NadekoBot.Modules.Conversations.Commands -{ - class RipCommand : DiscordCommand - { - public RipCommand(DiscordModule module) : base(module) - { - } - - internal override void Init(CommandGroupBuilder cgb) - { - cgb.CreateCommand("rip") - .Description("Shows a grave image of someone with a start year | `@NadekoBot rip @Someone 2000`") - .Parameter("user", ParameterType.Required) - .Parameter("year", ParameterType.Optional) - .Do(async e => - { - if (string.IsNullOrWhiteSpace(e.GetArg("user"))) - return; - var usr = e.Channel.FindUsers(e.GetArg("user")).FirstOrDefault(); - var text = ""; - Stream file; - if (usr == null) - { - text = e.GetArg("user"); - file = RipName(text, string.IsNullOrWhiteSpace(e.GetArg("year")) - ? null - : e.GetArg("year")); - } - else - { - var avatar = await GetAvatar(usr.AvatarUrl); - text = usr.Name; - file = RipUser(text, avatar, string.IsNullOrWhiteSpace(e.GetArg("year")) - ? null - : e.GetArg("year")); - } - await e.Channel.SendFile("ripzor_m8.png", - file); - }); - } - - - /// - /// Create a RIP image of the given name and avatar, with an optional year - /// - /// - /// - /// - /// - public Stream RipUser(string name, Image avatar, string year = null) - { - var bm = Resources.rip; - int width = 300; - var fontSize = width / name.Length -2; - if (fontSize > 20) fontSize = 20; - var g = Graphics.FromImage(bm); - Font nameFont = new Font("Comic Sans MS", fontSize, FontStyle.Bold, GraphicsUnit.Pixel); - SizeF nameSize = g.MeasureString(name, nameFont); - g.DrawString(name, new Font("Comic Sans MS", fontSize, FontStyle.Bold), Brushes.Black, (bm.Width /2 - 8) - (nameSize.Width /2), 243 - nameSize.Height); - g.DrawString((year ?? "?") + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 240); - - g.DrawImage(avatar, 80, 135); - g.DrawImage((Image)Resources.rose_overlay, 0, 0); - g.Flush(); - g.Dispose(); - - return bm.ToStream(ImageFormat.Png); - } - - public Stream RipName(string name, string year = null) - { - var bm = Resources.rip; - int width = 190; - var offset = name.Length * 5; - var fontSize = width / name.Length; - if (fontSize > 20) fontSize = 20; - var g = Graphics.FromImage(bm); - Font nameFont = new Font("Comic Sans MS", fontSize, FontStyle.Bold, GraphicsUnit.Pixel); - SizeF nameSize = g.MeasureString(name, nameFont); - g.DrawString(name, nameFont, Brushes.Black, (bm.Width / 2) - (nameSize.Width / 2), 200); - g.DrawString((year ?? "?") + " - " + DateTime.Now.Year, new Font("Consolas", 12, FontStyle.Bold), Brushes.Black, 80, 235); - g.Flush(); - g.Dispose(); - - return bm.ToStream(ImageFormat.Png); - } - - public static async Task GetAvatar(string url) - { - var stream = await SearchHelper.GetResponseStreamAsync(url); - Bitmap bmp = new Bitmap(100, 100); - using (GraphicsPath gp = new GraphicsPath()) - { - gp.AddEllipse(0, 0, bmp.Width, bmp.Height); - using (Graphics gr = Graphics.FromImage(bmp)) - { - gr.SetClip(gp); - gr.DrawImage(Image.FromStream(stream), Point.Empty); - - } - } - return bmp; - - } - } -} diff --git a/src/NadekoBot/_Modules/Conversations/Conversations.cs b/src/NadekoBot/_Modules/Conversations/Conversations.cs deleted file mode 100644 index a3611d0e..00000000 --- a/src/NadekoBot/_Modules/Conversations/Conversations.cs +++ /dev/null @@ -1,224 +0,0 @@ -using Discord; -using Discord.Commands; -using Discord.Modules; -using NadekoBot.DataModels; -using NadekoBot.Extensions; -using NadekoBot.Modules.Conversations.Commands; -using NadekoBot.Modules.Permissions.Classes; -using System; -using System.Diagnostics; -using System.IO; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Conversations -{ - internal class Conversations : DiscordModule - { - private const string firestr = "🔥 ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้ 🔥"; - public Conversations() - { - commands.Add(new RipCommand(this)); - } - - public override string Prefix { get; } = String.Format(NadekoBot.Config.CommandPrefixes.Conversations, NadekoBot.Creds.BotId); - - public override void Install(ModuleManager manager) - { - var rng = new Random(); - - manager.CreateCommands("", cgb => - { - cgb.AddCheck(PermissionChecker.Instance); - - cgb.CreateCommand("..") - .Description("Adds a new quote with the specified name (single word) and message (no limit). | `.. abc My message`") - .Parameter("keyword", ParameterType.Required) - .Parameter("text", ParameterType.Unparsed) - .Do(async e => - { - var text = e.GetArg("text"); - if (string.IsNullOrWhiteSpace(text)) - return; - await Task.Run(() => - Classes.DbHandler.Instance.Connection.Insert(new DataModels.UserQuote() - { - DateAdded = DateTime.Now, - Keyword = e.GetArg("keyword").ToLowerInvariant(), - Text = text, - UserName = e.User.Name, - })).ConfigureAwait(false); - - await e.Channel.SendMessage("`New quote added.`").ConfigureAwait(false); - }); - - cgb.CreateCommand("...") - .Description("Shows a random quote with a specified name. | `... abc`") - .Parameter("keyword", ParameterType.Required) - .Do(async e => - { - var keyword = e.GetArg("keyword")?.ToLowerInvariant(); - if (string.IsNullOrWhiteSpace(keyword)) - return; - - var quote = - Classes.DbHandler.Instance.GetRandom( - uqm => uqm.Keyword == keyword); - - if (quote != null) - await e.Channel.SendMessage($"📣 {quote.Text}").ConfigureAwait(false); - else - await e.Channel.SendMessage("💢`No quote found.`").ConfigureAwait(false); - }); - - cgb.CreateCommand("..qdel") - .Alias("..quotedelete") - .Description("Deletes all quotes with the specified keyword. You have to either be bot owner or the creator of the quote to delete it. | `..qdel abc`") - .Parameter("quote", ParameterType.Required) - .Do(async e => - { - var text = e.GetArg("quote")?.Trim(); - if (string.IsNullOrWhiteSpace(text)) - return; - await Task.Run(() => - { - if (NadekoBot.IsOwner(e.User.Id)) - Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text); - else - Classes.DbHandler.Instance.DeleteWhere(uq => uq.Keyword == text && uq.UserName == e.User.Name); - }).ConfigureAwait(false); - - await e.Channel.SendMessage("`Done.`").ConfigureAwait(false); - }); - }); - - manager.CreateCommands(NadekoBot.BotMention, cgb => - { - var client = manager.Client; - - cgb.AddCheck(PermissionChecker.Instance); - - commands.ForEach(cmd => cmd.Init(cgb)); - - cgb.CreateCommand("die") - .Description("Works only for the owner. Shuts the bot down. | `@NadekoBot die`") - .Do(async e => - { - if (NadekoBot.IsOwner(e.User.Id)) - { - await e.Channel.SendMessage(e.User.Mention + ", Yes, my love.").ConfigureAwait(false); - await Task.Delay(5000).ConfigureAwait(false); - Environment.Exit(0); - } - else - await e.Channel.SendMessage(e.User.Mention + ", No.").ConfigureAwait(false); - }); - - var randServerSw = new Stopwatch(); - randServerSw.Start(); - - cgb.CreateCommand("do you love me") - .Description("Replies with positive answer only to the bot owner. | `@NadekoBot do you love me`") - .Do(async e => - { - if (NadekoBot.IsOwner(e.User.Id)) - await e.Channel.SendMessage(e.User.Mention + ", Of course I do, my Master.").ConfigureAwait(false); - else - await e.Channel.SendMessage(e.User.Mention + ", Don't be silly.").ConfigureAwait(false); - }); - - cgb.CreateCommand("how are you") - .Alias("how are you?") - .Description("Replies positive only if bot owner is online. | `@NadekoBot how are you`") - .Do(async e => - { - if (NadekoBot.IsOwner(e.User.Id)) - { - await e.Channel.SendMessage(e.User.Mention + " I am great as long as you are here.").ConfigureAwait(false); - return; - } - var kw = e.Server.GetUser(NadekoBot.Creds.OwnerIds[0]); - if (kw != null && kw.Status == UserStatus.Online) - { - await e.Channel.SendMessage(e.User.Mention + " I am great as long as " + kw.Mention + " is with me.").ConfigureAwait(false); - } - else - { - await e.Channel.SendMessage(e.User.Mention + " I am sad. My Master is not with me.").ConfigureAwait(false); - } - }); - - cgb.CreateCommand("fire") - .Description("Shows a unicode fire message. Optional parameter [x] tells her how many times to repeat the fire. | `@NadekoBot fire [x]`") - .Parameter("times", ParameterType.Optional) - .Do(async e => - { - int count; - if (string.IsNullOrWhiteSpace(e.Args[0])) - count = 1; - else - int.TryParse(e.Args[0], out count); - if (count < 1 || count > 12) - { - await e.Channel.SendMessage("Number must be between 1 and 12").ConfigureAwait(false); - return; - } - - var str = new StringBuilder(); - for (var i = 0; i < count; i++) - { - str.Append(firestr); - } - await e.Channel.SendMessage(str.ToString()).ConfigureAwait(false); - }); - - cgb.CreateCommand("dump") - .Description("Dumps all of the invites it can to dump.txt.** Owner Only.** | `@NadekoBot dump`") - .Do(async e => - { - if (!NadekoBot.IsOwner(e.User.Id)) return; - var i = 0; - var j = 0; - var invites = ""; - foreach (var s in client.Servers) - { - try - { - var invite = await s.CreateInvite(0).ConfigureAwait(false); - invites += invite.Url + "\n"; - i++; - } - catch - { - j++; - continue; - } - } - File.WriteAllText("dump.txt", invites); - await e.Channel.SendMessage($"Got invites for {i} servers and failed to get invites for {j} servers") - .ConfigureAwait(false); - }); - - cgb.CreateCommand("ab") - .Description("Try to get 'abalabahaha'| `@NadekoBot ab`") - .Do(async e => - { - string[] strings = { "ba", "la", "ha" }; - var construct = "@a"; - var cnt = rng.Next(4, 7); - while (cnt-- > 0) - { - construct += strings[rng.Next(0, strings.Length)]; - } - await e.Channel.SendMessage(construct).ConfigureAwait(false); - }); - - }); - } - - - - private static Func SayYes() - => async e => await e.Channel.SendMessage("Yes. :)").ConfigureAwait(false); - } -} diff --git a/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs index b62b2dd7..81a59f2f 100644 --- a/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs @@ -58,7 +58,7 @@ namespace NadekoBot.Modules.CustomReactions commandFuncs.Keys.ForEach(key => str = key.Replace(str, m => commandFuncs[key](e, m))); - await e.Channel.SendMessage(str).ConfigureAwait(false); + await channel.SendMessageAsync(str).ConfigureAwait(false); }); } }); diff --git a/src/NadekoBot/_Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/_Modules/Gambling/Commands/AnimalRacing.cs index a908128c..ede3a350 100644 --- a/src/NadekoBot/_Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/_Modules/Gambling/Commands/AnimalRacing.cs @@ -48,7 +48,7 @@ namespace NadekoBot.Modules.Gambling.Commands if (userFlowers < amount) { - await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); return; } @@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Gambling.Commands AnimalRace ar; if (!AnimalRaces.TryGetValue(e.Server.Id, out ar)) { - await e.Channel.SendMessage("No race exists on this server"); + await channel.SendMessageAsync("No race exists on this server"); return; } await ar.JoinRace(e.User, amount); diff --git a/src/NadekoBot/_Modules/Gambling/DiceRollCommand.cs b/src/NadekoBot/_Modules/Gambling/DiceRollCommand.cs index 55bb5ee1..918416e1 100644 --- a/src/NadekoBot/_Modules/Gambling/DiceRollCommand.cs +++ b/src/NadekoBot/_Modules/Gambling/DiceRollCommand.cs @@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = r.Next(1, n2 + 1); } var elemCnt = 0; - await e.Channel.SendMessage($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + await channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } return; } @@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Gambling if (num < 1) num = 1; if (num > 30) { - await e.Channel.SendMessage("You can roll up to 30 dice at a time.").ConfigureAwait(false); + await channel.SendMessageAsync("You can roll up to 30 dice at a time.").ConfigureAwait(false); num = 30; } var dices = new List(num); @@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Gambling } var bitmap = dices.Merge(); - await e.Channel.SendMessage(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false); + await channel.SendMessageAsync(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false); await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Please enter a number of dice to roll.").ConfigureAwait(false); + await channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false); } }; } @@ -153,11 +153,11 @@ namespace NadekoBot.Modules.Gambling rolled = new Random().Next(0, int.Parse(e.GetArg("range")) + 1); } - await e.Channel.SendMessage($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($":anger: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($":anger: {ex.Message}").ConfigureAwait(false); } }; } diff --git a/src/NadekoBot/_Modules/Gambling/DrawCommand.cs b/src/NadekoBot/_Modules/Gambling/DrawCommand.cs index dbd023e1..2d1e2964 100644 --- a/src/NadekoBot/_Modules/Gambling/DrawCommand.cs +++ b/src/NadekoBot/_Modules/Gambling/DrawCommand.cs @@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Gambling return c; }); - await e.Channel.SendMessage("Deck reshuffled.").ConfigureAwait(false); + await channel.SendMessageAsync("Deck reshuffled.").ConfigureAwait(false); }; } @@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Gambling { if (cards.CardPool.Count == 0 && i != 0) { - await e.Channel.SendMessage("No more cards in a deck.").ConfigureAwait(false); + await channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false); break; } var currentCard = cards.DrawACard(); @@ -79,7 +79,7 @@ namespace NadekoBot.Modules.Gambling await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false); if (cardObjects.Count == 5) { - await e.Channel.SendMessage($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false); } } catch (Exception ex) diff --git a/src/NadekoBot/_Modules/Gambling/FlipCoinCommand.cs b/src/NadekoBot/_Modules/Gambling/FlipCoinCommand.cs index d0b79919..6cb2f4d7 100644 --- a/src/NadekoBot/_Modules/Gambling/FlipCoinCommand.cs +++ b/src/NadekoBot/_Modules/Gambling/FlipCoinCommand.cs @@ -47,7 +47,7 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); return; } @@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Gambling else str = $"{e.User.Mention}`More luck next time.`"; - await e.Channel.SendMessage(str).ConfigureAwait(false); + await channel.SendMessageAsync(str).ConfigureAwait(false); }; public Func FlipCoinFunc() => async e => @@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Gambling await e.Channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); return; } - await e.Channel.SendMessage("Invalid number").ConfigureAwait(false); + await channel.SendMessageAsync("Invalid number").ConfigureAwait(false); } }; } diff --git a/src/NadekoBot/_Modules/Gambling/GamblingModule.cs b/src/NadekoBot/_Modules/Gambling/GamblingModule.cs index d7ced224..9ab2cba2 100644 --- a/src/NadekoBot/_Modules/Gambling/GamblingModule.cs +++ b/src/NadekoBot/_Modules/Gambling/GamblingModule.cs @@ -41,13 +41,13 @@ namespace NadekoBot.Modules.Gambling var role = e.Server.FindRoles(arg).FirstOrDefault(); if (role == null) { - await e.Channel.SendMessage("💢 Role not found.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Role not found.").ConfigureAwait(false); return; } var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online var membersArray = members as User[] ?? members.ToArray(); var usr = membersArray[new Random().Next(0, membersArray.Length)]; - await e.Channel.SendMessage($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false); + await channel.SendMessageAsync($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "$$") @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Gambling var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User; var pts = GetUserFlowers(usr.Id); var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}"; - await e.Channel.SendMessage(str).ConfigureAwait(false); + await channel.SendMessageAsync(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "give") @@ -83,14 +83,14 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false); - await e.Channel.SendMessage($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); @@ -113,7 +113,7 @@ namespace NadekoBot.Modules.Gambling await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); - await e.Channel.SendMessage($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "take") @@ -135,7 +135,7 @@ namespace NadekoBot.Modules.Gambling await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false); - await e.Channel.SendMessage($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "betroll") @@ -154,7 +154,7 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await e.Channel.SendMessage($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false); return; } @@ -181,7 +181,7 @@ namespace NadekoBot.Modules.Gambling await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false); } - await e.Channel.SendMessage(str).ConfigureAwait(false); + await channel.SendMessageAsync(str).ConfigureAwait(false); }); @@ -194,7 +194,7 @@ namespace NadekoBot.Modules.Gambling var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray(); if (richest.Length == 0) return; - await e.Channel.SendMessage( + await channel.SendMessageAsync( richest.Aggregate(new StringBuilder( $@"```xl ┏━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━┓ diff --git a/src/NadekoBot/_Modules/Games/Commands/BetrayGame.cs b/src/NadekoBot/_Modules/Games/Commands/BetrayGame.cs index 74b98bf6..ba95cb13 100644 --- a/src/NadekoBot/_Modules/Games/Commands/BetrayGame.cs +++ b/src/NadekoBot/_Modules/Games/Commands/BetrayGame.cs @@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Games.Commands UserPoints -= 3; } - await e.Channel.SendMessage($"**ROUND {++round}**\n" + + await channel.SendMessageAsync($"**ROUND {++round}**\n" + $"{response}\n" + $"{nadekoResponse}\n" + $"--------------------------------\n" + @@ -100,11 +100,11 @@ namespace NadekoBot.Modules.Games.Commands .ConfigureAwait(false); if (round < 10) return; if (nadekoPoints == userPoints) - await e.Channel.SendMessage("Its a draw").ConfigureAwait(false); + await channel.SendMessageAsync("Its a draw").ConfigureAwait(false); else if (nadekoPoints > userPoints) - await e.Channel.SendMessage("Nadeko won.").ConfigureAwait(false); + await channel.SendMessageAsync("Nadeko won.").ConfigureAwait(false); else - await e.Channel.SendMessage("You won.").ConfigureAwait(false); + await channel.SendMessageAsync("You won.").ConfigureAwait(false); nadekoPoints = 0; userPoints = 0; round = 0; diff --git a/src/NadekoBot/_Modules/Games/Commands/Bomberman.cs b/src/NadekoBot/_Modules/Games/Commands/Bomberman.cs index 4987dd66..9652a893 100644 --- a/src/NadekoBot/_Modules/Games/Commands/Bomberman.cs +++ b/src/NadekoBot/_Modules/Games/Commands/Bomberman.cs @@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Games.Commands // { // if (gameChannel != null) // return; - // godMsg = await e.Channel.SendMessage("GAME START IN 1 SECOND....").ConfigureAwait(false); + // godMsg = await channel.SendMessageAsync("GAME START IN 1 SECOND....").ConfigureAwait(false); // gameChannel = e.Channel; // players[0] = new BombermanPlayer // { diff --git a/src/NadekoBot/_Modules/Games/Commands/Leet.cs b/src/NadekoBot/_Modules/Games/Commands/Leet.cs index e71a80d0..2fb1dcaa 100644 --- a/src/NadekoBot/_Modules/Games/Commands/Leet.cs +++ b/src/NadekoBot/_Modules/Games/Commands/Leet.cs @@ -310,7 +310,7 @@ namespace NadekoBot.Modules.Games.Commands return; if (string.IsNullOrWhiteSpace(text)) return; - await e.Channel.SendMessage(ToLeet(text, level)).ConfigureAwait(false); + await channel.SendMessageAsync(ToLeet(text, level)).ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Games/Commands/PlantPick.cs b/src/NadekoBot/_Modules/Games/Commands/PlantPick.cs index 2752ad1f..209e24e5 100644 --- a/src/NadekoBot/_Modules/Games/Commands/PlantPick.cs +++ b/src/NadekoBot/_Modules/Games/Commands/PlantPick.cs @@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Games.Commands var rnd = Math.Abs(rng.Next(0,101)); if (rnd == 0) { - var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await e.Channel.SendMessage($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") }; + var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await channel.SendMessageAsync($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") }; plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; }); plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now); } @@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Games.Commands await msgToDelete.Delete().ConfigureAwait(false); await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false); - var msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false); + var msg = await channel.SendMessageAsync($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false); ThreadPool.QueueUserWorkItem(async (state) => { try @@ -99,24 +99,24 @@ namespace NadekoBot.Modules.Games.Commands { if (plantedFlowerChannels.ContainsKey(e.Channel.Id)) { - await e.Channel.SendMessage($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false); return; } var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false); if (!removed) { - await e.Channel.SendMessage($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false); + await channel.SendMessageAsync($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false); return; } var file = GetRandomCurrencyImagePath(); Message msg; if (file == null) - msg = await e.Channel.SendMessage(NadekoBot.Config.CurrencySign).ConfigureAwait(false); + msg = await channel.SendMessageAsync(NadekoBot.Config.CurrencySign).ConfigureAwait(false); else msg = await e.Channel.SendFile(file).ConfigureAwait(false); var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); - var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false); + var msg2 = await channel.SendMessageAsync($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false); plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 }); } finally { locker.Release(); } @@ -139,12 +139,12 @@ namespace NadekoBot.Modules.Games.Commands int throwaway; if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway)) { - await e.Channel.SendMessage("`Currency generation disabled on this channel.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Currency generation disabled on this channel.`").ConfigureAwait(false); } else { if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd)) - await e.Channel.SendMessage($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false); } }); } diff --git a/src/NadekoBot/_Modules/Games/Commands/PollCommand.cs b/src/NadekoBot/_Modules/Games/Commands/PollCommand.cs index 785d5c5f..fb6777c4 100644 --- a/src/NadekoBot/_Modules/Games/Commands/PollCommand.cs +++ b/src/NadekoBot/_Modules/Games/Commands/PollCommand.cs @@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Games.Commands var num = 1; msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); msgToSend += "\n**Private Message me with the corresponding number of the answer.**"; - await e.Channel.SendMessage(msgToSend).ConfigureAwait(false); + await channel.SendMessageAsync(msgToSend).ConfigureAwait(false); } public async Task StopPoll(Channel ch) diff --git a/src/NadekoBot/_Modules/Games/Commands/SpeedTyping.cs b/src/NadekoBot/_Modules/Games/Commands/SpeedTyping.cs index 07100820..950c67ce 100644 --- a/src/NadekoBot/_Modules/Games/Commands/SpeedTyping.cs +++ b/src/NadekoBot/_Modules/Games/Commands/SpeedTyping.cs @@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Games.Commands await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!").ConfigureAwait(false); if (finishedUserIds.Count % 2 == 0) { - await e.Channel.SendMessage($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false); + await channel.SendMessageAsync($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false); } } } @@ -142,7 +142,7 @@ namespace NadekoBot.Modules.Games.Commands if (game.IsActive) { - await e.Channel.SendMessage( + await channel.SendMessageAsync( $"Contest already running in " + $"{game.Channell.Mention} channel.") .ConfigureAwait(false); @@ -162,7 +162,7 @@ namespace NadekoBot.Modules.Games.Commands await game.Stop().ConfigureAwait(false); return; } - await e.Channel.SendMessage("No contest to stop on this channel.").ConfigureAwait(false); + await channel.SendMessageAsync("No contest to stop on this channel.").ConfigureAwait(false); }; internal override void Init(CommandGroupBuilder cgb) @@ -188,7 +188,7 @@ namespace NadekoBot.Modules.Games.Commands DateAdded = DateTime.Now }); - await e.Channel.SendMessage("Added new article for typing game.").ConfigureAwait(false); + await channel.SendMessageAsync("Added new article for typing game.").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Games/Commands/TriviaCommand.cs b/src/NadekoBot/_Modules/Games/Commands/TriviaCommand.cs index 75481309..02e57efa 100644 --- a/src/NadekoBot/_Modules/Games/Commands/TriviaCommand.cs +++ b/src/NadekoBot/_Modules/Games/Commands/TriviaCommand.cs @@ -37,12 +37,12 @@ namespace NadekoBot.Modules.Games.Commands return; var triviaGame = new TriviaGame(e, showHints, number == 0 ? 10 : number); if (RunningTrivias.TryAdd(e.Server.Id, triviaGame)) - await e.Channel.SendMessage($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); + await channel.SendMessageAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); else await triviaGame.StopGame().ConfigureAwait(false); } else - await e.Channel.SendMessage("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false); + await channel.SendMessageAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "tl") @@ -51,9 +51,9 @@ namespace NadekoBot.Modules.Games.Commands { TriviaGame trivia; if (RunningTrivias.TryGetValue(e.Server.Id, out trivia)) - await e.Channel.SendMessage(trivia.GetLeaderboard()).ConfigureAwait(false); + await channel.SendMessageAsync(trivia.GetLeaderboard()).ConfigureAwait(false); else - await e.Channel.SendMessage("No trivia is running on this server.").ConfigureAwait(false); + await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "tq") @@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Games.Commands await trivia.StopGame().ConfigureAwait(false); } else - await e.Channel.SendMessage("No trivia is running on this server.").ConfigureAwait(false); + await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false); }); } } diff --git a/src/NadekoBot/_Modules/Games/GamesModule.cs b/src/NadekoBot/_Modules/Games/GamesModule.cs index acdaf1b3..d87e1f22 100644 --- a/src/NadekoBot/_Modules/Games/GamesModule.cs +++ b/src/NadekoBot/_Modules/Games/GamesModule.cs @@ -46,7 +46,7 @@ namespace NadekoBot.Modules.Games var list = arg.Split(';'); if (list.Count() < 2) return; - await e.Channel.SendMessage(list[rng.Next(0, list.Length)]).ConfigureAwait(false); + await channel.SendMessageAsync(list[rng.Next(0, list.Length)]).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "8ball") @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Games return; try { - await e.Channel.SendMessage( + await channel.SendMessageAsync( $":question: `Question` __**{question}**__ \n🎱 `8Ball Answers` __**{NadekoBot.Config._8BallResponses[rng.Next(0, NadekoBot.Config._8BallResponses.Length)]}**__") .ConfigureAwait(false); } @@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Games else msg = $"{e.User.Mention} won! :{GetRPSPick(pick)}: beats :{GetRPSPick(nadekoPick)}:"; - await e.Channel.SendMessage(msg).ConfigureAwait(false); + await channel.SendMessageAsync(msg).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "linux") @@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Games var guhnoo = e.Args[0]; var loonix = e.Args[1]; - await e.Channel.SendMessage( + await channel.SendMessageAsync( $@" I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. diff --git a/src/NadekoBot/_Modules/Help/Commands/HelpCommand.cs b/src/NadekoBot/_Modules/Help/Commands/HelpCommand.cs index d0ba292b..7a99c332 100644 --- a/src/NadekoBot/_Modules/Help/Commands/HelpCommand.cs +++ b/src/NadekoBot/_Modules/Help/Commands/HelpCommand.cs @@ -31,7 +31,7 @@ namespace NadekoBot.Classes.Help.Commands if (alias != null) str = $" / `{ com.Aliases.FirstOrDefault()}`"; if (com != null) - await e.Channel.SendMessage($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false); + await channel.SendMessageAsync($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false); }).ConfigureAwait(false); }; public static string HelpString { @@ -91,7 +91,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: - await e.Channel.SendMessage( + await channel.SendMessageAsync( @"**Wiki with all info**: **WINDOWS SETUP GUIDE**: @@ -105,7 +105,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: { - await e.Channel.SendMessage( + await channel.SendMessageAsync( $@"You can support the project on patreon. or You can send donations to `nadekodiscordbot@gmail.com` Don't forget to leave your discord name or id in the message. diff --git a/src/NadekoBot/_Modules/Help/HelpModule.cs b/src/NadekoBot/_Modules/Help/HelpModule.cs index 45e4dc76..a45299e4 100644 --- a/src/NadekoBot/_Modules/Help/HelpModule.cs +++ b/src/NadekoBot/_Modules/Help/HelpModule.cs @@ -32,7 +32,7 @@ namespace NadekoBot.Modules.Help .Description($"List all bot modules. | `{Prefix}modules` or `.modules`") .Do(async e => { - await e.Channel.SendMessage("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`") + await channel.SendMessageAsync("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`") .ConfigureAwait(false); }); @@ -52,20 +52,20 @@ namespace NadekoBot.Modules.Help var cmdsArray = cmds as Command[] ?? cmds.ToArray(); if (!cmdsArray.Any()) { - await e.Channel.SendMessage("That module does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync("That module does not exist.").ConfigureAwait(false); return; } if (module != "customreactions" && module != "conversations") { - await e.Channel.SendMessage("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode(cmdsArray, + await channel.SendMessageAsync("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode(cmdsArray, el => $"{el.Text,-15}{"[" + el.Aliases.FirstOrDefault() + "]",-8}")) .ConfigureAwait(false); } else { - await e.Channel.SendMessage("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}"))); + await channel.SendMessageAsync("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}"))); } - await e.Channel.SendMessage($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false); + await channel.SendMessageAsync($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false); }); }); } diff --git a/src/NadekoBot/_Modules/Music/MusicModule.cs b/src/NadekoBot/_Modules/Music/MusicModule.cs index 3c4aa351..1c4a010a 100644 --- a/src/NadekoBot/_Modules/Music/MusicModule.cs +++ b/src/NadekoBot/_Modules/Music/MusicModule.cs @@ -92,9 +92,9 @@ namespace NadekoBot.Modules.Music return; musicPlayer.TogglePause(); if (musicPlayer.Paused) - await e.Channel.SendMessage("🎵`Music Player paused.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎵`Music Player paused.`").ConfigureAwait(false); else - await e.Channel.SendMessage("🎵`Music Player unpaused.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎵`Music Player unpaused.`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "queue") @@ -137,7 +137,7 @@ namespace NadekoBot.Modules.Music MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) { - await e.Channel.SendMessage("🎵 No active music player.").ConfigureAwait(false); + await channel.SendMessageAsync("🎵 No active music player.").ConfigureAwait(false); return; } @@ -163,7 +163,7 @@ namespace NadekoBot.Modules.Music const int itemsPerPage = 15; int startAt = itemsPerPage * (page - 1); var number = 1 + startAt; - await e.Channel.SendMessage(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false); + await channel.SendMessageAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "nowplaying") @@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Music var currentSong = musicPlayer.CurrentSong; if (currentSong == null) return; - await e.Channel.SendMessage($"🎵`Now Playing` {currentSong.PrettyName} " + + await channel.SendMessageAsync($"🎵`Now Playing` {currentSong.PrettyName} " + $"{currentSong.PrettyCurrentTime()}").ConfigureAwait(false); }); @@ -196,11 +196,11 @@ namespace NadekoBot.Modules.Music int volume; if (!int.TryParse(arg, out volume)) { - await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false); + await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false); return; } volume = musicPlayer.SetVolume(volume); - await e.Channel.SendMessage($"🎵 `Volume set to {volume}%`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵 `Volume set to {volume}%`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "defvol") @@ -214,12 +214,12 @@ namespace NadekoBot.Modules.Music float volume; if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100) { - await e.Channel.SendMessage("Volume number invalid.").ConfigureAwait(false); + await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false); return; } var conf = SpecificConfigurations.Default.Of(e.Server.Id); conf.DefaultMusicVolume = volume / 100; - await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "mute") @@ -271,12 +271,12 @@ namespace NadekoBot.Modules.Music return; if (musicPlayer.Playlist.Count < 2) { - await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false); return; } musicPlayer.Shuffle(); - await e.Channel.SendMessage("🎵 `Songs shuffled.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎵 `Songs shuffled.`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "playlist") @@ -290,25 +290,25 @@ namespace NadekoBot.Modules.Music return; if (e.User.VoiceChannel?.Server != e.Server) { - await e.Channel.SendMessage("💢 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); + 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 SearchHelper.GetPlaylistIdByKeyword(arg).ConfigureAwait(false); if (plId == null) { - await e.Channel.SendMessage("No search results for that query."); + await channel.SendMessageAsync("No search results for that query."); return; } var ids = await SearchHelper.GetVideoIDs(plId, 500).ConfigureAwait(false); if (ids == null || ids.Count == 0) { - await e.Channel.SendMessage($"🎵 `Failed to find any songs.`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵 `Failed to find any songs.`").ConfigureAwait(false); return; } var idArray = ids as string[] ?? ids.ToArray(); var count = idArray.Length; var msg = - await e.Channel.SendMessage($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false); foreach (var id in idArray) { try @@ -383,7 +383,7 @@ namespace NadekoBot.Modules.Music } catch { } } - await e.Channel.SendMessage("🎵 `Directory queue complete.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎵 `Directory queue complete.`").ConfigureAwait(false); } catch { } }); @@ -395,7 +395,7 @@ namespace NadekoBot.Modules.Music { if (e.User.VoiceChannel?.Server != e.Server) { - await e.Channel.SendMessage("💢 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); + 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; } await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false); @@ -448,7 +448,7 @@ namespace NadekoBot.Modules.Music if (arg?.ToLower() == "all") { musicPlayer.ClearQueue(); - await e.Channel.SendMessage($"🎵`Queue cleared!`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵`Queue cleared!`").ConfigureAwait(false); return; } int num; @@ -460,7 +460,7 @@ namespace NadekoBot.Modules.Music return; var song = (musicPlayer.Playlist as List)?[num - 1]; musicPlayer.RemoveSongAt(num - 1); - await e.Channel.SendMessage($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false); }); //var msRegex = new Regex(@"(?\d+)>(?\d+)", RegexOptions.Compiled); @@ -487,7 +487,7 @@ namespace NadekoBot.Modules.Music !int.TryParse(fromtoArr[1], out n2) || n1 < 1 || n2 < 1 || n1 == n2 || n1 > playlist.Count || n2 > playlist.Count) { - await e.Channel.SendMessage("`Invalid input.`").ConfigureAwait(false); + await channel.SendMessageAsync("`Invalid input.`").ConfigureAwait(false); return; } @@ -496,7 +496,7 @@ namespace NadekoBot.Modules.Music var nn1 = n2 < n1 ? n1 : n1 - 1; playlist.RemoveAt(nn1); - await e.Channel.SendMessage($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); }); @@ -520,7 +520,7 @@ namespace NadekoBot.Modules.Music } musicPlayer.MaxQueueSize = size; - await e.Channel.SendMessage($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`"); + await channel.SendMessageAsync($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`"); }); cgb.CreateCommand(Prefix + "cleanup") @@ -553,7 +553,7 @@ namespace NadekoBot.Modules.Music if (currentSong == null) return; var currentValue = musicPlayer.ToggleRepeatSong(); - await e.Channel.SendMessage(currentValue ? + await channel.SendMessageAsync(currentValue ? $"🎵🔂`Repeating track:`{currentSong.PrettyName}" : $"🎵🔂`Current track repeat stopped.`") .ConfigureAwait(false); @@ -568,7 +568,7 @@ namespace NadekoBot.Modules.Music if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; var currentValue = musicPlayer.ToggleRepeatPlaylist(); - await e.Channel.SendMessage($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "save") @@ -620,7 +620,7 @@ namespace NadekoBot.Modules.Music SongInfoId = s.Id.Value }), typeof(PlaylistSongInfo)); - await e.Channel.SendMessage($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false); + await channel.SendMessageAsync($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false); }); @@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Music if (playlist == null) { - await e.Channel.SendMessage("Can't find playlist under that name.").ConfigureAwait(false); + await channel.SendMessageAsync("Can't find playlist under that name.").ConfigureAwait(false); return; } @@ -665,7 +665,7 @@ namespace NadekoBot.Modules.Music var songInfos = psis.Select(psi => DbHandler.Instance .FindOne(si => si.Id == psi.SongInfoId)); - await e.Channel.SendMessage($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false); foreach (var si in songInfos) { try @@ -695,9 +695,9 @@ namespace NadekoBot.Modules.Music return; var result = DbHandler.Instance.GetPlaylistData(num); if (result.Count == 0) - e.Channel.SendMessage($"`No saved playlists found on page {num}`").ConfigureAwait(false); + channel.SendMessageAsync($"`No saved playlists found on page {num}`").ConfigureAwait(false); else - e.Channel.SendMessage($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); + channel.SendMessageAsync($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "deleteplaylist") @@ -714,7 +714,7 @@ namespace NadekoBot.Modules.Music DbHandler.Instance.Delete(plnum); else DbHandler.Instance.DeleteWhere(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId); - await e.Channel.SendMessage("`Ok.` :ok:").ConfigureAwait(false); + await channel.SendMessageAsync("`Ok.` :ok:").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "goto") @@ -751,7 +751,7 @@ namespace NadekoBot.Modules.Music if (seconds.Length == 1) seconds = "0" + seconds; - await e.Channel.SendMessage($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "getlink") @@ -771,12 +771,12 @@ namespace NadekoBot.Modules.Music var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1); if (selSong == null) { - await e.Channel.SendMessage("Could not select song, likely wrong index"); + await channel.SendMessageAsync("Could not select song, likely wrong index"); } else { - await e.Channel.SendMessage($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); + await channel.SendMessageAsync($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false); } } else @@ -784,7 +784,7 @@ namespace NadekoBot.Modules.Music var curSong = musicPlayer.CurrentSong; if (curSong == null) return; - await e.Channel.SendMessage($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false); + await channel.SendMessageAsync($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false); } }); @@ -800,9 +800,9 @@ namespace NadekoBot.Modules.Music return; if (!musicPlayer.ToggleAutoplay()) - await e.Channel.SendMessage("🎶`Autoplay disabled.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎶`Autoplay disabled.`").ConfigureAwait(false); else - await e.Channel.SendMessage("🎶`Autoplay enabled.`").ConfigureAwait(false); + await channel.SendMessageAsync("🎶`Autoplay enabled.`").ConfigureAwait(false); }); }); } diff --git a/src/NadekoBot/_Modules/NSFW/NSFWModule.cs b/src/NadekoBot/_Modules/NSFW/NSFWModule.cs deleted file mode 100644 index ac688fb7..00000000 --- a/src/NadekoBot/_Modules/NSFW/NSFWModule.cs +++ /dev/null @@ -1,127 +0,0 @@ -using Discord.Commands; -using Discord.Modules; -using NadekoBot.Classes; -using NadekoBot.Modules.Permissions.Classes; -using Newtonsoft.Json.Linq; -using System; -using System.Linq; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.NSFW -{ - internal class NSFWModule : DiscordModule - { - - private readonly Random rng = new Random(); - - public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.NSFW; - - public override void Install(ModuleManager manager) - { - manager.CreateCommands("", cgb => - { - - cgb.AddCheck(PermissionChecker.Instance); - - cgb.CreateCommand(Prefix + "hentai") - .Description($"Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}hentai yuri+kissing`") - .Parameter("tag", ParameterType.Unparsed) - .Do(async e => - { - var tag = e.GetArg("tag")?.Trim() ?? ""; - - var links = await Task.WhenAll(SearchHelper.GetGelbooruImageLink("rating%3Aexplicit+" + tag), SearchHelper.GetDanbooruImageLink("rating%3Aexplicit+" + tag)).ConfigureAwait(false); - - if (links.All(l => l == null)) - { - await e.Channel.SendMessage("`No results.`"); - return; - } - - await e.Channel.SendMessage(String.Join("\n\n", links)).ConfigureAwait(false); - }); - cgb.CreateCommand(Prefix + "danbooru") - .Description($"Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}danbooru yuri+kissing`") - .Parameter("tag", ParameterType.Unparsed) - .Do(async e => - { - var tag = e.GetArg("tag")?.Trim() ?? ""; - var link = await SearchHelper.GetDanbooruImageLink(tag).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(link)) - await e.Channel.SendMessage("Search yielded no results ;("); - else - await e.Channel.SendMessage(link).ConfigureAwait(false); - }); - cgb.CreateCommand(Prefix + "gelbooru") - .Description($"Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}gelbooru yuri+kissing`") - .Parameter("tag", ParameterType.Unparsed) - .Do(async e => - { - var tag = e.GetArg("tag")?.Trim() ?? ""; - var link = await SearchHelper.GetGelbooruImageLink(tag).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(link)) - await e.Channel.SendMessage("Search yielded no results ;("); - else - await e.Channel.SendMessage(link).ConfigureAwait(false); - }); - - cgb.CreateCommand(Prefix + "rule34") - .Description($"Shows a random image from rule34.xx with a given tag. Tag is optional but preffered. (multiple tags are appended with +) | `{Prefix}rule34 yuri+kissing`") - .Parameter("tag", ParameterType.Unparsed) - .Do(async e => - { - var tag = e.GetArg("tag")?.Trim() ?? ""; - var link = await SearchHelper.GetRule34ImageLink(tag).ConfigureAwait(false); - if (string.IsNullOrWhiteSpace(link)) - await e.Channel.SendMessage("Search yielded no results ;("); - else - await e.Channel.SendMessage(link).ConfigureAwait(false); - }); - cgb.CreateCommand(Prefix + "e621") - .Description($"Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags. | `{Prefix}e621 yuri kissing`") - .Parameter("tag", ParameterType.Unparsed) - .Do(async e => - { - var tag = e.GetArg("tag")?.Trim() ?? ""; - await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag).ConfigureAwait(false)).ConfigureAwait(false); - }); - cgb.CreateCommand(Prefix + "cp") - .Description($"We all know where this will lead you to. | `{Prefix}cp`") - .Parameter("anything", ParameterType.Unparsed) - .Do(async e => - { - await e.Channel.SendMessage("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); - }); - cgb.CreateCommand(Prefix + "boobs") - .Description($"Real adult content. | `{Prefix}boobs`") - .Do(async e => - { - try - { - var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}").ConfigureAwait(false))[0]; - await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); - } - catch (Exception ex) - { - await e.Channel.SendMessage($"💢 {ex.Message}").ConfigureAwait(false); - } - }); - cgb.CreateCommand(Prefix + "butts") - .Alias(Prefix + "ass", Prefix + "butt") - .Description($"Real adult content. | `{Prefix}butts` or `{Prefix}ass`") - .Do(async e => - { - try - { - var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}").ConfigureAwait(false))[0]; - await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); - } - catch (Exception ex) - { - await e.Channel.SendMessage($"💢 {ex.Message}").ConfigureAwait(false); - } - }); - }); - } - } -} diff --git a/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs b/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs index 445558c3..47ba8b53 100644 --- a/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs +++ b/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs @@ -72,7 +72,7 @@ namespace NadekoBot.Modules.Permissions.Commands ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chanStr); await PermissionsHandler.SetChannelFilterInvitesPermission(chan, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.") + await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.") .ConfigureAwait(false); return; } @@ -82,13 +82,13 @@ namespace NadekoBot.Modules.Permissions.Commands { await PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.") + await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.") .ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}") + await channel.SendMessageAsync($"💢 Error: {ex.Message}") .ConfigureAwait(false); } }); @@ -103,13 +103,13 @@ namespace NadekoBot.Modules.Permissions.Commands { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.") + await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.") .ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); } diff --git a/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs b/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs index b574ef23..bd16354d 100644 --- a/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs +++ b/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs @@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Permissions.Commands ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chanStr); await PermissionsHandler.SetChannelWordPermission(chan, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false); return; } //all channels @@ -78,11 +78,11 @@ namespace NadekoBot.Modules.Permissions.Commands { await PermissionsHandler.SetChannelWordPermission(curChannel, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false); + await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); @@ -99,12 +99,12 @@ namespace NadekoBot.Modules.Permissions.Commands if (string.IsNullOrWhiteSpace(word)) return; await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully added new filtered word.").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully added new filtered word.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); @@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Permissions.Commands if (string.IsNullOrWhiteSpace(word)) return; await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); - await e.Channel.SendMessage($"Successfully removed filtered word.").ConfigureAwait(false); + await channel.SendMessageAsync($"Successfully removed filtered word.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); @@ -141,12 +141,12 @@ namespace NadekoBot.Modules.Permissions.Commands Classes.ServerPermissions serverPerms; if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms)) return; - await e.Channel.SendMessage($"There are `{serverPerms.Words.Count}` filtered words.\n" + + await channel.SendMessageAsync($"There are `{serverPerms.Words.Count}` filtered words.\n" + string.Join("\n", serverPerms.Words)).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); @@ -160,13 +160,13 @@ namespace NadekoBot.Modules.Permissions.Commands { var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.") + await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.") .ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error: {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false); } }); } diff --git a/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs b/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs index d2bc1840..de616d1c 100644 --- a/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs +++ b/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions { if (string.IsNullOrWhiteSpace(e.GetArg("role"))) { - await e.Channel.SendMessage($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); + await channel.SendMessageAsync($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); return; } @@ -52,11 +52,11 @@ namespace NadekoBot.Modules.Permissions catch (Exception ex) { Console.WriteLine(ex.Message); - await e.Channel.SendMessage($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false); + await channel.SendMessageAsync($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false); return; } await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false); - await e.Channel.SendMessage($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false); + await channel.SendMessageAsync($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "rolepermscopy") @@ -71,7 +71,7 @@ namespace NadekoBot.Modules.Permissions var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { - await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); + await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); return; } try @@ -80,11 +80,11 @@ namespace NadekoBot.Modules.Permissions var toRole = PermissionHelper.ValidateRole(e.Server, args[1]); await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false); - await e.Channel.SendMessage($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢{ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢{ex.Message}").ConfigureAwait(false); } }); cgb.CreateCommand(Prefix + "chnlpermscopy") @@ -99,7 +99,7 @@ namespace NadekoBot.Modules.Permissions var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { - await e.Channel.SendMessage("💢Invalid number of '~'s in the argument."); + await channel.SendMessageAsync("💢Invalid number of '~'s in the argument."); return; } try @@ -108,11 +108,11 @@ namespace NadekoBot.Modules.Permissions var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]); await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false); - await e.Channel.SendMessage($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢{ex.Message}"); + await channel.SendMessageAsync($"💢{ex.Message}"); } }); cgb.CreateCommand(Prefix + "usrpermscopy") @@ -127,7 +127,7 @@ namespace NadekoBot.Modules.Permissions var args = arg.Split('~').Select(a => a.Trim()).ToArray(); if (args.Length > 2) { - await e.Channel.SendMessage("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); + await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false); return; } try @@ -136,11 +136,11 @@ namespace NadekoBot.Modules.Permissions var toUser = PermissionHelper.ValidateUser(e.Server, args[1]); await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false); - await e.Channel.SendMessage($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢{ex.Message}"); + await channel.SendMessageAsync($"💢{ex.Message}"); } }); @@ -153,7 +153,7 @@ namespace NadekoBot.Modules.Permissions var arg = e.GetArg("arg"); var val = PermissionHelper.ValidateBool(arg); await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false); - await e.Channel.SendMessage($"Verbosity set to {val}.").ConfigureAwait(false); + await channel.SendMessageAsync($"Verbosity set to {val}.").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "srvrperms") @@ -163,8 +163,8 @@ namespace NadekoBot.Modules.Permissions { var perms = PermissionsHandler.GetServerPermissions(e.Server); if (string.IsNullOrWhiteSpace(perms?.ToString())) - await e.Channel.SendMessage("No permissions set for this server.").ConfigureAwait(false); - await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync("No permissions set for this server.").ConfigureAwait(false); + await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "roleperms") @@ -182,15 +182,15 @@ namespace NadekoBot.Modules.Permissions } catch (Exception ex) { - await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false); return; } var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) - await e.Channel.SendMessage($"No permissions set for **{role.Name}** role.").ConfigureAwait(false); - await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync($"No permissions set for **{role.Name}** role.").ConfigureAwait(false); + await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "chnlperms") @@ -208,14 +208,14 @@ namespace NadekoBot.Modules.Permissions } catch (Exception ex) { - await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false); return; } var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) - await e.Channel.SendMessage($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false); - await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "userperms") @@ -232,14 +232,14 @@ namespace NadekoBot.Modules.Permissions } catch (Exception ex) { - await e.Channel.SendMessage("💢 Error: " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false); return; } var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id); if (string.IsNullOrWhiteSpace(perms?.ToString())) - await e.Channel.SendMessage($"No permissions set for user **{user.Name}**.").ConfigureAwait(false); - await e.Channel.SendMessage(perms.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync($"No permissions set for user **{user.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "srvrmdl") @@ -255,15 +255,15 @@ namespace NadekoBot.Modules.Permissions var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -279,15 +279,15 @@ namespace NadekoBot.Modules.Permissions var state = PermissionHelper.ValidateBool(e.GetArg("bool")); await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -309,23 +309,23 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -347,23 +347,23 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false); } else { var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -385,28 +385,28 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else if (string.IsNullOrWhiteSpace(channelArg)) { await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, channelArg); await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -428,23 +428,23 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false); } else { var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -462,15 +462,15 @@ namespace NadekoBot.Modules.Permissions var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -488,15 +488,15 @@ namespace NadekoBot.Modules.Permissions var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false); - await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -513,15 +513,15 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); + await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -540,15 +540,15 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); + await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -568,15 +568,15 @@ namespace NadekoBot.Modules.Permissions await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -596,15 +596,15 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); + await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -623,15 +623,15 @@ namespace NadekoBot.Modules.Permissions await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); + await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Permissions await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } } - await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false); + await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false); } else { @@ -665,16 +665,16 @@ namespace NadekoBot.Modules.Permissions { await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false); } - await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); + await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); } } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -690,7 +690,7 @@ namespace NadekoBot.Modules.Permissions var usr = e.Message.MentionedUsers.First(); NadekoBot.Config.UserBlacklist.Add(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); @@ -708,11 +708,11 @@ namespace NadekoBot.Modules.Permissions { NadekoBot.Config.UserBlacklist.Remove(usr.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false); } else { - await e.Channel.SendMessage($"`{usr.Name} was not in blacklist`").ConfigureAwait(false); + await channel.SendMessageAsync($"`{usr.Name} was not in blacklist`").ConfigureAwait(false); } }).ConfigureAwait(false); }); @@ -728,7 +728,7 @@ namespace NadekoBot.Modules.Permissions var ch = e.Message.MentionedChannels.First(); NadekoBot.Config.UserBlacklist.Add(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); @@ -743,7 +743,7 @@ namespace NadekoBot.Modules.Permissions var ch = e.Message.MentionedChannels.First(); NadekoBot.Config.UserBlacklist.Remove(ch.Id); await ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); @@ -762,7 +762,7 @@ namespace NadekoBot.Modules.Permissions NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault(); if (server == null) { - await e.Channel.SendMessage("Cannot find that server").ConfigureAwait(false); + await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false); return; } var serverId = server.Id; @@ -774,7 +774,7 @@ namespace NadekoBot.Modules.Permissions TypingGame typeracer; SpeedTyping.RunningContests.TryRemove(serverId, out typeracer); - await e.Channel.SendMessage($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false); }).ConfigureAwait(false); }); @@ -797,17 +797,17 @@ namespace NadekoBot.Modules.Permissions await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false); if(secs == 0) - await e.Channel.SendMessage($"Command **{command}** has no coooldown now.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** has no coooldown now.").ConfigureAwait(false); else - await e.Channel.SendMessage($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false); + await channel.SendMessageAsync($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false); } catch (ArgumentException exArg) { - await e.Channel.SendMessage(exArg.Message).ConfigureAwait(false); + await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); + await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false); } }); @@ -823,10 +823,10 @@ namespace NadekoBot.Modules.Permissions if (!perms.CommandCooldowns.Any()) { - await e.Channel.SendMessage("`No command cooldowns set.`").ConfigureAwait(false); + await channel.SendMessageAsync("`No command cooldowns set.`").ConfigureAwait(false); return; } - await e.Channel.SendMessage(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false); + await channel.SendMessageAsync(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false); }); }); } diff --git a/src/NadekoBot/_Modules/Pokemon/PokemonModule.cs b/src/NadekoBot/_Modules/Pokemon/PokemonModule.cs index d494fffa..f9503fdc 100644 --- a/src/NadekoBot/_Modules/Pokemon/PokemonModule.cs +++ b/src/NadekoBot/_Modules/Pokemon/PokemonModule.cs @@ -92,12 +92,12 @@ namespace NadekoBot.Modules.Pokemon var target = e.Server.FindUsers(targetStr).FirstOrDefault(); if (target == null) { - await e.Channel.SendMessage("No such person.").ConfigureAwait(false); + await channel.SendMessageAsync("No such person.").ConfigureAwait(false); return; } else if (target == e.User) { - await e.Channel.SendMessage("You can't attack yourself.").ConfigureAwait(false); + await channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false); return; } // Checking stats first, then move @@ -109,17 +109,17 @@ namespace NadekoBot.Modules.Pokemon //User not able if HP < 0, has made more than 4 attacks if (userStats.Hp < 0) { - await e.Channel.SendMessage($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false); return; } if (userStats.MovesMade >= 5) { - await e.Channel.SendMessage($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false); return; } if (userStats.LastAttacked.Contains(target.Id)) { - await e.Channel.SendMessage($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false); return; } //get target stats @@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Pokemon //If target's HP is below 0, no use attacking if (targetStats.Hp <= 0) { - await e.Channel.SendMessage($"{target.Mention} has already fainted!").ConfigureAwait(false); + await channel.SendMessageAsync($"{target.Mention} has already fainted!").ConfigureAwait(false); return; } @@ -139,7 +139,7 @@ namespace NadekoBot.Modules.Pokemon var enabledMoves = userType.Moves; if (!enabledMoves.Contains(move.ToLowerInvariant())) { - await e.Channel.SendMessage($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false); return; } @@ -191,7 +191,7 @@ namespace NadekoBot.Modules.Pokemon Stats[e.User.Id] = userStats; Stats[target.Id] = targetStats; - await e.Channel.SendMessage(response).ConfigureAwait(false); + await channel.SendMessageAsync(response).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "movelist") @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.Pokemon { str += $"\n{userType.Icon}{m}"; } - await e.Channel.SendMessage(str).ConfigureAwait(false); + await channel.SendMessageAsync(str).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "heal") @@ -220,7 +220,7 @@ namespace NadekoBot.Modules.Pokemon var usr = e.Server.FindUsers(targetStr).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("No such person.").ConfigureAwait(false); + await channel.SendMessageAsync("No such person.").ConfigureAwait(false); return; } if (Stats.ContainsKey(usr.Id)) @@ -230,7 +230,7 @@ namespace NadekoBot.Modules.Pokemon int HP = targetStats.Hp; if (targetStats.Hp == targetStats.MaxHp) { - await e.Channel.SendMessage($"{usr.Name} already has full HP!").ConfigureAwait(false); + await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false); return; } //Payment~ @@ -238,7 +238,7 @@ namespace NadekoBot.Modules.Pokemon var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; if (pts < amount) { - await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); return; } var target = (usr.Id == e.User.Id) ? "yourself" : usr.Name; @@ -249,16 +249,16 @@ namespace NadekoBot.Modules.Pokemon { //Could heal only for half HP? Stats[usr.Id].Hp = (targetStats.MaxHp / 2); - await e.Channel.SendMessage($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); return; } var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]); - await e.Channel.SendMessage($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); return; } else { - await e.Channel.SendMessage($"{usr.Name} already has full HP!").ConfigureAwait(false); + await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false); } }); @@ -273,11 +273,11 @@ namespace NadekoBot.Modules.Pokemon var usr = e.Server.FindUsers(usrStr).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("No such person.").ConfigureAwait(false); + await channel.SendMessageAsync("No such person.").ConfigureAwait(false); return; } var pType = GetPokeType(usr.Id); - await e.Channel.SendMessage($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); + await channel.SendMessageAsync($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); }); @@ -292,12 +292,12 @@ namespace NadekoBot.Modules.Pokemon var targetType = stringToPokemonType(targetTypeStr); if (targetType == null) { - await e.Channel.SendMessage("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false); + await channel.SendMessageAsync("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false); return; } if (targetType == GetPokeType(e.User.Id)) { - await e.Channel.SendMessage($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); + await channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); return; } @@ -306,7 +306,7 @@ namespace NadekoBot.Modules.Pokemon var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0; if (pts < amount) { - await e.Channel.SendMessage($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); + await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false); return; } await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false); @@ -327,7 +327,7 @@ namespace NadekoBot.Modules.Pokemon //Now for the response - await e.Channel.SendMessage($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); + await channel.SendMessageAsync($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false); }); }); } diff --git a/src/NadekoBot/_Modules/Searches/Commands/ConverterCommand.cs b/src/NadekoBot/_Modules/Searches/Commands/ConverterCommand.cs index ada8709a..d6a5f983 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/ConverterCommand.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/ConverterCommand.cs @@ -61,7 +61,7 @@ namespace NadekoBot.Modules.Searches.Commands msg += curr + "; "; } - await e.Channel.SendMessage(msg).ConfigureAwait(false); + await channel.SendMessageAsync(msg).ConfigureAwait(false); }; private Func ConvertFunc() => @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Searches.Commands { Unit inUnit = new Unit(fromCode, quantity, table); Unit outUnit = inUnit.Convert(toCode); - await e.Channel.SendMessage(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); } else { @@ -97,13 +97,13 @@ namespace NadekoBot.Modules.Searches.Commands reInitCurrencyConverterTable(); Unit inUnit = currTable.CreateUnit(quantity, from.ToUpperInvariant()); Unit outUnit = inUnit.Convert(currTable.CurrencyCode(to.ToUpperInvariant())); - await e.Channel.SendMessage(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false); } } catch //(Exception ex) { //Console.WriteLine(ex.ToString()); - await e.Channel.SendMessage("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false); + await channel.SendMessageAsync("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false); } }; diff --git a/src/NadekoBot/_Modules/Searches/Commands/EvalCommand.cs b/src/NadekoBot/_Modules/Searches/Commands/EvalCommand.cs index 4dd5a9fe..2e237162 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/EvalCommand.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/EvalCommand.cs @@ -34,10 +34,10 @@ namespace NadekoBot.Modules.Searches.Commands string answer = Evaluate(expression); if (answer == null) { - await e.Channel.SendMessage($"Expression {expression} failed to evaluate"); + await channel.SendMessageAsync($"Expression {expression} failed to evaluate"); return; } - await e.Channel.SendMessage($"⚙ `{answer}`"); + await channel.SendMessageAsync($"⚙ `{answer}`"); }; private string Evaluate(string expression) diff --git a/src/NadekoBot/_Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/_Modules/Searches/Commands/LoLCommands.cs index 5a5b766a..d5e11c92 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/LoLCommands.cs @@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Searches.Commands } if (data == null) { - await e.Channel.SendMessage("💢 Data for that role does not exist.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Data for that role does not exist.").ConfigureAwait(false); return; } } @@ -275,7 +275,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% catch (Exception ex) { Console.WriteLine(ex); - await e.Channel.SendMessage("💢 Failed retreiving data for that champion.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Failed retreiving data for that champion.").ConfigureAwait(false); } }); @@ -307,11 +307,11 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% //sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)"); } - await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); } catch (Exception) { - await e.Channel.SendMessage($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false); + await channel.SendMessageAsync($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false); } }); } diff --git a/src/NadekoBot/_Modules/Searches/Commands/MemegenCommands.cs b/src/NadekoBot/_Modules/Searches/Commands/MemegenCommands.cs index a7d23181..62c4779c 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/MemegenCommands.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/MemegenCommands.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Searches.Commands .Do(async e => { int i = 0; - await e.Channel.SendMessage("`List Of Commands:`\n```xl\n" + + await channel.SendMessageAsync("`List Of Commands:`\n```xl\n" + string.Join("\n", JsonConvert.DeserializeObject>(await SearchHelper.GetResponseStringAsync("http://memegen.link/templates/")) .Select(kvp => Path.GetFileName(kvp.Value)) .GroupBy(item => (i++) / 4) @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Searches.Commands var meme = e.GetArg("meme"); var top = Uri.EscapeDataString(e.GetArg("toptext").Replace(' ', '-')); var bot = Uri.EscapeDataString(e.GetArg("bottext").Replace(' ', '-')); - await e.Channel.SendMessage($"http://memegen.link/{meme}/{top}/{bot}.jpg"); + await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg"); }); } } diff --git a/src/NadekoBot/_Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/_Modules/Searches/Commands/OsuCommands.cs index 0532203d..94251751 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/OsuCommands.cs @@ -43,14 +43,14 @@ namespace NadekoBot.Modules.Searches.Commands try { await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).ConfigureAwait(false); - await e.Channel.SendMessage($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); + await channel.SendMessageAsync($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); } catch { } }; } catch { - await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Failed retrieving osu signature :\\").ConfigureAwait(false); } } }); @@ -62,7 +62,7 @@ namespace NadekoBot.Modules.Searches.Commands { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) { - await e.Channel.SendMessage("💢 An osu! API key is required.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false); return; } @@ -79,11 +79,11 @@ namespace NadekoBot.Modules.Searches.Commands var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss"); sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}"); sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}"); - await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Something went wrong."); + await channel.SendMessageAsync("Something went wrong."); } }); @@ -95,13 +95,13 @@ namespace NadekoBot.Modules.Searches.Commands { if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) { - await e.Channel.SendMessage("💢 An osu! API key is required.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(e.GetArg("usr"))) { - await e.Channel.SendMessage("💢 Please provide a username.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Please provide a username.").ConfigureAwait(false); return; } @@ -129,11 +129,11 @@ namespace NadekoBot.Modules.Searches.Commands sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}"); } sb.Append("```"); - await e.Channel.SendMessage(sb.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Something went wrong."); + await channel.SendMessageAsync("Something went wrong."); } }); } diff --git a/src/NadekoBot/_Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/_Modules/Searches/Commands/PokemonSearchCommands.cs index b2c13dca..723d58cc 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/PokemonSearchCommands.cs @@ -34,11 +34,11 @@ namespace NadekoBot.Modules.Searches.Commands { if (kvp.Key.ToUpperInvariant() == pok.ToUpperInvariant()) { - await e.Channel.SendMessage($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}"); + await channel.SendMessageAsync($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}"); return; } } - await e.Channel.SendMessage("`No pokemon found.`"); + await channel.SendMessageAsync("`No pokemon found.`"); }); cgb.CreateCommand(Prefix + "pokemonability") @@ -54,11 +54,11 @@ namespace NadekoBot.Modules.Searches.Commands { if (kvp.Key.ToUpperInvariant() == ab) { - await e.Channel.SendMessage($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}"); + await channel.SendMessageAsync($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}"); return; } } - await e.Channel.SendMessage("`No ability found.`"); + await channel.SendMessageAsync("`No ability found.`"); }); } } diff --git a/src/NadekoBot/_Modules/Searches/Commands/StreamNotifications.cs b/src/NadekoBot/_Modules/Searches/Commands/StreamNotifications.cs index f8720324..936ad52c 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/StreamNotifications.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/StreamNotifications.cs @@ -163,12 +163,12 @@ namespace NadekoBot.Modules.Searches.Commands })); if (streamStatus.Item1) { - await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); + await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`"); } } catch { - await e.Channel.SendMessage("No channel found."); + await channel.SendMessageAsync("No channel found."); } }); @@ -192,12 +192,12 @@ namespace NadekoBot.Modules.Searches.Commands })); if (streamStatus.Item1) { - await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); + await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`"); } } catch { - await e.Channel.SendMessage("No channel found."); + await channel.SendMessageAsync("No channel found."); } }); @@ -221,12 +221,12 @@ namespace NadekoBot.Modules.Searches.Commands })); if (streamStatus.Item1) { - await e.Channel.SendMessage($"`Streamer {streamStatus.Item2} is online.`"); + await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`"); } } catch { - await e.Channel.SendMessage("No channel found."); + await channel.SendMessageAsync("No channel found."); } }); @@ -249,13 +249,13 @@ namespace NadekoBot.Modules.Searches.Commands snc.Username.ToLower().Trim() == username); if (toRemove == null) { - await e.Channel.SendMessage(":anger: No such stream.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger: No such stream.").ConfigureAwait(false); return; } config.ObservingStreams.Remove(toRemove); await ConfigHandler.SaveConfig().ConfigureAwait(false); - await e.Channel.SendMessage($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false); + await channel.SendMessageAsync($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false); }); cgb.CreateCommand(Module.Prefix + "liststreams") @@ -274,7 +274,7 @@ namespace NadekoBot.Modules.Searches.Commands if (streamsArray.Length == 0) { - await e.Channel.SendMessage("You are not following any streams on this server.").ConfigureAwait(false); + await channel.SendMessageAsync("You are not following any streams on this server.").ConfigureAwait(false); return; } @@ -288,7 +288,7 @@ namespace NadekoBot.Modules.Searches.Commands return ""; })); - await e.Channel.SendMessage($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false); + await channel.SendMessageAsync($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false); }); } @@ -311,7 +311,7 @@ namespace NadekoBot.Modules.Searches.Commands var exists = config.ObservingStreams.Contains(stream); if (exists) { - await e.Channel.SendMessage(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false); return; } Tuple data; @@ -321,7 +321,7 @@ namespace NadekoBot.Modules.Searches.Commands } catch { - await e.Channel.SendMessage(":anger: Stream probably doesn't exist.").ConfigureAwait(false); + await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false); return; } var msg = $"Stream is currently **{(data.Item1 ? "ONLINE" : "OFFLINE")}** with **{data.Item2}** viewers"; @@ -337,7 +337,7 @@ namespace NadekoBot.Modules.Searches.Commands stream.LastStatus = data.Item1; if (!exists) msg = $":ok: I will notify this channel when status changes.\n{msg}"; - await e.Channel.SendMessage(msg).ConfigureAwait(false); + await channel.SendMessageAsync(msg).ConfigureAwait(false); config.ObservingStreams.Add(stream); }; } diff --git a/src/NadekoBot/_Modules/Searches/Commands/WowJokes.cs b/src/NadekoBot/_Modules/Searches/Commands/WowJokes.cs index b3e67eed..714d1a2d 100644 --- a/src/NadekoBot/_Modules/Searches/Commands/WowJokes.cs +++ b/src/NadekoBot/_Modules/Searches/Commands/WowJokes.cs @@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Searches.Commands { jokes = JsonConvert.DeserializeObject>(File.ReadAllText("data/wowjokes.json")); } - await e.Channel.SendMessage(jokes[new Random().Next(0, jokes.Count)].ToString()); + await channel.SendMessageAsync(jokes[new Random().Next(0, jokes.Count)].ToString()); }); } } diff --git a/src/NadekoBot/_Modules/Searches/SearchesModule.cs b/src/NadekoBot/_Modules/Searches/SearchesModule.cs index 2662107a..8280c0e2 100644 --- a/src/NadekoBot/_Modules/Searches/SearchesModule.cs +++ b/src/NadekoBot/_Modules/Searches/SearchesModule.cs @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Searches var obj = JObject.Parse(response)["weather"]; - await e.Channel.SendMessage( + await channel.SendMessageAsync( $@"🌍 **Weather for** 【{obj["target"]}】 📏 **Lat,Long:** ({obj["latitude"]}, {obj["longitude"]}) ☁ **Condition:** {obj["condition"]} 😓 **Humidity:** {obj["humidity"]}% 💨 **Wind Speed:** {obj["windspeedk"]}km/h / {obj["windspeedm"]}mph @@ -76,11 +76,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var link = await SearchHelper.FindYoutubeUrlByKeywords(e.GetArg("query")).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) { - await e.Channel.SendMessage("No results found for that query."); + await channel.SendMessageAsync("No results found for that query."); return; } var shortUrl = await SearchHelper.ShortenUrl(link).ConfigureAwait(false); - await e.Channel.SendMessage(shortUrl).ConfigureAwait(false); + await channel.SendMessageAsync(shortUrl).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "ani") @@ -97,11 +97,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】 } catch { - await e.Channel.SendMessage("Failed to find that anime.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false); return; } - await e.Channel.SendMessage(result.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(result.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "imdb") @@ -120,11 +120,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】 } catch { - await e.Channel.SendMessage("Failed to find that movie.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to find that movie.").ConfigureAwait(false); return; } - await e.Channel.SendMessage(result.ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(result.ToString()).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "mang") @@ -141,10 +141,10 @@ $@"🌍 **Weather for** 【{obj["target"]}】 } catch { - await e.Channel.SendMessage("Failed to find that anime.").ConfigureAwait(false); + await channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false); return; } - await e.Channel.SendMessage(result).ConfigureAwait(false); + await channel.SendMessageAsync(result).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "randomcat") @@ -152,7 +152,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Description($"Shows a random cat image. | `{Prefix}meow`") .Do(async e => { - await e.Channel.SendMessage(JObject.Parse( + await channel.SendMessageAsync(JObject.Parse( await SearchHelper.GetResponseStringAsync("http://www.random.cat/meow").ConfigureAwait(false))["file"].ToString()) .ConfigureAwait(false); }); @@ -162,7 +162,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Description($"Shows a random dog image. | `{Prefix}woof`") .Do(async e => { - await e.Channel.SendMessage("http://random.dog/" + await SearchHelper.GetResponseStringAsync("http://random.dog/woof").ConfigureAwait(false)).ConfigureAwait(false); + await channel.SendMessageAsync("http://random.dog/" + await SearchHelper.GetResponseStringAsync("http://random.dog/woof").ConfigureAwait(false)).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "i") @@ -176,17 +176,17 @@ $@"🌍 **Weather for** 【{obj["target"]}】 { var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}"; var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false)); - await e.Channel.SendMessage(obj["items"][0]["link"].ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(obj["items"][0]["link"].ToString()).ConfigureAwait(false); } catch (HttpRequestException exception) { if (exception.Message.Contains("403 (Forbidden)")) { - await e.Channel.SendMessage("Daily limit reached!"); + await channel.SendMessageAsync("Daily limit reached!"); } else { - await e.Channel.SendMessage("Something went wrong."); + await channel.SendMessageAsync("Something went wrong."); } } }); @@ -203,17 +203,17 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 50) }&fields=items%2Flink&key={NadekoBot.Creds.GoogleAPIKey}"; var obj = JObject.Parse(await SearchHelper.GetResponseStringAsync(reqString).ConfigureAwait(false)); var items = obj["items"] as JArray; - await e.Channel.SendMessage(items[0]["link"].ToString()).ConfigureAwait(false); + await channel.SendMessageAsync(items[0]["link"].ToString()).ConfigureAwait(false); } catch (HttpRequestException exception) { if (exception.Message.Contains("403 (Forbidden)")) { - await e.Channel.SendMessage("Daily limit reached!"); + await channel.SendMessageAsync("Daily limit reached!"); } else { - await e.Channel.SendMessage("Something went wrong."); + await channel.SendMessageAsync("Something went wrong."); } } }); @@ -224,7 +224,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Do(async e => { if (e.GetArg("ffs") == null || e.GetArg("ffs").Length < 1) return; - await e.Channel.SendMessage(await $"http://lmgtfy.com/?q={ Uri.EscapeUriString(e.GetArg("ffs").ToString()) }".ShortenUrl()) + await channel.SendMessageAsync(await $"http://lmgtfy.com/?q={ Uri.EscapeUriString(e.GetArg("ffs").ToString()) }".ShortenUrl()) .ConfigureAwait(false); }); @@ -237,7 +237,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var terms = e.GetArg("terms")?.Trim(); if (string.IsNullOrWhiteSpace(terms)) return; - await e.Channel.SendMessage($"https://google.com/search?q={ HttpUtility.UrlEncode(terms).Replace(' ', '+') }") + await channel.SendMessageAsync($"https://google.com/search?q={ HttpUtility.UrlEncode(terms).Replace(' ', '+') }") .ConfigureAwait(false); }); @@ -249,7 +249,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var arg = e.GetArg("name"); if (string.IsNullOrWhiteSpace(arg)) { - await e.Channel.SendMessage("💢 Please enter a card name to search for.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Please enter a card name to search for.").ConfigureAwait(false); return; } await e.Channel.SendIsTyping().ConfigureAwait(false); @@ -271,14 +271,14 @@ $@"🌍 **Weather for** 【{obj["target"]}】 } if (items.Count > 4) { - await e.Channel.SendMessage("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false); + await channel.SendMessageAsync("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false); } await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png)) .ConfigureAwait(false); } catch (Exception ex) { - await e.Channel.SendMessage($"💢 Error {ex.Message}").ConfigureAwait(false); + await channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false); } }); @@ -290,7 +290,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var arg = e.GetArg("query"); if (string.IsNullOrWhiteSpace(arg)) { - await e.Channel.SendMessage("💢 Please enter a search term.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Please enter a search term.").ConfigureAwait(false); return; } await e.Channel.SendIsTyping().ConfigureAwait(false); @@ -303,11 +303,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】 sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}"); sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl().ConfigureAwait(false)}>"); - await e.Channel.SendMessage(sb.ToString()); + await channel.SendMessageAsync(sb.ToString()); } catch { - await e.Channel.SendMessage("💢 Failed finding a definition for that term.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Failed finding a definition for that term.").ConfigureAwait(false); } }); // thanks to Blaubeerwald @@ -319,7 +319,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var arg = e.GetArg("query"); if (string.IsNullOrWhiteSpace(arg)) { - await e.Channel.SendMessage("💢 Please enter a search term.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Please enter a search term.").ConfigureAwait(false); return; } await e.Channel.SendIsTyping().ConfigureAwait(false); @@ -332,11 +332,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】 sb.AppendLine($"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}"); sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}"); sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl().ConfigureAwait(false)}>"); - await e.Channel.SendMessage(sb.ToString()); + await channel.SendMessageAsync(sb.ToString()); } catch { - await e.Channel.SendMessage("💢 Failed finidng a definition for that tag.").ConfigureAwait(false); + await channel.SendMessageAsync("💢 Failed finidng a definition for that tag.").ConfigureAwait(false); } }); @@ -345,7 +345,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Do(async e => { var quote = NadekoBot.Config.Quotes[rng.Next(0, NadekoBot.Config.Quotes.Count)].ToString(); - await e.Channel.SendMessage(quote).ConfigureAwait(false); + await channel.SendMessageAsync(quote).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "catfact") @@ -355,7 +355,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var response = await SearchHelper.GetResponseStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false); if (response == null) return; - await e.Channel.SendMessage($"🐈 `{JObject.Parse(response)["facts"][0].ToString()}`").ConfigureAwait(false); + await channel.SendMessageAsync($"🐈 `{JObject.Parse(response)["facts"][0].ToString()}`").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "yomama") @@ -364,7 +364,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Do(async e => { var response = await SearchHelper.GetResponseStringAsync("http://api.yomomma.info/").ConfigureAwait(false); - await e.Channel.SendMessage("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); + await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "randjoke") @@ -373,7 +373,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Do(async e => { var response = await SearchHelper.GetResponseStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false); - await e.Channel.SendMessage("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); + await channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "chucknorris") @@ -382,7 +382,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 .Do(async e => { var response = await SearchHelper.GetResponseStringAsync("http://api.icndb.com/jokes/random/").ConfigureAwait(false); - await e.Channel.SendMessage("`" + JObject.Parse(response)["value"]["joke"].ToString() + "` 😆").ConfigureAwait(false); + await channel.SendMessageAsync("`" + JObject.Parse(response)["value"]["joke"].ToString() + "` 😆").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "magicitem") @@ -393,7 +393,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var magicItems = JsonConvert.DeserializeObject>(File.ReadAllText("data/magicitems.json")); var item = magicItems[rng.Next(0, magicItems.Count)].ToString(); - await e.Channel.SendMessage(item).ConfigureAwait(false); + await channel.SendMessageAsync(item).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "revav") @@ -410,7 +410,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 if (usr == null || string.IsNullOrWhiteSpace(usr.AvatarUrl)) return; - await e.Channel.SendMessage($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); + await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "revimg") @@ -422,7 +422,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 if (string.IsNullOrWhiteSpace(imgLink)) return; - await e.Channel.SendMessage($"https://images.google.com/searchbyimage?image_url={imgLink}").ConfigureAwait(false); + await channel.SendMessageAsync($"https://images.google.com/searchbyimage?image_url={imgLink}").ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "safebooru") @@ -433,9 +433,9 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var tag = e.GetArg("tag")?.Trim() ?? ""; var link = await SearchHelper.GetSafebooruImageLink(tag).ConfigureAwait(false); if (link == null) - await e.Channel.SendMessage("`No results.`"); + await channel.SendMessageAsync("`No results.`"); else - await e.Channel.SendMessage(link).ConfigureAwait(false); + await channel.SendMessageAsync(link).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "wiki") @@ -447,9 +447,9 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var result = await SearchHelper.GetResponseStringAsync("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 e.Channel.SendMessage("`That page could not be found.`"); + await channel.SendMessageAsync("`That page could not be found.`"); else - await e.Channel.SendMessage(data.Query.Pages[0].FullUrl); + await channel.SendMessageAsync(data.Query.Pages[0].FullUrl); }); cgb.CreateCommand(Prefix + "clr") @@ -508,10 +508,10 @@ $@"🌍 **Weather for** 【{obj["target"]}】 var usr = e.Channel.FindUsers(e.GetArg("mention")).FirstOrDefault(); if (usr == null) { - await e.Channel.SendMessage("Invalid user specified.").ConfigureAwait(false); + await channel.SendMessageAsync("Invalid user specified.").ConfigureAwait(false); return; } - await e.Channel.SendMessage(await usr.AvatarUrl.ShortenUrl()).ConfigureAwait(false); + await channel.SendMessageAsync(await usr.AvatarUrl.ShortenUrl()).ConfigureAwait(false); }); }); diff --git a/src/NadekoBot/_Modules/Translator/TranslateCommand.cs b/src/NadekoBot/_Modules/Translator/TranslateCommand.cs index e54aa020..ded3a0d3 100644 --- a/src/NadekoBot/_Modules/Translator/TranslateCommand.cs +++ b/src/NadekoBot/_Modules/Translator/TranslateCommand.cs @@ -32,12 +32,12 @@ namespace NadekoBot.Modules.Translator return; string translation = await t.Translate(text, from, to).ConfigureAwait(false); - await e.Channel.SendMessage(translation).ConfigureAwait(false); + await channel.SendMessageAsync(translation).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine(ex); - await e.Channel.SendMessage("Bad input format, or something went wrong...").ConfigureAwait(false); + await channel.SendMessageAsync("Bad input format, or something went wrong...").ConfigureAwait(false); } }; diff --git a/src/NadekoBot/_Modules/Translator/ValidLanguagesCommand.cs b/src/NadekoBot/_Modules/Translator/ValidLanguagesCommand.cs index 438e77de..e727dd66 100644 --- a/src/NadekoBot/_Modules/Translator/ValidLanguagesCommand.cs +++ b/src/NadekoBot/_Modules/Translator/ValidLanguagesCommand.cs @@ -38,11 +38,11 @@ namespace NadekoBot.Modules.Translator ret += " " + key + ";"; } } - await e.Channel.SendMessage(ret).ConfigureAwait(false); + await channel.SendMessageAsync(ret).ConfigureAwait(false); } catch { - await e.Channel.SendMessage("Bad input format, or sth went wrong...").ConfigureAwait(false); + await channel.SendMessageAsync("Bad input format, or sth went wrong...").ConfigureAwait(false); } }; diff --git a/src/NadekoBot/_Modules/Trello/TrelloModule.cs b/src/NadekoBot/_Modules/Trello/TrelloModule.cs index 176ca2b8..b424c6eb 100644 --- a/src/NadekoBot/_Modules/Trello/TrelloModule.cs +++ b/src/NadekoBot/_Modules/Trello/TrelloModule.cs @@ -82,7 +82,7 @@ namespace NadekoBot.Modules.Trello bound = e.Channel; board = new Board(e.GetArg("board_id").Trim()); board.Refresh(); - await e.Channel.SendMessage("Successfully bound to this channel and board " + board.Name); + await channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name); t.Start(); } catch (Exception ex) @@ -100,7 +100,7 @@ namespace NadekoBot.Modules.Trello t.Stop(); bound = null; board = null; - await e.Channel.SendMessage("Successfully unbound trello from this channel.").ConfigureAwait(false); + await channel.SendMessageAsync("Successfully unbound trello from this channel.").ConfigureAwait(false); }); @@ -111,7 +111,7 @@ namespace NadekoBot.Modules.Trello { if (!NadekoBot.IsOwner(e.User.Id)) return; if (bound == null || board == null || bound != e.Channel) return; - await e.Channel.SendMessage("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**"))) + await channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**"))) .ConfigureAwait(false); }); @@ -133,10 +133,10 @@ namespace NadekoBot.Modules.Trello if (list != null) - await e.Channel.SendMessage("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**"))) + await channel.SendMessageAsync("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**"))) .ConfigureAwait(false); else - await e.Channel.SendMessage("No such list.") + await channel.SendMessageAsync("No such list.") .ConfigureAwait(false); }); }); diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.dll b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.dll index f58c84d5..ff977cfc 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.dll and b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.dll differ diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.pdb b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.pdb index 9dd0af16..5714ebba 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.pdb and b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.Commands.pdb differ diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.dll b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.dll index 063e73d3..6c092ad8 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.dll and b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.dll differ diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.pdb b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.pdb index 24d16752..ee65f8ec 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.pdb and b/src/NadekoBot/bin/Debug/netcoreapp1.0/Discord.Net.pdb differ diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.dll b/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.dll index a5e6718a..73139e28 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.dll and b/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.dll differ diff --git a/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.pdb b/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.pdb index ea72d44c..5fc37e87 100644 Binary files a/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.pdb and b/src/NadekoBot/bin/Debug/netcoreapp1.0/NadekoBot.pdb differ