diff --git a/src/NadekoBot/Classes/NadekoStats.cs b/src/NadekoBot/Classes/NadekoStats.cs index ae83dc3b..49038e98 100644 --- a/src/NadekoBot/Classes/NadekoStats.cs +++ b/src/NadekoBot/Classes/NadekoStats.cs @@ -115,13 +115,13 @@ namespace NadekoBot HttpClient carbonClient = new HttpClient(); private async Task SendUpdateToCarbon() { - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.CarbonKey)) + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.CarbonKey)) return; try { using (var content = new FormUrlEncodedContent(new Dictionary { { "servercount", NadekoBot.Client.Servers.Count().ToString() }, - { "key", NadekoBot.Creds.CarbonKey } + { "key", NadekoBot.Credentials.CarbonKey } })) { content.Headers.Clear(); @@ -155,7 +155,7 @@ namespace NadekoBot sb.AppendLine($"`Bot Version: {BotVersion}`"); sb.AppendLine($"`Bot id: {NadekoBot.Client.CurrentUser.Id}`"); sb.Append("`Owners' Ids:` "); - sb.AppendLine("`" + String.Join(", ", NadekoBot.Creds.OwnerIds) + "`"); + sb.AppendLine("`" + String.Join(", ", NadekoBot.Credentials.OwnerIds) + "`"); sb.AppendLine($"`Uptime: {GetUptimeString()}`"); sb.Append($"`Servers: {ServerCount}"); sb.Append($" | TextChannels: {TextChannelsCount}"); diff --git a/src/NadekoBot/Classes/SearchHelper.cs b/src/NadekoBot/Classes/SearchHelper.cs index 1339c9d8..8b434786 100644 --- a/src/NadekoBot/Classes/SearchHelper.cs +++ b/src/NadekoBot/Classes/SearchHelper.cs @@ -147,14 +147,14 @@ namespace NadekoBot.Classes return $"https://www.youtube.com/watch?v={match.Groups["id"].Value}"; } - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.GoogleAPIKey)) throw new InvalidCredentialException("Google API Key is missing."); var response = await GetResponseStringAsync( $"https://www.googleapis.com/youtube/v3/search?" + $"part=snippet&maxResults=1" + $"&q={Uri.EscapeDataString(keywords)}" + - $"&key={NadekoBot.Creds.GoogleAPIKey}").ConfigureAwait(false); + $"&key={NadekoBot.Credentials.GoogleAPIKey}").ConfigureAwait(false); JObject obj = JObject.Parse(response); var data = JsonConvert.DeserializeObject(response); @@ -181,7 +181,7 @@ namespace NadekoBot.Classes $"https://www.googleapis.com/youtube/v3/search?" + $"part=snippet&maxResults={count}&type=video" + $"&relatedToVideoId={id}" + - $"&key={NadekoBot.Creds.GoogleAPIKey}").ConfigureAwait(false); + $"&key={NadekoBot.Credentials.GoogleAPIKey}").ConfigureAwait(false); JObject obj = JObject.Parse(response); var data = JsonConvert.DeserializeObject(response); @@ -191,7 +191,7 @@ namespace NadekoBot.Classes public static async Task GetPlaylistIdByKeyword(string query) { - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.GoogleAPIKey)) throw new ArgumentNullException(nameof(query)); var match = new Regex("(?:youtu\\.be\\/|list=)(?[\\da-zA-Z\\-_]*)").Match(query); if (match.Length > 1) @@ -201,7 +201,7 @@ namespace NadekoBot.Classes var link = "https://www.googleapis.com/youtube/v3/search?part=snippet" + "&maxResults=1&type=playlist" + $"&q={Uri.EscapeDataString(query)}" + - $"&key={NadekoBot.Creds.GoogleAPIKey}"; + $"&key={NadekoBot.Credentials.GoogleAPIKey}"; var response = await GetResponseStringAsync(link).ConfigureAwait(false); var data = JsonConvert.DeserializeObject(response); @@ -212,7 +212,7 @@ namespace NadekoBot.Classes public static async Task> GetVideoIDs(string playlist, int number = 50) { - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.GoogleAPIKey)) { throw new ArgumentNullException(nameof(playlist)); } @@ -231,7 +231,7 @@ namespace NadekoBot.Classes $"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails" + $"&maxResults={toGet}" + $"&playlistId={playlist}" + - $"&key={NadekoBot.Creds.GoogleAPIKey}"; + $"&key={NadekoBot.Credentials.GoogleAPIKey}"; if (!string.IsNullOrWhiteSpace(nextPageToken)) link += $"&pageToken={nextPageToken}"; var response = await GetResponseStringAsync(link).ConfigureAwait(false); @@ -245,12 +245,12 @@ namespace NadekoBot.Classes public static async Task ShortenUrl(string url) { - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) return url; + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.GoogleAPIKey)) return url; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + - NadekoBot.Creds.GoogleAPIKey); + NadekoBot.Credentials.GoogleAPIKey); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; diff --git a/src/NadekoBot/Modules/Administration/AdministrationModule.cs b/src/NadekoBot/Modules/Administration/AdministrationModule.cs index b6f14069..387d3d78 100644 --- a/src/NadekoBot/Modules/Administration/AdministrationModule.cs +++ b/src/NadekoBot/Modules/Administration/AdministrationModule.cs @@ -494,10 +494,10 @@ namespace NadekoBot.Modules.Administration //{ // var channel = imsg.Channel as ITextChannel; - // if (string.IsNullOrWhiteSpace(e.GetArg("img"))) + // if (string.IsNullOrWhiteSpace(img)) // return; // // Gather user provided URL. - // var avatarAddress = e.GetArg("img"); + // var avatarAddress = img; // var imageStream = await SearchHelper.GetResponseStreamAsync(avatarAddress).ConfigureAwait(false); // var image = System.Drawing.Image.FromStream(imageStream); // await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false); @@ -515,7 +515,7 @@ namespace NadekoBot.Modules.Administration // game = game ?? ""; - // client.SetGame(e.GetArg("set_game")); + // client.SetGame(set_game); //} ////todo owner only @@ -570,8 +570,8 @@ namespace NadekoBot.Modules.Administration //public async Task Donadd(IMessage imsg, IUser donator, int amount) //{ // var channel = imsg.Channel as ITextChannel; - // var donator = channel.Guild.FindUsers(e.GetArg("donator")).FirstOrDefault(); - // var amount = int.Parse(e.GetArg("amount")); + // var donator = channel.Guild.FindUsers(donator).FirstOrDefault(); + // var amount = int.Parse(amount); // if (donator == null) return; // try // { diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 66f31d8f..81343c62 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -86,7 +86,7 @@ // .Do(async e => // { // int token; -// if (!int.TryParse(e.GetArg("token"), out token)) +// if (!int.TryParse(token, out token)) // return; // HashSet set; // if (!Subscribers.TryGetValue(token, out set)) diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 498621c6..a2ba8b43 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -456,7 +456,7 @@ // { // var config = SpecificConfigurations.Default.Of(e.Server.Id); -// if (e.GetArg("all")?.ToLower() == "all") +// if (all?.ToLower() == "all") // { // foreach (var voiceChannel in e.Server.VoiceChannels) // { diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 6192ea95..0be2230e 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -80,8 +80,8 @@ // .AddCheck(SimpleCheckers.ManageMessages()) // .Do(async e => // { -// var minutesStr = e.GetArg("minutes"); -// var msg = e.GetArg("msg"); +// var minutesStr = minutes; +// var msg = msg; // // if both null, disable // if (string.IsNullOrWhiteSpace(msg) && string.IsNullOrWhiteSpace(minutesStr)) diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotate.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotate.cs index 6b105a37..d1537e50 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotate.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotate.cs @@ -109,7 +109,7 @@ // .AddCheck(SimpleCheckers.OwnerOnly()) // .Do(async e => // { -// var arg = e.GetArg("text"); +// var arg = text; // if (string.IsNullOrWhiteSpace(arg)) // return; // await playingPlaceholderLock.WaitAsync().ConfigureAwait(false); @@ -149,7 +149,7 @@ // .AddCheck(SimpleCheckers.OwnerOnly()) // .Do(async e => // { -// var arg = e.GetArg("number"); +// var arg = number; // int num; // string str; // await playingPlaceholderLock.WaitAsync().ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs index 7bb9235a..7171a63d 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -49,7 +49,7 @@ // .AddCheck(SimpleCheckers.CanManageRoles) // .Do(async e => // { -// var roleName = e.GetArg("role")?.Trim(); +// var roleName = role?.Trim(); // if (string.IsNullOrWhiteSpace(roleName)) // return; // var role = e.Server.FindRoles(roleName).FirstOrDefault(); @@ -116,7 +116,7 @@ // .Parameter("role", ParameterType.Unparsed) // .Do(async e => // { -// var roleName = e.GetArg("role")?.Trim(); +// var roleName = role?.Trim(); // if (string.IsNullOrWhiteSpace(roleName)) // return; // var role = e.Server.FindRoles(roleName).FirstOrDefault(); @@ -172,7 +172,7 @@ // .Parameter("role", ParameterType.Unparsed) // .Do(async e => // { -// var roleName = e.GetArg("role")?.Trim(); +// var roleName = role?.Trim(); // if (string.IsNullOrWhiteSpace(roleName)) // return; // var role = e.Server.FindRoles(roleName).FirstOrDefault(); diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs index 4fa51a62..ccd20a36 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommand.cs @@ -240,14 +240,14 @@ // { // if (!imsg.Author.ServerPermissions.ManageServer) return; // var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); -// if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) +// if (string.IsNullOrWhiteSpace(msg)) // { // await channel.SendMessageAsync("`Current greet message:` " + ann.GreetText); // return; // } -// ann.GreetText = e.GetArg("msg"); +// ann.GreetText = msg; // await channel.SendMessageAsync("New greet message set.").ConfigureAwait(false); // if (!ann.Greet) // await channel.SendMessageAsync("Enable greet messsages by typing `.greet`").ConfigureAwait(false); @@ -273,13 +273,13 @@ // { // if (!imsg.Author.ServerPermissions.ManageServer) return; // var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id)); -// if (string.IsNullOrWhiteSpace(e.GetArg("msg"))) +// if (string.IsNullOrWhiteSpace(msg)) // { // await channel.SendMessageAsync("`Current bye message:` " + ann.ByeText); // return; // } -// ann.ByeText = e.GetArg("msg"); +// ann.ByeText = msg; // await channel.SendMessageAsync("New bye message set.").ConfigureAwait(false); // if (!ann.Bye) // await channel.SendMessageAsync("Enable bye messsages by typing `.bye`.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index c2744de7..75939c89 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -53,7 +53,7 @@ // try // { // var num = 1; -// var isParsed = int.TryParse(e.GetArg("count"), out num); +// var isParsed = int.TryParse(count, out num); // if (!isParsed || num < 2) // { // var c = cards.DrawACard(); diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 32e2f938..3b0b9401 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -34,9 +34,9 @@ // public Func BetFlipCoinFunc() => async e => // { -// var amountstr = e.GetArg("amount").Trim(); +// var amountstr = amount.Trim(); -// var guessStr = e.GetArg("guess").Trim().ToUpperInvariant(); +// var guessStr = guess.Trim().ToUpperInvariant(); // if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS") // return; @@ -82,7 +82,7 @@ // public Func FlipCoinFunc() => async e => // { -// if (e.GetArg("count") == "") +// if (count == "") // { // if (rng.Next(0, 2) == 1) // await e.Channel.SendFile("heads.png", Properties.Resources.heads.ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false); @@ -92,7 +92,7 @@ // else // { // int result; -// if (int.TryParse(e.GetArg("count"), out result)) +// if (int.TryParse(count, out result)) // { // if (result > 10) // result = 10; diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 9262678b..b670c633 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -131,7 +131,7 @@ // .Parameter("cd", ParameterType.Unparsed) // .Do(async e => // { -// var cdStr = e.GetArg("cd"); +// var cdStr = cd; // int cd = 2; // if (!int.TryParse(cdStr, out cd) || cd < 0) // { diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index cd561349..eb5e8a9f 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -181,11 +181,11 @@ // .Parameter("text", ParameterType.Unparsed) // .Do(async e => // { -// if (!NadekoBot.IsOwner(imsg.Author.Id) || string.IsNullOrWhiteSpace(e.GetArg("text"))) return; +// if (!NadekoBot.IsOwner(imsg.Author.Id) || string.IsNullOrWhiteSpace(text)) return; // DbHandler.Instance.Connection.Insert(new TypingArticle // { -// Text = e.GetArg("text"), +// Text = text, // DateAdded = DateTime.Now // }); diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 269ce7ce..b3977f5a 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -11,6 +11,7 @@ using System.Text.RegularExpressions; using System.Xml.Linq; using System.Net; using Discord.WebSocket; +using NadekoBot.Extensions; namespace NadekoBot.Modules.NSFW { @@ -173,9 +174,7 @@ namespace NadekoBot.Modules.NSFW { using (var http = new HttpClient()) { - http.DefaultRequestHeaders.Clear(); - http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); - http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + http.AddFakeHeaders(); var webpage = await http.GetStringAsync("http://gelbooru.com/index.php?page=dapi&s=post&q=index&limit=100&tags="+ tag.Replace(" ", "_")).ConfigureAwait(false); var matches = Regex.Matches(webpage, "file_url=\"(?.*?)\""); @@ -211,9 +210,7 @@ namespace NadekoBot.Modules.NSFW { using (var http = new HttpClient()) { - http.DefaultRequestHeaders.Clear(); - http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); - http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + http.AddFakeHeaders(); var data = await http.GetStreamAsync("http://e621.net/post/index.xml?tags=" + Uri.EscapeUriString(tags) + "%20order:random&limit=1"); var doc = XDocument.Load(data); return doc.Descendants("file_url").FirstOrDefault().Value; diff --git a/src/NadekoBot/Modules/Searches/Commands/ConverterCommands.cs b/src/NadekoBot/Modules/Searches/Commands/ConverterCommands.cs index 14651abb..52a6d157 100644 --- a/src/NadekoBot/Modules/Searches/Commands/ConverterCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/ConverterCommands.cs @@ -72,11 +72,11 @@ // { // await e.Channel.SendIsTyping().ConfigureAwait(false); -// string from = e.GetArg("from-to").ToLowerInvariant().Split('>')[0]; -// string to = e.GetArg("from-to").ToLowerInvariant().Split('>')[1]; +// string from = from-to.ToLowerInvariant().Split('>')[0]; +// string to = from-to.ToLowerInvariant().Split('>')[1]; // float quantity = 1.0f; -// if (!float.TryParse(e.GetArg("quantity"), out quantity)) +// if (!float.TryParse(quantity, out quantity)) // { // quantity = 1.0f; // } diff --git a/src/NadekoBot/Modules/Searches/Commands/EvalCommand.cs b/src/NadekoBot/Modules/Searches/Commands/EvalCommand.cs index 617682d2..5c8e45ad 100644 --- a/src/NadekoBot/Modules/Searches/Commands/EvalCommand.cs +++ b/src/NadekoBot/Modules/Searches/Commands/EvalCommand.cs @@ -27,7 +27,7 @@ // private CustomParser parser = new CustomParser(); // private Func EvalFunc() => async e => // { -// string expression = e.GetArg("expression")?.Trim(); +// string expression = expression?.Trim(); // if (string.IsNullOrWhiteSpace(expression)) // { // return; diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index dfc25b3e..1a4a5de9 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -124,9 +124,9 @@ namespace NadekoBot.Modules.Searches // try // { // //get role -// var role = ResolvePos(e.GetArg("position")); +// var role = ResolvePos(position); // var resolvedRole = role; -// var name = e.GetArg("champ").Replace(" ", "").ToLower(); +// var name = champ.Replace(" ", "").ToLower(); // CachedChampion champ = null; // if (CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ)) @@ -136,7 +136,7 @@ namespace NadekoBot.Modules.Searches // await e.Channel.SendFile("champ.png", champ.ImageStream).ConfigureAwait(false); // return; // } -// var allData = JArray.Parse(await Classes.http.GetStringAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}").ConfigureAwait(false)); +// var allData = JArray.Parse(await Classes.http.GetStringAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Credentials.LOLAPIKey}").ConfigureAwait(false)); // JToken data = null; // if (role != null) // { @@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Searches // roles[i] = ">" + roles[i] + "<"; // } // var general = JArray.Parse(await http.GetStringAsync($"http://api.champion.gg/stats/" + -// $"champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}") +// $"champs/{name}?api_key={NadekoBot.Credentials.LOLAPIKey}") // .ConfigureAwait(false)) // .FirstOrDefault(jt => jt["role"].ToString() == role)?["general"]; // if (general == null) diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index 3731ff8c..19479696 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -1,269 +1,277 @@ -ο»Ώ//using Discord.Commands; -//using NadekoBot.Classes; -//using Newtonsoft.Json.Linq; -//using System; -//using System.IO; -//using System.Net; -//using System.Text.RegularExpressions; +ο»Ώusing Discord; +using Discord.Commands; +using NadekoBot.Attributes; +using NadekoBot.Classes; +using NadekoBot.Extensions; +using Newtonsoft.Json.Linq; +using NLog; +using System; +using System.Globalization; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.RegularExpressions; +using System.Threading.Tasks; -//todo DI into partials -//namespace NadekoBot.Modules.Searches -//{ -// internal class OsuCommands : DiscordCommand -// { -// public OsuCommands(DiscordModule module) : base(module) -// { -// } +namespace NadekoBot.Modules.Searches +{ + public partial class Searches + { + [Group] + public class OsuCommands + { + private Logger _log; -// internal override void Init(CommandGroupBuilder cgb) -// { -// cgb.CreateCommand(Module.Prefix + "osu") -// .Description($"Shows osu stats for a player. | `{Prefix}osu Name` or `{Prefix}osu Name taiko`") -// .Parameter("usr", ParameterType.Required) -// .Parameter("mode", ParameterType.Unparsed) -// .Do(async e => -// { -// if (string.IsNullOrWhiteSpace(e.GetArg("usr"))) -// return; + public OsuCommands() + { + _log = LogManager.GetCurrentClassLogger(); + } + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Osu(IMessage imsg, string usr, string mode) + { + var channel = imsg.Channel as ITextChannel; -// using (WebClient cl = new WebClient()) -// { -// try -// { -// var m = 0; -// if (!string.IsNullOrWhiteSpace(e.GetArg("mode"))) -// { -// m = ResolveGameMode(e.GetArg("mode")); -// } + if (string.IsNullOrWhiteSpace(usr)) + return; -// cl.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); -// cl.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; Win64; x64)"); -// cl.DownloadDataAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ e.GetArg("usr") }&flagshadow&xpbar&xpbarhex&pp=2&mode={m}")); -// cl.DownloadDataCompleted += async (s, cle) => -// { -// try -// { -// await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).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 channel.SendMessageAsync("πŸ’’ Failed retrieving osu signature :\\").ConfigureAwait(false); -// } -// } -// }); + using (HttpClient http = new HttpClient()) + { + try + { + var m = 0; + if (!string.IsNullOrWhiteSpace(mode)) + { + m = ResolveGameMode(mode); + } + http.AddFakeHeaders(); + var res = await http.GetStreamAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ usr }&flagshadow&xpbar&xpbarhex&pp=2&mode={m}")).ConfigureAwait(false); -// cgb.CreateCommand(Module.Prefix + "osu b") -// .Description($"Shows information about an osu beatmap. |`{Prefix}osu b` https://osu.ppy.sh/s/127712`") -// .Parameter("map", ParameterType.Unparsed) -// .Do(async e => -// { -// if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) -// { -// await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); -// return; -// } + res.Position = 0; + await channel.SendFileAsync(res, $"{usr}.png").ConfigureAwait(false); + await channel.SendMessageAsync($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(usr)}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); + } + catch (Exception ex) + { + await channel.SendMessageAsync("πŸ’’ Failed retrieving osu signature :\\").ConfigureAwait(false); + _log.Warn(ex, "Osu command failed"); + } + } + } -// if (string.IsNullOrWhiteSpace(e.GetArg("map"))) -// return; + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Osub(IMessage imsg, [Remainder] string map) + { + var channel = imsg.Channel as ITextChannel; -// try -// { -// var mapId = ResolveMap(e.GetArg("map")); -// var reqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&{mapId}"; -// var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false))[0]; -// var sb = new System.Text.StringBuilder(); -// var starRating = Math.Round(Double.Parse($"{obj["difficultyrating"]}", CultureInfo.InvariantCulture), 2); -// 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 channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); -// } -// catch -// { -// await channel.SendMessageAsync("Something went wrong."); -// } -// }); + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) + { + await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); + return; + } -// cgb.CreateCommand(Module.Prefix + "osu top5") -// .Description($"Displays a user's top 5 plays. |`{Prefix}osu top5 Name`") -// .Parameter("usr", ParameterType.Required) -// .Parameter("mode", ParameterType.Unparsed) -// .Do(async e => -// { -// if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey)) -// { -// await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); -// return; -// } + if (string.IsNullOrWhiteSpace(map)) + return; -// if (string.IsNullOrWhiteSpace(e.GetArg("usr"))) -// { -// await channel.SendMessageAsync("πŸ’’ Please provide a username.").ConfigureAwait(false); -// return; -// } + try + { + using (var http = new HttpClient()) + { + var mapId = ResolveMap(map); + var reqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Credentials.OsuApiKey}&{mapId}"; + var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false))[0]; + var sb = new System.Text.StringBuilder(); + var starRating = Math.Round(Double.Parse($"{obj["difficultyrating"]}", CultureInfo.InvariantCulture), 2); + 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 channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); + } + } + catch (Exception ex) + { + await channel.SendMessageAsync("Something went wrong."); + _log.Warn(ex, "Osub command failed"); + } + } -// try -// { -// var m = 0; -// if (!string.IsNullOrWhiteSpace(e.GetArg("mode"))) -// { -// m = ResolveGameMode(e.GetArg("mode")); -// } + [LocalizedCommand, LocalizedDescription, LocalizedSummary] + [RequireContext(ContextType.Guild)] + public async Task Osu5(IMessage imsg, string user, [Remainder] string mode) + { + var channel = imsg.Channel as ITextChannel; + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) + { + await channel.SendMessageAsync("πŸ’’ An osu! API key is required.").ConfigureAwait(false); + return; + } -// var reqString = $"https://osu.ppy.sh/api/get_user_best?k={NadekoBot.Creds.OsuAPIKey}&u={Uri.EscapeDataString(e.GetArg("usr"))}&type=string&limit=5&m={m}"; -// var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); -// var sb = new System.Text.StringBuilder($"`Top 5 plays for {e.GetArg("usr")}:`\n```xl" + Environment.NewLine); -// foreach (var item in obj) -// { -// var mapReqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&b={item["beatmap_id"]}"; -// var map = JArray.Parse(await http.GetStringAsync(mapReqString).ConfigureAwait(false))[0]; -// var pp = Math.Round(Double.Parse($"{item["pp"]}", CultureInfo.InvariantCulture), 2); -// var acc = CalculateAcc(item, m); -// var mods = ResolveMods(Int32.Parse($"{item["enabled_mods"]}")); -// if (mods != "+") -// sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | **{mods,-10}** | /b/{item["beatmap_id"]}"); -// else -// sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}"); -// } -// sb.Append("```"); -// await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); -// } -// catch -// { -// await channel.SendMessageAsync("Something went wrong."); -// } -// }); -// } + if (string.IsNullOrWhiteSpace(user)) + { + await channel.SendMessageAsync("πŸ’’ Please provide a username.").ConfigureAwait(false); + return; + } + using (var http = new HttpClient()) + { + try + { + var m = 0; + if (!string.IsNullOrWhiteSpace(mode)) + { + m = ResolveGameMode(mode); + } -// //https://osu.ppy.sh/wiki/Accuracy -// private static Double CalculateAcc(JToken play, int mode) -// { -// if (mode == 0) -// { -// var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["count300"]}") * 300; -// var totalHits = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countmiss"]}"); -// totalHits *= 300; -// return Math.Round(hitPoints / totalHits * 100, 2); -// } -// else if (mode == 1) -// { -// var hitPoints = Double.Parse($"{play["countmiss"]}") * 0 + Double.Parse($"{play["count100"]}") * 0.5 + Double.Parse($"{play["count300"]}") * 1; -// var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}"); -// hitPoints *= 300; -// totalHits *= 300; -// return Math.Round(hitPoints / totalHits * 100, 2); -// } -// else if (mode == 2) -// { -// var fruitsCaught = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}"); -// var totalFruits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countkatu"]}"); -// return Math.Round(fruitsCaught / totalFruits * 100, 2); -// } -// else -// { -// var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["countkatu"]}") * 200 + (Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}")) * 300; -// var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["countkatu"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}"); -// totalHits *= 300; -// return Math.Round(hitPoints / totalHits * 100, 2); -// } -// } + var reqString = $"https://osu.ppy.sh/api/get_user_best?k={NadekoBot.Credentials.OsuApiKey}&u={Uri.EscapeDataString(user)}&type=string&limit=5&m={m}"; + var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); + var sb = new System.Text.StringBuilder($"`Top 5 plays for {user}:`\n```xl" + Environment.NewLine); + foreach (var item in obj) + { + var mapReqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Credentials.OsuApiKey}&b={item["beatmap_id"]}"; + var map = JArray.Parse(await http.GetStringAsync(mapReqString).ConfigureAwait(false))[0]; + var pp = Math.Round(Double.Parse($"{item["pp"]}", CultureInfo.InvariantCulture), 2); + var acc = CalculateAcc(item, m); + var mods = ResolveMods(Int32.Parse($"{item["enabled_mods"]}")); + if (mods != "+") + sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | **{mods,-10}** | /b/{item["beatmap_id"]}"); + else + sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}"); + } + sb.Append("```"); + await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); + } + catch (Exception ex) + { + await channel.SendMessageAsync("Something went wrong."); + _log.Warn(ex, "Osu5 command failed"); + } -// private static string ResolveMap(string mapLink) -// { -// Match s = new Regex(@"osu.ppy.sh\/s\/", RegexOptions.IgnoreCase).Match(mapLink); -// Match b = new Regex(@"osu.ppy.sh\/b\/", RegexOptions.IgnoreCase).Match(mapLink); -// Match p = new Regex(@"osu.ppy.sh\/p\/", RegexOptions.IgnoreCase).Match(mapLink); -// Match m = new Regex(@"&m=", RegexOptions.IgnoreCase).Match(mapLink); -// if (s.Success) -// { -// var mapId = mapLink.Substring(mapLink.IndexOf("/s/") + 3); -// return $"s={mapId}"; -// } -// else if (b.Success) -// { -// if (m.Success) -// return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("/b/") + 3))}"; -// else -// return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3)}"; -// } -// else if (p.Success) -// { -// if (m.Success) -// return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("?b=") + 3))}"; -// else -// return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3)}"; -// } -// else -// { -// return $"s={mapLink}"; //just a default incase an ID number was provided by itself (non-url)? -// } -// } + } + } -// private static int ResolveGameMode(string mode) -// { -// switch (mode.ToLower()) -// { -// case "std": -// case "standard": -// return 0; -// case "taiko": -// return 1; -// case "ctb": -// case "catchthebeat": -// return 2; -// case "mania": -// case "osu!mania": -// return 3; -// default: -// return 0; -// } -// } + //https://osu.ppy.sh/wiki/Accuracy + private static Double CalculateAcc(JToken play, int mode) + { + if (mode == 0) + { + var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["count300"]}") * 300; + var totalHits = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countmiss"]}"); + totalHits *= 300; + return Math.Round(hitPoints / totalHits * 100, 2); + } + else if (mode == 1) + { + var hitPoints = Double.Parse($"{play["countmiss"]}") * 0 + Double.Parse($"{play["count100"]}") * 0.5 + Double.Parse($"{play["count300"]}") * 1; + var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}"); + hitPoints *= 300; + totalHits *= 300; + return Math.Round(hitPoints / totalHits * 100, 2); + } + else if (mode == 2) + { + var fruitsCaught = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}"); + var totalFruits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countkatu"]}"); + return Math.Round(fruitsCaught / totalFruits * 100, 2); + } + else + { + var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["countkatu"]}") * 200 + (Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}")) * 300; + var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["countkatu"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}"); + totalHits *= 300; + return Math.Round(hitPoints / totalHits * 100, 2); + } + } -// //https://github.com/ppy/osu-api/wiki#mods -// private static string ResolveMods(int mods) -// { -// var modString = $"+"; + private static string ResolveMap(string mapLink) + { + Match s = new Regex(@"osu.ppy.sh\/s\/", RegexOptions.IgnoreCase).Match(mapLink); + Match b = new Regex(@"osu.ppy.sh\/b\/", RegexOptions.IgnoreCase).Match(mapLink); + Match p = new Regex(@"osu.ppy.sh\/p\/", RegexOptions.IgnoreCase).Match(mapLink); + Match m = new Regex(@"&m=", RegexOptions.IgnoreCase).Match(mapLink); + if (s.Success) + { + var mapId = mapLink.Substring(mapLink.IndexOf("/s/") + 3); + return $"s={mapId}"; + } + else if (b.Success) + { + if (m.Success) + return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("/b/") + 3))}"; + else + return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3)}"; + } + else if (p.Success) + { + if (m.Success) + return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("?b=") + 3))}"; + else + return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3)}"; + } + else + { + return $"s={mapLink}"; //just a default incase an ID number was provided by itself (non-url)? + } + } -// if (IsBitSet(mods, 0)) -// modString += "NF"; -// if (IsBitSet(mods, 1)) -// modString += "EZ"; -// if (IsBitSet(mods, 8)) -// modString += "HT"; + private static int ResolveGameMode(string mode) + { + switch (mode.ToLower()) + { + case "std": + case "standard": + return 0; + case "taiko": + return 1; + case "ctb": + case "catchthebeat": + return 2; + case "mania": + case "osu!mania": + return 3; + default: + return 0; + } + } -// if (IsBitSet(mods, 3)) -// modString += "HD"; -// if (IsBitSet(mods, 4)) -// modString += "HR"; -// if (IsBitSet(mods, 6) && !IsBitSet(mods, 9)) -// modString += "DT"; -// if (IsBitSet(mods, 9)) -// modString += "NC"; -// if (IsBitSet(mods, 10)) -// modString += "FL"; + //https://github.com/ppy/osu-api/wiki#mods + private static string ResolveMods(int mods) + { + var modString = $"+"; -// if (IsBitSet(mods, 5)) -// modString += "SD"; -// if (IsBitSet(mods, 14)) -// modString += "PF"; + if (IsBitSet(mods, 0)) + modString += "NF"; + if (IsBitSet(mods, 1)) + modString += "EZ"; + if (IsBitSet(mods, 8)) + modString += "HT"; -// if (IsBitSet(mods, 7)) -// modString += "RX"; -// if (IsBitSet(mods, 11)) -// modString += "AT"; -// if (IsBitSet(mods, 12)) -// modString += "SO"; -// return modString; -// } + if (IsBitSet(mods, 3)) + modString += "HD"; + if (IsBitSet(mods, 4)) + modString += "HR"; + if (IsBitSet(mods, 6) && !IsBitSet(mods, 9)) + modString += "DT"; + if (IsBitSet(mods, 9)) + modString += "NC"; + if (IsBitSet(mods, 10)) + modString += "FL"; -// private static bool IsBitSet(int mods, int pos) -// { -// return (mods & (1 << pos)) != 0; -// } + if (IsBitSet(mods, 5)) + modString += "SD"; + if (IsBitSet(mods, 14)) + modString += "PF"; -// } -//} + if (IsBitSet(mods, 7)) + modString += "RX"; + if (IsBitSet(mods, 11)) + modString += "AT"; + if (IsBitSet(mods, 12)) + modString += "SO"; + return modString; + } + + private static bool IsBitSet(int mods, int pos) => + (mods & (1 << pos)) != 0; + } + } +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 9b915794..529d7fe3 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -154,7 +154,7 @@ // .AddCheck(SimpleCheckers.ManageServer()) // .Do(async e => // { -// var stream = e.GetArg("username")?.Trim(); +// var stream = username?.Trim(); // if (string.IsNullOrWhiteSpace(stream)) // return; // try @@ -183,7 +183,7 @@ // .Parameter("username", ParameterType.Unparsed) // .Do(async e => // { -// var stream = e.GetArg("username")?.Trim(); +// var stream = username?.Trim(); // if (string.IsNullOrWhiteSpace(stream)) // return; // try @@ -212,7 +212,7 @@ // .Parameter("username", ParameterType.Unparsed) // .Do(async e => // { -// var stream = e.GetArg("username")?.Trim(); +// var stream = username?.Trim(); // if (string.IsNullOrWhiteSpace(stream)) // return; // try @@ -241,7 +241,7 @@ // .Parameter("username", ParameterType.Unparsed) // .Do(async e => // { -// var username = e.GetArg("username")?.ToLower().Trim(); +// var username = username?.ToLower().Trim(); // if (string.IsNullOrWhiteSpace(username)) // return; @@ -298,7 +298,7 @@ // private Func TrackStream(StreamNotificationConfig.StreamType type) => // async e => // { -// var username = e.GetArg("username")?.ToLowerInvariant(); +// var username = username?.ToLowerInvariant(); // if (string.IsNullOrWhiteSpace(username)) // return; diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index f8a0bec1..ea571a23 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -8,7 +8,6 @@ using System.Net.Http; using NadekoBot.Services; using System.Threading.Tasks; using NadekoBot.Attributes; -using NadekoBot.Extensions; using System.Text.RegularExpressions; using System.Net; using Discord.WebSocket; @@ -206,7 +205,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】 //public async Task Hearthstone(IMessage imsg, [Remainder] string name = null) //{ // var channel = imsg.Channel as ITextChannel; - // var arg = e.GetArg("name"); + // var arg = name; // if (string.IsNullOrWhiteSpace(arg)) // { // await channel.SendMessageAsync("πŸ’’ Please enter a card name to search for.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Trello/Trello.cs b/src/NadekoBot/Modules/Trello/Trello.cs index b62c9a55..820b0379 100644 --- a/src/NadekoBot/Modules/Trello/Trello.cs +++ b/src/NadekoBot/Modules/Trello/Trello.cs @@ -26,7 +26,7 @@ // TrelloConfiguration.Deserializer = serializer; // TrelloConfiguration.JsonFactory = new ManateeFactory(); // TrelloConfiguration.RestClientProvider = new Manatee.Trello.WebApi.WebApiClientProvider(); -// TrelloAuthorization.Default.AppKey = NadekoBot.Creds.TrelloAppKey; +// TrelloAuthorization.Default.AppKey = NadekoBot.Credentials.TrelloAppKey; // //TrelloAuthorization.Default.UserToken = "[your user token]"; // Discord.Channel bound = null; @@ -80,7 +80,7 @@ // try // { // bound = e.Channel; -// board = new Board(e.GetArg("board_id").Trim()); +// board = new Board(board_id.Trim()); // board.Refresh(); // await channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name); // t.Start(); @@ -121,15 +121,15 @@ // .Do(async e => // { // if (!NadekoBot.IsOwner(imsg.Author.Id)) return; -// if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null) return; +// if (bound == null || board == null || bound != e.Channel || list_name == null) return; // int num; -// var success = int.TryParse(e.GetArg("list_name"), out num); +// var success = int.TryParse(list_name, out num); // List list = null; // if (success && num <= board.Lists.Count() && num > 0) // list = board.Lists[num - 1]; // else -// list = board.Lists.FirstOrDefault(l => l.Name == e.GetArg("list_name")); +// list = board.Lists.FirstOrDefault(l => l.Name == list_name); // if (list != null) diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index be814fea..f6c67748 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -94,7 +94,7 @@ // .Parameter("message", ParameterType.Unparsed) // .Do(async e => // { -// var meorchStr = e.GetArg("meorchannel").ToUpperInvariant(); +// var meorchStr = meorchannel.ToUpperInvariant(); // Channel ch; // bool isPrivate = false; // if (meorchStr == "ME") @@ -117,7 +117,7 @@ // return; // } -// var timeStr = e.GetArg("time"); +// var timeStr = time; // var m = regex.Match(timeStr); @@ -167,7 +167,7 @@ // ChannelId = (long)ch.Id, // IsPrivate = isPrivate, // When = time, -// Message = e.GetArg("message"), +// Message = message, // UserId = (long)imsg.Author.Id, // ServerId = (long)e.Server.Id // }; @@ -175,7 +175,7 @@ // reminders.Add(StartNewReminder(rem)); -// 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); +// await channel.SendMessageAsync($"⏰ I will remind \"{ch.Name}\" to \"{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. " + @@ -185,7 +185,7 @@ // .AddCheck(SimpleCheckers.OwnerOnly()) // .Do(async e => // { -// var arg = e.GetArg("msg")?.Trim(); +// var arg = msg?.Trim(); // if (string.IsNullOrWhiteSpace(arg)) // return; diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 4b0f9c3c..c20aa1fb 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -23,7 +23,7 @@ namespace NadekoBot public static Localization Localizer { get; private set; } public static BotCredentials Credentials { get; private set; } - private static YoutubeService Youtube { get; set; } + private static GoogleApiService Youtube { get; set; } public static StatsService Stats { get; private set; } public async Task RunAsync(string[] args) @@ -43,7 +43,7 @@ namespace NadekoBot Commands = new CommandService(); Config = new BotConfiguration(); Localizer = new Localization(); - Youtube = new YoutubeService(); + Youtube = new GoogleApiService(); Stats = new StatsService(Client); _log = LogManager.GetCurrentClassLogger(); diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 4128fe38..d9265ce3 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; @@ -14,6 +15,13 @@ namespace NadekoBot.Extensions { public static class Extensions { + public static void AddFakeHeaders(this HttpClient http) + { + http.DefaultRequestHeaders.Clear(); + http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1"); + http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); + } + public static async Task SendMessageAsync(this IGuildUser user, string message, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(message, isTTS).ConfigureAwait(false); diff --git a/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs index d7c6008d..af36cd94 100644 --- a/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/_Modules/CustomReactions/CustomReactions.cs @@ -32,7 +32,7 @@ namespace NadekoBot.Modules.CustomReactions } }, {new Regex("%mention%"), (e,m) => NadekoBot.BotMention }, {new Regex("%user%"), (e,m) => imsg.Author.Mention }, - {new Regex("%target%"), (e,m) => e.GetArg("args")?.Trim() ?? "" }, + {new Regex("%target%"), (e,m) => args?.Trim() ?? "" }, }; } diff --git a/src/NadekoBot/_Modules/Music/Classes/SoundCloud.cs b/src/NadekoBot/_Modules/Music/Classes/SoundCloud.cs index ed829adb..9cab3fcf 100644 --- a/src/NadekoBot/_Modules/Music/Classes/SoundCloud.cs +++ b/src/NadekoBot/_Modules/Music/Classes/SoundCloud.cs @@ -18,10 +18,10 @@ namespace NadekoBot.Modules.Music.Classes { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.SoundCloudClientID)) - throw new ArgumentNullException(nameof(NadekoBot.Creds.SoundCloudClientID)); + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.SoundCloudClientID)) + throw new ArgumentNullException(nameof(NadekoBot.Credentials.SoundCloudClientID)); - var response = await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.Creds.SoundCloudClientID}").ConfigureAwait(false); + var response = await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.Credentials.SoundCloudClientID}").ConfigureAwait(false); var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject(response); if (responseObj?.Kind != "track") @@ -37,10 +37,10 @@ namespace NadekoBot.Modules.Music.Classes { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); - if (string.IsNullOrWhiteSpace(NadekoBot.Creds.SoundCloudClientID)) - throw new ArgumentNullException(nameof(NadekoBot.Creds.SoundCloudClientID)); + if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.SoundCloudClientID)) + throw new ArgumentNullException(nameof(NadekoBot.Credentials.SoundCloudClientID)); - var response = await http.GetStringAsync($"http://api.soundcloud.com/tracks?q={Uri.EscapeDataString(query)}&client_id={NadekoBot.Creds.SoundCloudClientID}").ConfigureAwait(false); + var response = await http.GetStringAsync($"http://api.soundcloud.com/tracks?q={Uri.EscapeDataString(query)}&client_id={NadekoBot.Credentials.SoundCloudClientID}").ConfigureAwait(false); var responseObj = JsonConvert.DeserializeObject(response).Where(s => s.Streamable).FirstOrDefault(); if (responseObj?.Kind != "track") @@ -62,7 +62,7 @@ namespace NadekoBot.Modules.Music.Classes [JsonProperty("permalink_url")] public string TrackLink { get; set; } = ""; [JsonIgnore] - public string StreamLink => $"https://api.soundcloud.com/tracks/{Id}/stream?client_id={NadekoBot.Creds.SoundCloudClientID}"; + public string StreamLink => $"https://api.soundcloud.com/tracks/{Id}/stream?client_id={NadekoBot.Credentials.SoundCloudClientID}"; } public class SoundCloudUser { diff --git a/src/NadekoBot/_Modules/Music/MusicModule.cs b/src/NadekoBot/_Modules/Music/MusicModule.cs index ea9d136e..49308c94 100644 --- a/src/NadekoBot/_Modules/Music/MusicModule.cs +++ b/src/NadekoBot/_Modules/Music/MusicModule.cs @@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Music .Parameter("query", ParameterType.Unparsed) .Do(async e => { - await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, e.GetArg("query")).ConfigureAwait(false); + await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, query).ConfigureAwait(false); if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -120,7 +120,7 @@ namespace NadekoBot.Modules.Music .Parameter("query", ParameterType.Unparsed) .Do(async e => { - await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, e.GetArg("query"), musicType: MusicType.Soundcloud).ConfigureAwait(false); + await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -142,7 +142,7 @@ namespace NadekoBot.Modules.Music } int page; - if (!int.TryParse(e.GetArg("page"), out page) || page <= 0) + if (!int.TryParse(page, out page) || page <= 0) { page = 1; } @@ -192,7 +192,7 @@ namespace NadekoBot.Modules.Music return; if (imsg.Author.VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; - var arg = e.GetArg("val"); + var arg = val; int volume; if (!int.TryParse(arg, out volume)) { @@ -210,7 +210,7 @@ namespace NadekoBot.Modules.Music .Parameter("val", ParameterType.Required) .Do(async e => { - var arg = e.GetArg("val"); + var arg = val; float volume; if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100) { @@ -285,7 +285,7 @@ namespace NadekoBot.Modules.Music .Parameter("playlist", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("playlist"); + var arg = playlist; if (string.IsNullOrWhiteSpace(arg)) return; if (imsg.Author.VoiceChannel?.Server != e.Server) @@ -328,12 +328,12 @@ namespace NadekoBot.Modules.Music .Parameter("pl", ParameterType.Unparsed) .Do(async e => { - var pl = e.GetArg("pl")?.Trim(); + var pl = pl?.Trim(); if (string.IsNullOrWhiteSpace(pl)) return; - var scvids = JObject.Parse(await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={pl}&client_id={NadekoBot.Creds.SoundCloudClientID}").ConfigureAwait(false))["tracks"].ToObject(); + var scvids = JObject.Parse(await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={pl}&client_id={NadekoBot.Credentials.SoundCloudClientID}").ConfigureAwait(false))["tracks"].ToObject(); await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false); MusicPlayer mp; @@ -364,7 +364,7 @@ namespace NadekoBot.Modules.Music .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { - var arg = e.GetArg("directory"); + var arg = directory; if (string.IsNullOrWhiteSpace(arg)) return; try @@ -398,7 +398,7 @@ namespace NadekoBot.Modules.Music await channel.SendMessageAsync("πŸ’’ You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); return; } - await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false); + await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); if (e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -413,10 +413,10 @@ namespace NadekoBot.Modules.Music .AddCheck(SimpleCheckers.OwnerOnly()) .Do(async e => { - var arg = e.GetArg("path"); + var arg = path; if (string.IsNullOrWhiteSpace(arg)) return; - await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, e.GetArg("path"), musicType: MusicType.Local).ConfigureAwait(false); + await QueueSong(imsg.Author, e.Channel, imsg.Author.VoiceChannel, path, musicType: MusicType.Local).ConfigureAwait(false); }); cgb.CreateCommand(Prefix + "move") @@ -437,7 +437,7 @@ namespace NadekoBot.Modules.Music .Parameter("num", ParameterType.Required) .Do(async e => { - var arg = e.GetArg("num"); + var arg = num; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) { @@ -475,7 +475,7 @@ namespace NadekoBot.Modules.Music { return; } - var fromto = e.GetArg("fromto").Trim(); + var fromto = fromto.Trim(); var fromtoArr = fromto.Split('>'); int n1; @@ -512,7 +512,7 @@ namespace NadekoBot.Modules.Music return; } - var sizeStr = e.GetArg("size")?.Trim(); + var sizeStr = size?.Trim(); uint size = 0; if (string.IsNullOrWhiteSpace(sizeStr) || !uint.TryParse(sizeStr, out size)) { @@ -576,7 +576,7 @@ namespace NadekoBot.Modules.Music .Parameter("name", ParameterType.Unparsed) .Do(async e => { - var name = e.GetArg("name")?.Trim(); + var name = name?.Trim(); if (string.IsNullOrWhiteSpace(name) || name.Length > 20 || @@ -636,7 +636,7 @@ namespace NadekoBot.Modules.Music await textCh.SendMessageAsync("πŸ’’ You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); return; } - var name = e.GetArg("name")?.Trim().ToLowerInvariant(); + var name = name?.Trim().ToLowerInvariant(); if (string.IsNullOrWhiteSpace(name)) return; @@ -690,7 +690,7 @@ namespace NadekoBot.Modules.Music .Do(e => { int num = 0; - int.TryParse(e.GetArg("num"), out num); + int.TryParse(num, out num); if (num < 0) return; var result = DbHandler.Instance.GetPlaylistData(num); @@ -706,7 +706,7 @@ namespace NadekoBot.Modules.Music .Parameter("pl", ParameterType.Required) .Do(async e => { - var pl = e.GetArg("pl").Trim().Split('-')[1]; + var pl = pl.Trim().Split('-')[1]; if (string.IsNullOrWhiteSpace(pl)) return; var plnum = int.Parse(pl); @@ -722,7 +722,7 @@ namespace NadekoBot.Modules.Music .Parameter("time") .Do(async e => { - var skipToStr = e.GetArg("time")?.Trim(); + var skipToStr = time?.Trim(); MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; @@ -764,7 +764,7 @@ namespace NadekoBot.Modules.Music if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; int index; - string arg = e.GetArg("index")?.Trim(); + string arg = index?.Trim(); if (!string.IsNullOrEmpty(arg) && int.TryParse(arg, out index)) { diff --git a/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs b/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs index 8109ca2b..7b9b1dc1 100644 --- a/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs +++ b/src/NadekoBot/_Modules/Permissions/Commands/FilterInvitesCommand.cs @@ -62,8 +62,8 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var chanStr = e.GetArg("channel"); + var state = PermissionHelper.ValidateBool(bool); + var chanStr = channel; if (chanStr?.ToLowerInvariant().Trim() != "all") { @@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var state = PermissionHelper.ValidateBool(bool); await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false); await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.") .ConfigureAwait(false); diff --git a/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs b/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs index deb3920b..781faa93 100644 --- a/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs +++ b/src/NadekoBot/_Modules/Permissions/Commands/FilterWordsCommand.cs @@ -60,8 +60,8 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var chanStr = e.GetArg("channel")?.ToLowerInvariant().Trim(); + var state = PermissionHelper.ValidateBool(bool); + var chanStr = channel?.ToLowerInvariant().Trim(); if (chanStr != "all") { @@ -95,7 +95,7 @@ namespace NadekoBot.Modules.Permissions { try { - var word = e.GetArg("word"); + var word = word; if (string.IsNullOrWhiteSpace(word)) return; await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); @@ -117,7 +117,7 @@ namespace NadekoBot.Modules.Permissions { try { - var word = e.GetArg("word"); + var word = word; if (string.IsNullOrWhiteSpace(word)) return; await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false); @@ -158,7 +158,7 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var state = PermissionHelper.ValidateBool(bool); await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false); await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.") .ConfigureAwait(false); diff --git a/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs b/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs index 37374687..b0cdbe87 100644 --- a/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs +++ b/src/NadekoBot/_Modules/Permissions/PermissionsModule.cs @@ -37,13 +37,13 @@ namespace NadekoBot.Modules.Permissions .Parameter("role", ParameterType.Unparsed) .Do(async e => { - if (string.IsNullOrWhiteSpace(e.GetArg("role"))) + if (string.IsNullOrWhiteSpace(role)) { await channel.SendMessageAsync($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false); return; } - var arg = e.GetArg("role"); + var arg = role; Discord.Role role = null; try { @@ -65,7 +65,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("from_to")?.Trim(); + var arg = from_to?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) return; var args = arg.Split('~').Select(a => a.Trim()).ToArray(); @@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("from_to")?.Trim(); + var arg = from_to?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) return; var args = arg.Split('~').Select(a => a.Trim()).ToArray(); @@ -121,7 +121,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("from_to", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("from_to")?.Trim(); + var arg = from_to?.Trim(); if (string.IsNullOrWhiteSpace(arg) || !arg.Contains('~')) return; var args = arg.Split('~').Select(a => a.Trim()).ToArray(); @@ -150,7 +150,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("arg", ParameterType.Required) .Do(async e => { - var arg = e.GetArg("arg"); + var arg = arg; var val = PermissionHelper.ValidateBool(arg); await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false); await channel.SendMessageAsync($"Verbosity set to {val}.").ConfigureAwait(false); @@ -173,7 +173,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("role", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("role"); + var arg = role; var role = e.Server.EveryoneRole; if (!string.IsNullOrWhiteSpace(arg)) try @@ -199,7 +199,7 @@ namespace NadekoBot.Modules.Permissions .Parameter("channel", ParameterType.Unparsed) .Do(async e => { - var arg = e.GetArg("channel"); + var arg = channel; var channel = e.Channel; if (!string.IsNullOrWhiteSpace(arg)) try @@ -225,10 +225,10 @@ namespace NadekoBot.Modules.Permissions .Do(async e => { var user = imsg.Author; - if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) + if (!string.IsNullOrWhiteSpace(user)) try { - user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); + user = PermissionHelper.ValidateUser(e.Server, user); } catch (Exception ex) { @@ -251,8 +251,8 @@ namespace NadekoBot.Modules.Permissions { try { - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(module); + var state = PermissionHelper.ValidateBool(bool); await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); @@ -275,8 +275,8 @@ namespace NadekoBot.Modules.Permissions { try { - var command = PermissionHelper.ValidateCommand(e.GetArg("command")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(command); + var state = PermissionHelper.ValidateBool(bool); await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false); @@ -300,10 +300,10 @@ namespace NadekoBot.Modules.Permissions { try { - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(module); + var state = PermissionHelper.ValidateBool(bool); - if (e.GetArg("role")?.ToLower() == "all") + if (role?.ToLower() == "all") { foreach (var role in e.Server.Roles) { @@ -313,7 +313,7 @@ namespace NadekoBot.Modules.Permissions } else { - var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var role = PermissionHelper.ValidateRole(e.Server, role); await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); @@ -338,10 +338,10 @@ namespace NadekoBot.Modules.Permissions { try { - var command = PermissionHelper.ValidateCommand(e.GetArg("command")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(command); + var state = PermissionHelper.ValidateBool(bool); - if (e.GetArg("role")?.ToLower() == "all") + if (role?.ToLower() == "all") { foreach (var role in e.Server.Roles) { @@ -351,7 +351,7 @@ namespace NadekoBot.Modules.Permissions } else { - var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var role = PermissionHelper.ValidateRole(e.Server, role); await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false); @@ -376,9 +376,9 @@ namespace NadekoBot.Modules.Permissions { try { - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var channelArg = e.GetArg("channel"); + var module = PermissionHelper.ValidateModule(module); + var state = PermissionHelper.ValidateBool(bool); + var channelArg = channel; if (channelArg?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) @@ -419,10 +419,10 @@ namespace NadekoBot.Modules.Permissions { try { - var command = PermissionHelper.ValidateCommand(e.GetArg("command")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(command); + var state = PermissionHelper.ValidateBool(bool); - if (e.GetArg("channel")?.ToLower() == "all") + if (channel?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { @@ -432,7 +432,7 @@ namespace NadekoBot.Modules.Permissions } else { - var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var channel = PermissionHelper.ValidateChannel(e.Server, channel); await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false); @@ -457,9 +457,9 @@ namespace NadekoBot.Modules.Permissions { try { - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); + var module = PermissionHelper.ValidateModule(module); + var state = PermissionHelper.ValidateBool(bool); + var user = PermissionHelper.ValidateUser(e.Server, user); await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false); await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); @@ -483,9 +483,9 @@ namespace NadekoBot.Modules.Permissions { try { - var command = PermissionHelper.ValidateCommand(e.GetArg("command")); - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); + var command = PermissionHelper.ValidateCommand(command); + var state = PermissionHelper.ValidateBool(bool); + var user = PermissionHelper.ValidateUser(e.Server, user); await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false); await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false); @@ -507,7 +507,7 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var state = PermissionHelper.ValidateBool(bool); foreach (var module in NadekoBot.Client.GetService().Modules) { @@ -533,8 +533,8 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(bool); + var module = PermissionHelper.ValidateModule(module); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { @@ -560,8 +560,8 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var chArg = e.GetArg("channel"); + var state = PermissionHelper.ValidateBool(bool); + var chArg = channel; var channel = string.IsNullOrWhiteSpace(chArg) ? e.Channel : PermissionHelper.ValidateChannel(e.Server, chArg); foreach (var module in NadekoBot.Client.GetService().Modules) { @@ -589,9 +589,9 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var state = PermissionHelper.ValidateBool(bool); + var module = PermissionHelper.ValidateModule(module); + var channel = PermissionHelper.ValidateChannel(e.Server, channel); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false); @@ -616,8 +616,8 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var state = PermissionHelper.ValidateBool(bool); + var role = PermissionHelper.ValidateRole(e.Server, role); foreach (var module in NadekoBot.Client.GetService().Modules) { await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false); @@ -644,9 +644,9 @@ namespace NadekoBot.Modules.Permissions { try { - var state = PermissionHelper.ValidateBool(e.GetArg("bool")); - var module = PermissionHelper.ValidateModule(e.GetArg("module")); - if (e.GetArg("role")?.ToLower() == "all") + var state = PermissionHelper.ValidateBool(bool); + var module = PermissionHelper.ValidateModule(module); + if (role?.ToLower() == "all") { foreach (var role in e.Server.Roles) { @@ -659,7 +659,7 @@ namespace NadekoBot.Modules.Permissions } else { - var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var role = PermissionHelper.ValidateRole(e.Server, role); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { @@ -755,7 +755,7 @@ namespace NadekoBot.Modules.Permissions { await Task.Run(async () => { - var arg = e.GetArg("server")?.Trim(); + var arg = server?.Trim(); if (string.IsNullOrWhiteSpace(arg)) return; var server = NadekoBot.Client.Servers.FirstOrDefault(s => s.Id.ToString() == arg) ?? @@ -788,8 +788,8 @@ namespace NadekoBot.Modules.Permissions { try { - var command = PermissionHelper.ValidateCommand(e.GetArg("command")); - var secsStr = e.GetArg("secs").Trim(); + var command = PermissionHelper.ValidateCommand(command); + var secsStr = secs.Trim(); int secs; if (!int.TryParse(secsStr, out secs) || secs < 0 || secs > 3600) throw new ArgumentOutOfRangeException("secs", "Invalid second parameter. (Must be a number between 0 and 3600)");