diff --git a/NadekoBot/Classes/Music/Song.cs b/NadekoBot/Classes/Music/Song.cs index e4600322..4bf47d44 100644 --- a/NadekoBot/Classes/Music/Song.cs +++ b/NadekoBot/Classes/Music/Song.cs @@ -149,7 +149,7 @@ namespace NadekoBot.Classes.Music { byte[] buffer = new byte[blockSize]; int attempt = 0; while (!cancelToken.IsCancellationRequested) { - int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize); + int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken); if (read == 0) if (attempt++ == 20) break; @@ -162,6 +162,9 @@ namespace NadekoBot.Classes.Music { prebufferingComplete = true; } } + catch { + Console.WriteLine("Buffering errored"); + } finally { if (p != null) { p.CancelOutputRead(); @@ -171,7 +174,7 @@ namespace NadekoBot.Classes.Music { p.Dispose(); } } - Console.WriteLine($"Buffering done. [{songBuffer.ContentLength}]"); + Console.WriteLine($"Buffering done." + $" [{songBuffer.ContentLength}]"); }); internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) { @@ -180,8 +183,9 @@ namespace NadekoBot.Classes.Music { int waitPerAttempt = 500; int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9; while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) { - await Task.Delay(waitPerAttempt); + await Task.Delay(waitPerAttempt, cancelToken); } + cancelToken.ThrowIfCancellationRequested(); Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}"); int blockSize = 3840; byte[] buffer = new byte[blockSize]; @@ -190,9 +194,9 @@ namespace NadekoBot.Classes.Music { //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------"); int read = songBuffer.Read(buffer, blockSize); if (read == 0) - if (attempt++ == 10) { + if (attempt++ == 20) { voiceClient.Wait(); - Console.WriteLine("Playing done."); + Console.WriteLine("Nothing to read."); return; } else @@ -201,10 +205,11 @@ namespace NadekoBot.Classes.Music { attempt = 0; while (this.MusicPlayer.Paused) - await Task.Delay(200); + await Task.Delay(200, cancelToken); buffer = adjustVolume(buffer, MusicPlayer.Volume); voiceClient.Send(buffer, 0, read); } + cancelToken.ThrowIfCancellationRequested(); //try { // voiceClient.Clear(); // Console.WriteLine("CLEARED"); diff --git a/NadekoBot/Classes/Music/SoundCloud.cs b/NadekoBot/Classes/Music/SoundCloud.cs index 207e45e6..f3231389 100644 --- a/NadekoBot/Classes/Music/SoundCloud.cs +++ b/NadekoBot/Classes/Music/SoundCloud.cs @@ -16,10 +16,10 @@ namespace NadekoBot.Classes.Music { public async Task GetVideoAsync(string url) { 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.Creds.SoundCloudClientID)) + throw new ArgumentNullException(nameof(NadekoBot.Creds.SoundCloudClientID)); - var response = await SearchHelper.GetResponseAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.creds.SoundCloudClientID}"); + var response = await SearchHelper.GetResponseAsync($"http://api.soundcloud.com/resolve?url={url}&client_id={NadekoBot.Creds.SoundCloudClientID}"); var responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject(response); if (responseObj?.Kind != "track") @@ -39,7 +39,7 @@ namespace NadekoBot.Classes.Music { public string Title = ""; public string FullName => User.Name + " - " + Title; public bool Streamable = false; - 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.Creds.SoundCloudClientID}"; } public class SoundCloudUser { [Newtonsoft.Json.JsonProperty("username")] diff --git a/NadekoBot/Classes/NadekoStats.cs b/NadekoBot/Classes/NadekoStats.cs index 52b7802b..40376b2f 100644 --- a/NadekoBot/Classes/NadekoStats.cs +++ b/NadekoBot/Classes/NadekoStats.cs @@ -31,8 +31,8 @@ namespace NadekoBot { static NadekoStats() { } private NadekoStats() { - _service = NadekoBot.client.GetService(); - _client = NadekoBot.client; + _service = NadekoBot.Client.GetService(); + _client = NadekoBot.Client; _statsSW = new Stopwatch(); _statsSW.Start(); @@ -130,10 +130,10 @@ namespace NadekoBot { while (true) { await Task.Delay(new TimeSpan(0, 30, 0)); try { - var onlineUsers = await Task.Run(() => NadekoBot.client.Servers.Sum(x => x.Users.Count())); - var realOnlineUsers = await Task.Run(() => NadekoBot.client.Servers + var onlineUsers = await Task.Run(() => NadekoBot.Client.Servers.Sum(x => x.Users.Count())); + var realOnlineUsers = await Task.Run(() => NadekoBot.Client.Servers .Sum(x => x.Users.Where(u => u.Status == UserStatus.Online).Count())); - var connectedServers = NadekoBot.client.Servers.Count(); + var connectedServers = NadekoBot.Client.Servers.Count(); Classes.DBHandler.Instance.InsertData(new Classes._DataModels.Stats { OnlineUsers = onlineUsers, diff --git a/NadekoBot/Classes/Permissions/PermissionChecker.cs b/NadekoBot/Classes/Permissions/PermissionChecker.cs index 56b21985..0a1997c0 100644 --- a/NadekoBot/Classes/Permissions/PermissionChecker.cs +++ b/NadekoBot/Classes/Permissions/PermissionChecker.cs @@ -1,8 +1,5 @@ using Discord.Commands.Permissions; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; using Discord; using Discord.Commands; diff --git a/NadekoBot/Classes/Permissions/PermissionHelper.cs b/NadekoBot/Classes/Permissions/PermissionHelper.cs index 9dca4eac..20fe0943 100644 --- a/NadekoBot/Classes/Permissions/PermissionHelper.cs +++ b/NadekoBot/Classes/Permissions/PermissionHelper.cs @@ -40,7 +40,7 @@ namespace NadekoBot.Classes { if (string.IsNullOrWhiteSpace(mod)) throw new ArgumentNullException(nameof(mod)); - foreach (var m in NadekoBot.client.GetService().Modules) { + foreach (var m in NadekoBot.Client.GetService().Modules) { if (m.Name.ToLower().Equals(mod.ToLower())) return m.Name; } @@ -51,7 +51,7 @@ namespace NadekoBot.Classes { if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentNullException(nameof(commandText)); - foreach (var com in NadekoBot.client.GetService().AllCommands) { + foreach (var com in NadekoBot.Client.GetService().AllCommands) { if (com.Text.ToLower().Equals(commandText.ToLower())) return com.Text; } diff --git a/NadekoBot/Classes/Permissions/SimpleCheckers.cs b/NadekoBot/Classes/Permissions/SimpleCheckers.cs index 90df1aad..37c85e24 100644 --- a/NadekoBot/Classes/Permissions/SimpleCheckers.cs +++ b/NadekoBot/Classes/Permissions/SimpleCheckers.cs @@ -9,6 +9,6 @@ using System.Threading.Tasks; namespace NadekoBot.Classes.Permissions { static class SimpleCheckers { public static Func OwnerOnly() => - (com, user, ch) => user.Id == NadekoBot.creds.OwnerID; + (com, user, ch) => user.Id == NadekoBot.Creds.OwnerID; } } diff --git a/NadekoBot/Classes/SearchHelper.cs b/NadekoBot/Classes/SearchHelper.cs index 743297fe..156efc82 100644 --- a/NadekoBot/Classes/SearchHelper.cs +++ b/NadekoBot/Classes/SearchHelper.cs @@ -9,23 +9,19 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; namespace NadekoBot.Classes { - static class SearchHelper { + public static class SearchHelper { public static async Task GetResponseStream(string v) { var wr = (HttpWebRequest)WebRequest.Create(v); - try { - return (await (wr).GetResponseAsync()).GetResponseStream(); - } - catch (Exception ex) { - Console.WriteLine("error in getresponse stream " + ex); - return null; - } + return (await (wr).GetResponseAsync()).GetResponseStream(); } public static async Task GetResponseAsync(string v, WebHeaderCollection headers = null) { var wr = (HttpWebRequest)WebRequest.Create(v); if (headers != null) wr.Headers = headers; - using (var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream())) { + var stream = (await wr.GetResponseAsync()).GetResponseStream(); + if (stream == null) return ""; + using (var sr = new StreamReader(stream)) { return await sr.ReadToEndAsync(); } } @@ -46,8 +42,7 @@ namespace NadekoBot.Classes { rq = new RestSharp.RestRequest("anime/" + smallObj["id"]); rq.AddParameter("access_token", token); return await Task.Run(() => JsonConvert.DeserializeObject(cl.Execute(rq).Content)); - } - catch { + } catch { return null; } } @@ -66,8 +61,7 @@ namespace NadekoBot.Classes { rq = new RestSharp.RestRequest("manga/" + smallObj["id"]); rq.AddParameter("access_token", token); return await Task.Run(() => JsonConvert.DeserializeObject(cl.Execute(rq).Content)); - } - catch (Exception ex) { + } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } @@ -83,8 +77,7 @@ namespace NadekoBot.Classes { var exec = cl.Execute(rq); token = JObject.Parse(exec.Content)["access_token"].ToString(); - } - catch (Exception ex) { + } catch (Exception ex) { Console.WriteLine($"Failed refreshing anilist token:\n {ex}"); } } @@ -98,7 +91,7 @@ namespace NadekoBot.Classes { } public static async Task FindYoutubeUrlByKeywords(string v) { - if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { + if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); return @"https://www.youtube.com/watch?v=dQw4w9WgXcQ"; } @@ -117,15 +110,14 @@ namespace NadekoBot.Classes { dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString(); } - } - catch (Exception ex) { + } catch (Exception ex) { Console.WriteLine($"Error in findyoutubeurl: {ex.Message}"); return string.Empty; } } public static async Task GetPlaylistIdByKeyword(string v) { - if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { + if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); return string.Empty; } @@ -136,8 +128,7 @@ namespace NadekoBot.Classes { dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); return obj.items[0].id.playlistId.ToString(); - } - catch (Exception ex) { + } catch (Exception ex) { Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); return string.Empty; } @@ -145,15 +136,17 @@ namespace NadekoBot.Classes { public static async Task> GetVideoIDs(string v) { List toReturn = new List(); - if (NadekoBot.GoogleAPIKey == "" || NadekoBot.GoogleAPIKey == null) { + if (string.IsNullOrWhiteSpace(NadekoBot.GoogleAPIKey)) { Console.WriteLine("ERROR: No google api key found. Playing `Never gonna give you up`."); return toReturn; } try { - WebRequest wr = WebRequest.Create($"https://www.googleapis.com/youtube/v3/playlistItems?part=contentDetails&maxResults={30}&playlistId={v}&key={ NadekoBot.creds.GoogleAPIKey }"); - - var sr = new StreamReader((await wr.GetResponseAsync()).GetResponseStream()); + var response = await wr.GetResponseAsync(); + if (response == null) return toReturn; + var responseStream = response.GetResponseStream(); + if (responseStream == null) return toReturn; + var sr = new StreamReader(responseStream); dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); @@ -161,8 +154,7 @@ namespace NadekoBot.Classes { toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId); } return toReturn; - } - catch (Exception ex) { + } catch (Exception ex) { Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); return new List(); } @@ -180,8 +172,7 @@ namespace NadekoBot.Classes { var matches = Regex.Matches(webpage, "data-large-file-url=\"(?.*?)\""); return await $"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl(); - } - catch { + } catch { return null; } } @@ -197,8 +188,7 @@ namespace NadekoBot.Classes { //now extract the image from post page var match = Regex.Match(webpage, "\"(?http://simg4.gelbooru.com//images.*?)\""); return match.Groups["url"].Value; - } - catch { + } catch { return null; } } @@ -210,32 +200,32 @@ namespace NadekoBot.Classes { var webpage = await GetResponseAsync(url); // first extract the post id and go to that posts page var matches = Regex.Matches(webpage, "\"file_url\":\"(?.*?)\""); return matches[rng.Next(0, matches.Count)].Groups["url"].Value; - } - catch { + } catch { return null; } } public static async Task ShortenUrl(string url) { - if (NadekoBot.creds.GoogleAPIKey == null || NadekoBot.creds.GoogleAPIKey == "") return url; + if (string.IsNullOrWhiteSpace(NadekoBot.creds.GoogleAPIKey)) return url; try { var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + NadekoBot.creds.GoogleAPIKey); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) { - string json = "{\"longUrl\":\"" + url + "\"}"; + var json = "{\"longUrl\":\"" + url + "\"}"; streamWriter.Write(json); } var httpResponse = (await httpWebRequest.GetResponseAsync()) as HttpWebResponse; - using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { - string responseText = await streamReader.ReadToEndAsync(); - string MATCH_PATTERN = @"""id"": ?""(?.+)"""; - return Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value; + if (httpResponse == null) return "HTTP_RESPONSE_ERROR"; + var responseStream = httpResponse.GetResponseStream(); + if (responseStream == null) return "RESPONSE_STREAM ERROR"; + using (var streamReader = new StreamReader(responseStream)) { + var responseText = await streamReader.ReadToEndAsync(); + return Regex.Match(responseText, @"""id"": ?""(?.+)""").Groups["id"].Value; } - } - catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; } + } catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; } } } } diff --git a/NadekoBot/Classes/Trivia/TriviaGame.cs b/NadekoBot/Classes/Trivia/TriviaGame.cs index 81c088a1..8fe38bb7 100644 --- a/NadekoBot/Classes/Trivia/TriviaGame.cs +++ b/NadekoBot/Classes/Trivia/TriviaGame.cs @@ -52,7 +52,7 @@ namespace NadekoBot.Classes.Trivia { await _channel.SendMessage($":question: **{CurrentQuestion.Question}**"); //receive messages - NadekoBot.client.MessageReceived += PotentialGuess; + NadekoBot.Client.MessageReceived += PotentialGuess; //allow people to guess GameActive = true; @@ -71,7 +71,7 @@ namespace NadekoBot.Classes.Trivia { GameActive = false; if (!triviaCancelSource.IsCancellationRequested) await _channel.Send($":clock2: :question: **Time's up!** The correct answer was **{CurrentQuestion.Answer}**"); - NadekoBot.client.MessageReceived -= PotentialGuess; + NadekoBot.Client.MessageReceived -= PotentialGuess; // load next question if game is still running await Task.Delay(2000); } diff --git a/NadekoBot/Classes/_JSONModels.cs b/NadekoBot/Classes/_JSONModels.cs index d6caa123..9b32d1cd 100644 --- a/NadekoBot/Classes/_JSONModels.cs +++ b/NadekoBot/Classes/_JSONModels.cs @@ -1,4 +1,5 @@ -namespace NadekoBot +// ReSharper disable InconsistentNaming +namespace NadekoBot.Classes { public class Credentials { @@ -31,7 +32,8 @@ "\n`Synopsis:` " + description.Substring(0, description.Length > 500 ? 500 : description.Length) + "..." + "\n`img:` " + image_url_lge; } - class MangaResult + + public class MangaResult { public int id; public string publishing_status; diff --git a/NadekoBot/Commands/DiscordCommand.cs b/NadekoBot/Commands/DiscordCommand.cs index fccda6c5..ecc0c37e 100644 --- a/NadekoBot/Commands/DiscordCommand.cs +++ b/NadekoBot/Commands/DiscordCommand.cs @@ -22,7 +22,7 @@ namespace NadekoBot /// CommandBuilder which will be modified protected DiscordCommand() { - client = NadekoBot.client; + client = NadekoBot.Client; } /// /// Function containing the behaviour of the command. diff --git a/NadekoBot/Commands/HelpCommand.cs b/NadekoBot/Commands/HelpCommand.cs index 59936082..d968da6b 100644 --- a/NadekoBot/Commands/HelpCommand.cs +++ b/NadekoBot/Commands/HelpCommand.cs @@ -42,7 +42,7 @@ namespace NadekoBot { await Task.Run(async () => { var comToFind = e.GetArg("command"); - var com = NadekoBot.client.GetService().AllCommands + var com = NadekoBot.Client.GetService().AllCommands .Where(c => c.Text.ToLower().Equals(comToFind)) .FirstOrDefault(); if (com != null) diff --git a/NadekoBot/Commands/LoLCommands.cs b/NadekoBot/Commands/LoLCommands.cs index 59261a2a..3102836a 100644 --- a/NadekoBot/Commands/LoLCommands.cs +++ b/NadekoBot/Commands/LoLCommands.cs @@ -78,7 +78,7 @@ namespace NadekoBot.Commands { await e.Channel.SendFile("champ.png", champ.ImageStream); return; } - var allData = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.creds.LOLAPIKey}")); + var allData = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")); JToken data = null; if (role != null) { for (int i = 0; i < allData.Count; i++) { @@ -114,7 +114,7 @@ namespace NadekoBot.Commands { if (roles[i] == role) roles[i] = ">" + roles[i] + "<"; } - var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.creds.LOLAPIKey}")) + var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")) .Where(jt => jt["role"].ToString() == role) .FirstOrDefault()?["general"]; if (general == null) { @@ -253,7 +253,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% var data = JObject.Parse( await Classes .SearchHelper - .GetResponseAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray; + .GetResponseAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.Creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray; StringBuilder sb = new StringBuilder(); sb.AppendLine($"**Showing {showCount} top banned champions.**"); diff --git a/NadekoBot/Commands/LogCommand.cs b/NadekoBot/Commands/LogCommand.cs index 1e4fa74f..49e019d9 100644 --- a/NadekoBot/Commands/LogCommand.cs +++ b/NadekoBot/Commands/LogCommand.cs @@ -9,10 +9,10 @@ namespace NadekoBot.Commands { class LogCommand : DiscordCommand { public LogCommand() : base() { - NadekoBot.client.MessageReceived += MsgRecivd; - NadekoBot.client.MessageDeleted += MsgDltd; - NadekoBot.client.MessageUpdated += MsgUpdtd; - NadekoBot.client.UserUpdated += UsrUpdtd; + NadekoBot.Client.MessageReceived += MsgRecivd; + NadekoBot.Client.MessageDeleted += MsgDltd; + NadekoBot.Client.MessageUpdated += MsgUpdtd; + NadekoBot.Client.UserUpdated += UsrUpdtd; } ConcurrentDictionary logs = new ConcurrentDictionary(); @@ -36,7 +36,7 @@ namespace NadekoBot.Commands { private async void MsgRecivd(object sender, MessageEventArgs e) { try { - if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) + if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id) return; Channel ch; if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) @@ -47,7 +47,7 @@ namespace NadekoBot.Commands { } private async void MsgDltd(object sender, MessageEventArgs e) { try { - if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) + if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id) return; Channel ch; if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) @@ -58,7 +58,7 @@ namespace NadekoBot.Commands { } private async void MsgUpdtd(object sender, MessageUpdatedEventArgs e) { try { - if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.client.CurrentUser.Id) + if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id) return; Channel ch; if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch) diff --git a/NadekoBot/Commands/PlayingRotate.cs b/NadekoBot/Commands/PlayingRotate.cs index defcdd00..68ce7ba6 100644 --- a/NadekoBot/Commands/PlayingRotate.cs +++ b/NadekoBot/Commands/PlayingRotate.cs @@ -13,8 +13,8 @@ namespace NadekoBot.Commands { private static Timer timer = new Timer(12000); private Dictionary> playingPlaceholders => new Dictionary> { - {"%servers%", ()=> NadekoBot.client.Servers.Count().ToString() }, - {"%users%", () => NadekoBot.client.Servers.SelectMany(s=>s.Users).Count().ToString() }, + {"%servers%", ()=> NadekoBot.Client.Servers.Count().ToString() }, + {"%users%", () => NadekoBot.Client.Servers.SelectMany(s=>s.Users).Count().ToString() }, {"%playing%", () => { var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); if(cnt == 1) { @@ -51,7 +51,7 @@ namespace NadekoBot.Commands { } if (string.IsNullOrWhiteSpace(status)) return; - Task.Run(() => { try { NadekoBot.client.SetGame(status); } catch { } }); + Task.Run(() => { try { NadekoBot.Client.SetGame(status); } catch { } }); } catch { } }; diff --git a/NadekoBot/Commands/PollCommand.cs b/NadekoBot/Commands/PollCommand.cs index 37719773..2f9ed9a1 100644 --- a/NadekoBot/Commands/PollCommand.cs +++ b/NadekoBot/Commands/PollCommand.cs @@ -66,7 +66,7 @@ namespace NadekoBot.Modules { private async Task StartPoll() { started = DateTime.Now; - NadekoBot.client.MessageReceived += Vote; + NadekoBot.Client.MessageReceived += Vote; var msgToSend = $"📃**{e.User.Name}** from **{e.Server.Name}** server has created a poll which requires your attention:\n\n" + $"**{question}**\n"; @@ -79,7 +79,7 @@ namespace NadekoBot.Modules { } public async Task StopPoll(Channel ch) { - NadekoBot.client.MessageReceived -= Vote; + NadekoBot.Client.MessageReceived -= Vote; Poll throwaway; PollCommand.ActivePolls.TryRemove(e.Server, out throwaway); try { diff --git a/NadekoBot/Commands/RequestsCommand.cs b/NadekoBot/Commands/RequestsCommand.cs index 2fba72f6..faef19fb 100644 --- a/NadekoBot/Commands/RequestsCommand.cs +++ b/NadekoBot/Commands/RequestsCommand.cs @@ -73,7 +73,7 @@ namespace NadekoBot.Commands { .Description("Deletes a request. Only owner is able to do this.") .Parameter("reqNumber", ParameterType.Required) .Do(async e => { - if (e.User.Id == NadekoBot.OwnerID) { + if (e.User.Id == NadekoBot.OwnerId) { try { if (DeleteRequest(int.Parse(e.Args[0]))) { await e.Channel.SendMessage(e.User.Mention + " Request deleted."); @@ -90,7 +90,7 @@ namespace NadekoBot.Commands { .Description("Resolves a request. Only owner is able to do this.") .Parameter("reqNumber", ParameterType.Required) .Do(async e => { - if (e.User.Id == NadekoBot.OwnerID) { + if (e.User.Id == NadekoBot.OwnerId) { try { var sc = ResolveRequest(int.Parse(e.Args[0])); if (sc != null) { diff --git a/NadekoBot/Commands/ServerGreetCommand.cs b/NadekoBot/Commands/ServerGreetCommand.cs index 4782212b..3fc4d1bc 100644 --- a/NadekoBot/Commands/ServerGreetCommand.cs +++ b/NadekoBot/Commands/ServerGreetCommand.cs @@ -30,8 +30,8 @@ namespace NadekoBot.Commands { public ServerGreetCommand() : base() { AnnouncementsDictionary = new ConcurrentDictionary(); - NadekoBot.client.UserJoined += UserJoined; - NadekoBot.client.UserLeft += UserLeft; + NadekoBot.Client.UserJoined += UserJoined; + NadekoBot.Client.UserLeft += UserLeft; List data = Classes.DBHandler.Instance.GetAllRows(); @@ -46,7 +46,7 @@ namespace NadekoBot.Commands { !AnnouncementsDictionary[e.Server.Id].Bye) return; var controls = AnnouncementsDictionary[e.Server.Id]; - var channel = NadekoBot.client.GetChannel(controls.ByeChannel); + var channel = NadekoBot.Client.GetChannel(controls.ByeChannel); var msg = controls.ByeText.Replace("%user%", "**" + e.User.Name + "**").Trim(); if (string.IsNullOrEmpty(msg)) return; @@ -73,7 +73,7 @@ namespace NadekoBot.Commands { !AnnouncementsDictionary[e.Server.Id].Greet) return; var controls = AnnouncementsDictionary[e.Server.Id]; - var channel = NadekoBot.client.GetChannel(controls.GreetChannel); + var channel = NadekoBot.Client.GetChannel(controls.GreetChannel); var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim(); if (string.IsNullOrEmpty(msg)) diff --git a/NadekoBot/Commands/SpeedTyping.cs b/NadekoBot/Commands/SpeedTyping.cs index a673ee8e..c30923e7 100644 --- a/NadekoBot/Commands/SpeedTyping.cs +++ b/NadekoBot/Commands/SpeedTyping.cs @@ -39,7 +39,7 @@ namespace NadekoBot.Commands { internal async Task Stop() { if (!IsActive) return false; - NadekoBot.client.MessageReceived -= AnswerReceived; + NadekoBot.Client.MessageReceived -= AnswerReceived; finishedUserIds.Clear(); IsActive = false; sw.Stop(); @@ -78,7 +78,7 @@ namespace NadekoBot.Commands { } private void HandleAnswers() { - NadekoBot.client.MessageReceived += AnswerReceived; + NadekoBot.Client.MessageReceived += AnswerReceived; } private async void AnswerReceived(object sender, MessageEventArgs e) { diff --git a/NadekoBot/Modules/Administration.cs b/NadekoBot/Modules/Administration.cs index 7b70eecd..aaedb627 100644 --- a/NadekoBot/Modules/Administration.cs +++ b/NadekoBot/Modules/Administration.cs @@ -436,7 +436,7 @@ namespace NadekoBot.Modules { .Description("Clears some of Nadeko's (or some other user's if supplied) messages from the current channel.\n**Usage**: .clr @X") .Parameter("user", ParameterType.Unparsed) .Do(async e => { - var usrId = NadekoBot.client.CurrentUser.Id; + var usrId = NadekoBot.Client.CurrentUser.Id; if (!string.IsNullOrWhiteSpace(e.GetArg("user")) && e.User.ServerPermissions.ManageMessages) { var usr = e.Server.FindUsers(e.GetArg("user")).FirstOrDefault(); if (usr != null) @@ -608,7 +608,7 @@ namespace NadekoBot.Modules { .Description("Clears the message queue. **OWNER ONLY**") .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .Do(e => { - NadekoBot.client.MessageQueue.Clear(); + NadekoBot.Client.MessageQueue.Clear(); }); cgb.CreateCommand(".donators") diff --git a/NadekoBot/Modules/Conversations.cs b/NadekoBot/Modules/Conversations.cs index 43646c85..c5315525 100644 --- a/NadekoBot/Modules/Conversations.cs +++ b/NadekoBot/Modules/Conversations.cs @@ -352,7 +352,7 @@ namespace NadekoBot.Modules { .Do(async e => { string str = "Bye"; foreach (var u in e.Message.MentionedUsers) { - if (u.Id != NadekoBot.client.CurrentUser.Id) + if (u.Id != NadekoBot.Client.CurrentUser.Id) str += " " + u.Mention; } await e.Channel.SendMessage(str); diff --git a/NadekoBot/Modules/Help.cs b/NadekoBot/Modules/Help.cs index 12d4c34e..8fdb3924 100644 --- a/NadekoBot/Modules/Help.cs +++ b/NadekoBot/Modules/Help.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules { .Alias("-modules") .Description("List all bot modules.") .Do(async e => { - await e.Channel.SendMessage("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.client.GetService().Modules.Select(m => m.Name))); + await e.Channel.SendMessage("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService().Modules.Select(m => m.Name))); }); cgb.CreateCommand(".commands") @@ -30,7 +30,7 @@ namespace NadekoBot.Modules { .Description("List all of the bot's commands from a certain module.") .Parameter("module", ParameterType.Unparsed) .Do(async e => { - var commands = NadekoBot.client.GetService().AllCommands + var commands = NadekoBot.Client.GetService().AllCommands .Where(c => c.Category.ToLower() == e.GetArg("module").Trim().ToLower()); if (commands == null || commands.Count() == 0) { await e.Channel.SendMessage("That module does not exist."); diff --git a/NadekoBot/Modules/Music.cs b/NadekoBot/Modules/Music.cs index fff6abae..26bc8679 100644 --- a/NadekoBot/Modules/Music.cs +++ b/NadekoBot/Modules/Music.cs @@ -28,7 +28,7 @@ namespace NadekoBot.Modules { setgameTimer.Elapsed += (s, e) => { try { int num = musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); - NadekoBot.client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.Playlist.Count())} queued"); + NadekoBot.Client.SetGame($"{num} songs".SnPl(num) + $", {musicPlayers.Sum(kvp => kvp.Value.Playlist.Count())} queued"); } catch { } }; @@ -36,7 +36,7 @@ namespace NadekoBot.Modules { } public override void Install(ModuleManager manager) { - var client = NadekoBot.client; + var client = NadekoBot.Client; manager.CreateCommands("!m", cgb => { diff --git a/NadekoBot/Modules/Permissions.cs b/NadekoBot/Modules/Permissions.cs index 07f437d6..c65f60cc 100644 --- a/NadekoBot/Modules/Permissions.cs +++ b/NadekoBot/Modules/Permissions.cs @@ -15,7 +15,7 @@ namespace NadekoBot.Modules { } public override void Install(ModuleManager manager) { - var client = NadekoBot.client; + var client = NadekoBot.Client; manager.CreateCommands("", cgb => { cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); @@ -349,7 +349,7 @@ namespace NadekoBot.Modules { try { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - foreach (var module in NadekoBot.client.GetService().Modules) { + foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetServerModulePermission(e.Server, module.Name, state); } await e.Channel.SendMessage($"All modules have been **{(state ? "enabled" : "disabled")}** on this server."); @@ -371,7 +371,7 @@ namespace NadekoBot.Modules { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); string module = PermissionHelper.ValidateModule(e.GetArg("module")); - foreach (var command in NadekoBot.client.GetService().AllCommands.Where(c => c.Category == module)) { + foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetServerCommandPermission(e.Server, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server."); @@ -392,7 +392,7 @@ namespace NadekoBot.Modules { try { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); - foreach (var module in NadekoBot.client.GetService().Modules) { + foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetChannelModulePermission(channel, module.Name, state); } @@ -416,7 +416,7 @@ namespace NadekoBot.Modules { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); string module = PermissionHelper.ValidateModule(e.GetArg("module")); Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); - foreach (var command in NadekoBot.client.GetService().AllCommands.Where(c => c.Category == module)) { + foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetChannelCommandPermission(channel, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel."); @@ -437,7 +437,7 @@ namespace NadekoBot.Modules { try { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); - foreach (var module in NadekoBot.client.GetService().Modules) { + foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetRoleModulePermission(role, module.Name, state); } @@ -461,7 +461,7 @@ namespace NadekoBot.Modules { bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); string module = PermissionHelper.ValidateModule(e.GetArg("module")); Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel")); - foreach (var command in NadekoBot.client.GetService().AllCommands.Where(c => c.Category == module)) { + foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetRoleCommandPermission(role, command.Text, state); } await e.Channel.SendMessage($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role."); diff --git a/NadekoBot/Modules/Searches.cs b/NadekoBot/Modules/Searches.cs index f7ec224a..240ae518 100644 --- a/NadekoBot/Modules/Searches.cs +++ b/NadekoBot/Modules/Searches.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules { } public override void Install(ModuleManager manager) { - var client = NadekoBot.client; + var client = NadekoBot.Client; manager.CreateCommands("", cgb => { diff --git a/NadekoBot/Modules/Trello.cs b/NadekoBot/Modules/Trello.cs index 7f0bdf67..44621b49 100644 --- a/NadekoBot/Modules/Trello.cs +++ b/NadekoBot/Modules/Trello.cs @@ -65,7 +65,7 @@ namespace NadekoBot.Modules { .Description("Joins a server") .Parameter("code", Discord.Commands.ParameterType.Required) .Do(async e => { - if (e.User.Id != NadekoBot.OwnerID) return; + if (e.User.Id != NadekoBot.OwnerId) return; try { await (await client.GetInvite(e.GetArg("code"))).Accept(); } catch (Exception ex) { @@ -77,7 +77,7 @@ namespace NadekoBot.Modules { .Description("Bind a trello bot to a single channel. You will receive notifications from your board when something is added or edited.") .Parameter("board_id", Discord.Commands.ParameterType.Required) .Do(async e => { - if (e.User.Id != NadekoBot.OwnerID) return; + if (e.User.Id != NadekoBot.OwnerId) return; if (bound != null) return; try { bound = e.Channel; @@ -93,7 +93,7 @@ namespace NadekoBot.Modules { cgb.CreateCommand("unbind") .Description("Unbinds a bot from the channel and board.") .Do(async e => { - if (e.User.Id != NadekoBot.OwnerID) return; + if (e.User.Id != NadekoBot.OwnerId) return; if (bound == null || bound != e.Channel) return; t.Stop(); bound = null; @@ -106,7 +106,7 @@ namespace NadekoBot.Modules { .Alias("list") .Description("Lists all lists yo ;)") .Do(async e => { - if (e.User.Id != NadekoBot.OwnerID) return; + if (e.User.Id != NadekoBot.OwnerId) 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() + "**"))); }); @@ -115,7 +115,7 @@ namespace NadekoBot.Modules { .Description("Lists all cards from the supplied list. You can supply either a name or an index.") .Parameter("list_name", Discord.Commands.ParameterType.Unparsed) .Do(async e => { - if (e.User.Id != NadekoBot.OwnerID) return; + if (e.User.Id != NadekoBot.OwnerId) return; if (bound == null || board == null || bound != e.Channel || e.GetArg("list_name") == null) return; int num; diff --git a/NadekoBot/NadekoBot.cs b/NadekoBot/NadekoBot.cs index 3955d61a..c76b809b 100644 --- a/NadekoBot/NadekoBot.cs +++ b/NadekoBot/NadekoBot.cs @@ -9,53 +9,49 @@ using Discord.Audio; using NadekoBot.Extensions; using System.Timers; using System.Linq; +using NadekoBot.Classes; namespace NadekoBot { - class NadekoBot { - public static DiscordClient client; + public class NadekoBot { + public static DiscordClient Client; public static string botMention; public static string GoogleAPIKey = null; - public static ulong OwnerID; public static Channel OwnerPrivateChannel = null; - public static string password; public static string TrelloAppKey; public static bool ForwardMessages = false; - public static Credentials creds; + public static Credentials Creds { get; set; } static void Main() { //load credentials from credentials.json bool loadTrello = false; try { - creds = JsonConvert.DeserializeObject(File.ReadAllText("credentials.json")); - botMention = creds.BotMention; - if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { + Creds = JsonConvert.DeserializeObject(File.ReadAllText("credentials.json")); + botMention = Creds.BotMention; + if (string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)) { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { Console.WriteLine("Google API key provided."); - GoogleAPIKey = creds.GoogleAPIKey; + GoogleAPIKey = Creds.GoogleAPIKey; } - if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { + if (string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) { Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); } else { Console.WriteLine("Trello app key provided."); - TrelloAppKey = creds.TrelloAppKey; + TrelloAppKey = Creds.TrelloAppKey; loadTrello = true; } - if (creds.ForwardMessages != true) + if (Creds.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } - if (string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) + if (string.IsNullOrWhiteSpace(Creds.SoundCloudClientID)) Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); else Console.WriteLine("SoundCloud streaming enabled."); - - OwnerID = creds.OwnerID; - password = creds.Password; } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); @@ -64,7 +60,7 @@ namespace NadekoBot { } //create new discord client - client = new DiscordClient(new DiscordConfigBuilder() { + Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 20, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => { @@ -93,16 +89,16 @@ namespace NadekoBot { }); //reply to personal messages and forward if enabled. - client.MessageReceived += Client_MessageReceived; + Client.MessageReceived += Client_MessageReceived; //add command service - var commands = client.AddService(commandService); + var commands = Client.AddService(commandService); //create module service - var modules = client.AddService(new ModuleService()); + var modules = Client.AddService(new ModuleService()); //add audio service - var audio = client.AddService(new AudioService(new AudioServiceConfigBuilder() { + var audio = Client.AddService(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, @@ -123,9 +119,9 @@ namespace NadekoBot { modules.Add(new NSFW(), "NSFW", ModuleFilter.None); //run the bot - client.ExecuteAndWait(async () => { + Client.ExecuteAndWait(async () => { try { - await client.Connect(creds.Username, creds.Password); + await Client.Connect(Creds.Username, Creds.Password); } catch (Exception ex) { Console.WriteLine($"Probably wrong EMAIL or PASSWORD.\n{ex.Message}"); @@ -139,7 +135,7 @@ namespace NadekoBot { Console.WriteLine("-----------------"); try { - OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID); + OwnerPrivateChannel = await Client.CreatePrivateChannel(OwnerId); } catch { Console.WriteLine("Failed creating private channel with the owner"); @@ -147,7 +143,7 @@ namespace NadekoBot { Classes.Permissions.PermissionsHandler.Initialize(); - client.ClientAPI.SendingRequest += (s, e) => { + Client.ClientAPI.SendingRequest += (s, e) => { try { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; @@ -182,7 +178,7 @@ namespace NadekoBot { static bool repliedRecently = false; private static async void Client_MessageReceived(object sender, MessageEventArgs e) { try { - if (e.Server != null || e.User.Id == client.CurrentUser.Id) return; + if (e.Server != null || e.User.Id == Client.CurrentUser.Id) return; if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u => u.Id)).Contains(e.User.Id)) return; // just ban this trash AutoModerator // and cancer christmass spirit @@ -192,9 +188,9 @@ namespace NadekoBot { e.User.Id == 143515953525817344) return; // FU - if (!NadekoBot.creds.DontJoinServers) { + if (!NadekoBot.Creds.DontJoinServers) { try { - await (await client.GetInvite(e.Message.Text)).Accept(); + await (await Client.GetInvite(e.Message.Text)).Accept(); await e.Channel.SendMessage("I got in!"); return; }