diff --git a/NadekoBot/Classes/JSONModels/Config.cs b/NadekoBot/Classes/JSONModels/Config.cs new file mode 100644 index 00000000..aa427aac --- /dev/null +++ b/NadekoBot/Classes/JSONModels/Config.cs @@ -0,0 +1,10 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace NadekoBot.Classes.JSONModels { + internal class Config { + } +} diff --git a/NadekoBot/Classes/Music/Song.cs b/NadekoBot/Classes/Music/Song.cs index 34966df2..ffe6f67d 100644 --- a/NadekoBot/Classes/Music/Song.cs +++ b/NadekoBot/Classes/Music/Song.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Classes.Music { /// public class PoopyBuffer { - private byte[] ringBuffer; + private readonly byte[] ringBuffer; public int WritePosition { get; private set; } = 0; public int ReadPosition { get; private set; } = 0; @@ -70,13 +70,13 @@ namespace NadekoBot.Classes.Music { return count; } // B: if i can't read as much, read to the end, - int readNormaly = BufferSize - ReadPosition; + var readNormaly = BufferSize - ReadPosition; Buffer.BlockCopy(ringBuffer, ReadPosition, buffer, 0, readNormaly); //Console.WriteLine($"Read normaly {count}[{ReadPosition} to {ReadPosition + readNormaly}]"); //then read the remaining amount from the start - int readFromStart = count - readNormaly; + var readFromStart = count - readNormaly; Buffer.BlockCopy(ringBuffer, 0, buffer, readNormaly, readFromStart); //Console.WriteLine($"Read From start {readFromStart}[{0} to {readFromStart}]"); ReadPosition = readFromStart; @@ -88,7 +88,7 @@ namespace NadekoBot.Classes.Music { if (count > buffer.Length) throw new ArgumentException(); while (ContentLength + count > BufferSize) { - await Task.Delay(20); + await Task.Delay(20, cancelToken); if (cancelToken.IsCancellationRequested) return; } @@ -104,12 +104,12 @@ namespace NadekoBot.Classes.Music { } // otherwise, i have to write to the end, then write the rest from the start - int wroteNormaly = BufferSize - WritePosition; + var wroteNormaly = BufferSize - WritePosition; Buffer.BlockCopy(buffer, 0, ringBuffer, WritePosition, wroteNormaly); //Console.WriteLine($"Wrote normally {wroteNormaly}[{WritePosition} to {BufferSize}]"); - int wroteFromStart = count - wroteNormaly; + var wroteFromStart = count - wroteNormaly; Buffer.BlockCopy(buffer, wroteNormaly, ringBuffer, 0, wroteFromStart); //Console.WriteLine($"and from start {wroteFromStart} [0 to {wroteFromStart}"); @@ -145,27 +145,25 @@ namespace NadekoBot.Classes.Music { RedirectStandardError = false, CreateNoWindow = true, }); - int blockSize = 3840; - byte[] buffer = new byte[blockSize]; - int attempt = 0; + var blockSize = 3840; + var buffer = new byte[blockSize]; + var attempt = 0; while (!cancelToken.IsCancellationRequested) { - int read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken); + var read = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, blockSize, cancelToken); if (read == 0) if (attempt++ == 20) break; else - await Task.Delay(50); + await Task.Delay(50, cancelToken); else attempt = 0; await songBuffer.WriteAsync(buffer, read, cancelToken); if (songBuffer.ContentLength > 2.MB()) prebufferingComplete = true; } - } - catch { + } catch { Console.WriteLine("Buffering errored"); - } - finally { + } finally { if (p != null) { p.CancelOutputRead(); p.StandardOutput.Dispose(); @@ -179,34 +177,33 @@ namespace NadekoBot.Classes.Music { internal async Task Play(IAudioClient voiceClient, CancellationToken cancelToken) { var t = BufferSong(cancelToken).ConfigureAwait(false); - int bufferAttempts = 0; - int waitPerAttempt = 500; - int toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9; + var bufferAttempts = 0; + const int waitPerAttempt = 500; + var toAttemptTimes = SongInfo.ProviderType != MusicType.Normal ? 5 : 9; while (!prebufferingComplete && bufferAttempts++ < toAttemptTimes) { await Task.Delay(waitPerAttempt, cancelToken); } cancelToken.ThrowIfCancellationRequested(); Console.WriteLine($"Prebuffering done? in {waitPerAttempt * bufferAttempts}"); - int blockSize = 3840; - byte[] buffer = new byte[blockSize]; - int attempt = 0; + var blockSize = 3840; + var buffer = new byte[blockSize]; + var attempt = 0; while (!cancelToken.IsCancellationRequested) { //Console.WriteLine($"Read: {songBuffer.ReadPosition}\nWrite: {songBuffer.WritePosition}\nContentLength:{songBuffer.ContentLength}\n---------"); - int read = songBuffer.Read(buffer, blockSize); + var read = songBuffer.Read(buffer, blockSize); if (read == 0) if (attempt++ == 20) { voiceClient.Wait(); Console.WriteLine("Nothing to read."); return; - } - else - await Task.Delay(50); + } else + await Task.Delay(50, cancelToken); else attempt = 0; while (this.MusicPlayer.Paused) await Task.Delay(200, cancelToken); - buffer = adjustVolume(buffer, MusicPlayer.Volume); + buffer = AdjustVolume(buffer, MusicPlayer.Volume); voiceClient.Send(buffer, 0, read); } cancelToken.ThrowIfCancellationRequested(); @@ -220,11 +217,11 @@ namespace NadekoBot.Classes.Music { } //stackoverflow ftw - private byte[] adjustVolume(byte[] audioSamples, float volume) { - if (volume == 1.0f) + private static byte[] AdjustVolume(byte[] audioSamples, float volume) { + if (Math.Abs(volume - 1.0f) < 0.01f) return audioSamples; - byte[] array = new byte[audioSamples.Length]; - for (int i = 0; i < array.Length; i += 2) { + var array = new byte[audioSamples.Length]; + for (var i = 0; i < array.Length; i += 2) { // convert byte pair to int short buf1 = audioSamples[i + 1]; @@ -233,7 +230,7 @@ namespace NadekoBot.Classes.Music { buf1 = (short)((buf1 & 0xff) << 8); buf2 = (short)(buf2 & 0xff); - short res = (short)(buf1 | buf2); + var res = (short)(buf1 | buf2); res = (short)(res * volume); // convert back @@ -254,23 +251,23 @@ namespace NadekoBot.Classes.Music { } try { - if (musicType == MusicType.Local) { - return new Song(new SongInfo { - Uri = "\"" + Path.GetFullPath(query) + "\"", - Title = Path.GetFileNameWithoutExtension(query), - Provider = "Local File", - ProviderType = musicType, - }); + switch (musicType) { + case MusicType.Local: + return new Song(new SongInfo { + Uri = "\"" + Path.GetFullPath(query) + "\"", + Title = Path.GetFileNameWithoutExtension(query), + Provider = "Local File", + ProviderType = musicType, + }); + case MusicType.Radio: + return new Song(new SongInfo { + Uri = query, + Title = $"{query}", + Provider = "Radio Stream", + ProviderType = musicType, + }); } - else if (musicType == MusicType.Radio) { - return new Song(new SongInfo { - Uri = query, - Title = $"{query}", - Provider = "Radio Stream", - ProviderType = musicType, - }); - } - else if (SoundCloud.Default.IsSoundCloudLink(query)) { + if (SoundCloud.Default.IsSoundCloudLink(query)) { var svideo = await SoundCloud.Default.GetVideoAsync(query); return new Song(new SongInfo { Title = svideo.FullName, @@ -279,29 +276,25 @@ namespace NadekoBot.Classes.Music { ProviderType = musicType, }); } - else { - var links = await SearchHelper.FindYoutubeUrlByKeywords(query); - if (links == String.Empty) - throw new OperationCanceledException("Not a valid youtube query."); - var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(links)).Unwrap(); - var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); - var video = videos - .Where(v => v.AudioBitrate < 192) - .OrderByDescending(v => v.AudioBitrate) - .FirstOrDefault(); + var links = await SearchHelper.FindYoutubeUrlByKeywords(query); + if (links == String.Empty) + throw new OperationCanceledException("Not a valid youtube query."); + var allVideos = await Task.Factory.StartNew(async () => await YouTube.Default.GetAllVideosAsync(links)).Unwrap(); + var videos = allVideos.Where(v => v.AdaptiveKind == AdaptiveKind.Audio); + var video = videos + .Where(v => v.AudioBitrate < 192) + .OrderByDescending(v => v.AudioBitrate) + .FirstOrDefault(); - if (video == null) // do something with this error - throw new Exception("Could not load any video elements based on the query."); - return new Song(new SongInfo { - Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" - Provider = "YouTube", - Uri = video.Uri, - ProviderType = musicType, - }); - - } - } - catch (Exception ex) { + if (video == null) // do something with this error + throw new Exception("Could not load any video elements based on the query."); + return new Song(new SongInfo { + Title = video.Title.Substring(0, video.Title.Length - 10), // removing trailing "- You Tube" + Provider = "YouTube", + Uri = video.Uri, + ProviderType = musicType, + }); + } catch (Exception ex) { Console.WriteLine($"Failed resolving the link.{ex.Message}"); return null; } @@ -311,8 +304,7 @@ namespace NadekoBot.Classes.Music { string file = null; try { file = await SearchHelper.GetResponseStringAsync(query); - } - catch { + } catch { return query; } if (query.Contains(".pls")) { @@ -322,13 +314,12 @@ namespace NadekoBot.Classes.Music { var m = Regex.Match(file, "File1=(?.*?)\\n"); var res = m.Groups["url"]?.ToString(); return res?.Trim(); - } - catch { + } catch { Console.WriteLine($"Failed reading .pls:\n{file}"); return null; } } - else if (query.Contains(".m3u")) { + if (query.Contains(".m3u")) { /* # This is a comment C:\xxx4xx\xxxxxx3x\xx2xxxx\xx.mp3 @@ -338,26 +329,24 @@ namespace NadekoBot.Classes.Music { var m = Regex.Match(file, "(?^[^#].*)", RegexOptions.Multiline); var res = m.Groups["url"]?.ToString(); return res?.Trim(); - } - catch { + } catch { Console.WriteLine($"Failed reading .m3u:\n{file}"); return null; } } - else if (query.Contains(".asx")) { + if (query.Contains(".asx")) { // try { var m = Regex.Match(file, ".*?)\""); var res = m.Groups["url"]?.ToString(); return res?.Trim(); - } - catch { + } catch { Console.WriteLine($"Failed reading .asx:\n{file}"); return null; } } - else if (query.Contains(".xspf")) { + if (query.Contains(".xspf")) { /* @@ -368,8 +357,7 @@ namespace NadekoBot.Classes.Music { var m = Regex.Match(file, "(?.*?)"); var res = m.Groups["url"]?.ToString(); return res?.Trim(); - } - catch { + } catch { Console.WriteLine($"Failed reading .xspf:\n{file}"); return null; } diff --git a/NadekoBot/Classes/Permissions/PermissionChecker.cs b/NadekoBot/Classes/Permissions/PermissionChecker.cs index a0d3d9e8..59898ff9 100644 --- a/NadekoBot/Classes/Permissions/PermissionChecker.cs +++ b/NadekoBot/Classes/Permissions/PermissionChecker.cs @@ -15,8 +15,8 @@ namespace NadekoBot.Classes.Permissions { public PermissionChecker() { Task.Run(async () => { while (true) { - //blacklist is cleared every 1.3 seconds. That is the most time anyone will be blocked for ever - await Task.Delay(1300); + //blacklist is cleared every 1.75 seconds. That is the most time anyone will be blocked for ever + await Task.Delay(1750); timeBlackList.Clear(); } }); @@ -45,7 +45,7 @@ namespace NadekoBot.Classes.Permissions { if (user.Server.Owner.Id == user.Id || (role != null && user.HasRole(role))) return true; ServerPermissions perms; - PermissionsHandler._permissionsDict.TryGetValue(user.Server.Id, out perms); + PermissionsHandler.PermissionsDict.TryGetValue(user.Server.Id, out perms); throw new Exception($"You don't have the necessary role (**{(perms?.PermissionsControllerRole ?? "Nadeko")}**) to change permissions."); } @@ -83,11 +83,11 @@ namespace NadekoBot.Classes.Permissions { default: return true; } - if (PermissionsHandler._permissionsDict[user.Server.Id].Verbose) //if verbose - print errors + if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors error = msg; return false; } catch (Exception ex) { - if (PermissionsHandler._permissionsDict[user.Server.Id].Verbose) //if verbose - print errors + if (PermissionsHandler.PermissionsDict[user.Server.Id].Verbose) //if verbose - print errors error = ex.Message; return false; } diff --git a/NadekoBot/Classes/Permissions/PermissionsHandler.cs b/NadekoBot/Classes/Permissions/PermissionsHandler.cs index b00a58b8..08b0af16 100644 --- a/NadekoBot/Classes/Permissions/PermissionsHandler.cs +++ b/NadekoBot/Classes/Permissions/PermissionsHandler.cs @@ -4,12 +4,13 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; using System.Threading.Tasks; using Discord.Commands; namespace NadekoBot.Classes.Permissions { public static class PermissionsHandler { - public static ConcurrentDictionary _permissionsDict = + public static ConcurrentDictionary PermissionsDict = new ConcurrentDictionary(); public enum PermissionBanType { @@ -25,19 +26,18 @@ namespace NadekoBot.Classes.Permissions { foreach (var file in Directory.EnumerateFiles("data/permissions/")) { try { var strippedFileName = Path.GetFileNameWithoutExtension(file); + if (string.IsNullOrWhiteSpace(strippedFileName)) continue; var id = ulong.Parse(strippedFileName); var data = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(file)); - _permissionsDict.TryAdd(id, data); - } catch (Exception ex) { - //Console.WriteLine($"Failed getting server with id: {file}\nReason: {ex.Message}"); - } + PermissionsDict.TryAdd(id, data); + } catch { } } Console.WriteLine("Permission initialization complete."); } internal static Permissions GetRolePermissionsById(Server server, ulong id) { ServerPermissions serverPerms; - if (!_permissionsDict.TryGetValue(server.Id, out serverPerms)) + if (!PermissionsDict.TryGetValue(server.Id, out serverPerms)) return null; Permissions toReturn; @@ -47,7 +47,7 @@ namespace NadekoBot.Classes.Permissions { internal static Permissions GetUserPermissionsById(Server server, ulong id) { ServerPermissions serverPerms; - if (!_permissionsDict.TryGetValue(server.Id, out serverPerms)) + if (!PermissionsDict.TryGetValue(server.Id, out serverPerms)) return null; Permissions toReturn; @@ -57,7 +57,7 @@ namespace NadekoBot.Classes.Permissions { internal static Permissions GetChannelPermissionsById(Server server, ulong id) { ServerPermissions serverPerms; - if (!_permissionsDict.TryGetValue(server.Id, out serverPerms)) + if (!PermissionsDict.TryGetValue(server.Id, out serverPerms)) return null; Permissions toReturn; @@ -67,32 +67,29 @@ namespace NadekoBot.Classes.Permissions { internal static Permissions GetServerPermissions(Server server) { ServerPermissions serverPerms; - if (!_permissionsDict.TryGetValue(server.Id, out serverPerms)) - return null; - - return serverPerms.Permissions; + return !PermissionsDict.TryGetValue(server.Id, out serverPerms) ? null : serverPerms.Permissions; } internal static PermissionBanType GetPermissionBanType(Command command, User user, Channel channel) { var server = user.Server; ServerPermissions serverPerms; - if (!_permissionsDict.TryGetValue(server.Id,out serverPerms)) { + if (!PermissionsDict.TryGetValue(server.Id, out serverPerms)) { serverPerms = new ServerPermissions(server.Id, server.Name); - _permissionsDict.TryAdd(server.Id, serverPerms); + PermissionsDict.TryAdd(server.Id, serverPerms); } bool val; Permissions perm; //server - if (serverPerms.Permissions.modules.TryGetValue(command.Category, out val) && val == false) + if (serverPerms.Permissions.Modules.TryGetValue(command.Category, out val) && val == false) return PermissionBanType.ServerBanModule; - if (serverPerms.Permissions.commands.TryGetValue(command.Text, out val) && val == false) + if (serverPerms.Permissions.Commands.TryGetValue(command.Text, out val) && val == false) return PermissionBanType.ServerBanCommand; //channel if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) && - perm.modules.TryGetValue(command.Category, out val) && val == false) + perm.Modules.TryGetValue(command.Category, out val) && val == false) return PermissionBanType.ChannelBanModule; if (serverPerms.ChannelPermissions.TryGetValue(channel.Id, out perm) && - perm.commands.TryGetValue(command.Text, out val) && val == false) + perm.Commands.TryGetValue(command.Text, out val) && val == false) return PermissionBanType.ChannelBanCommand; //ROLE PART - TWO CASES @@ -101,16 +98,14 @@ namespace NadekoBot.Classes.Permissions { // THAT MEANS USER CANNOT RUN THIS COMMAND // IF AT LEAST ONE ROLE EXIST THAT IS NOT BANNED, // USER CAN RUN THE COMMAND - bool foundNotBannedRole = false; + var foundNotBannedRole = false; foreach (var role in user.Roles) { //if every role is banned from using the module -> rolebanmodule if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) && - perm.modules.TryGetValue(command.Category, out val) && val == false) + perm.Modules.TryGetValue(command.Category, out val) && val == false) continue; - else { - foundNotBannedRole = true; - break; - } + foundNotBannedRole = true; + break; } if (!foundNotBannedRole) return PermissionBanType.RoleBanModule; @@ -124,7 +119,7 @@ namespace NadekoBot.Classes.Permissions { foreach (var role in user.Roles) { //if every role is banned from using the module -> rolebanmodule if (serverPerms.RolePermissions.TryGetValue(role.Id, out perm) && - perm.commands.TryGetValue(command.Text, out val) && val == false) + perm.Commands.TryGetValue(command.Text, out val) && val == false) continue; else { foundNotBannedRole = true; @@ -136,169 +131,175 @@ namespace NadekoBot.Classes.Permissions { //user if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) && - perm.modules.TryGetValue(command.Category, out val) && val == false) + perm.Modules.TryGetValue(command.Category, out val) && val == false) return PermissionBanType.UserBanModule; if (serverPerms.UserPermissions.TryGetValue(user.Id, out perm) && - perm.commands.TryGetValue(command.Text, out val) && val == false) + perm.Commands.TryGetValue(command.Text, out val) && val == false) return PermissionBanType.UserBanCommand; return PermissionBanType.None; } - private static void WriteServerToJson(ulong serverId) { - string pathToFile = $"data/permissions/{serverId}.json"; - File.WriteAllText(pathToFile, Newtonsoft.Json.JsonConvert.SerializeObject(_permissionsDict[serverId], Newtonsoft.Json.Formatting.Indented)); + private static void WriteServerToJson(ServerPermissions serverPerms) { + string pathToFile = $"data/permissions/{serverPerms}.json"; + File.WriteAllText(pathToFile, + Newtonsoft.Json.JsonConvert.SerializeObject(serverPerms, Newtonsoft.Json.Formatting.Indented)); } public static void WriteToJson() { Directory.CreateDirectory("data/permissions/"); - foreach (var kvp in _permissionsDict) { - WriteServerToJson(kvp.Key); + foreach (var kvp in PermissionsDict) { + WriteServerToJson(kvp.Value); } } public static string GetServerPermissionsRoleName(Server server) { - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); + return serverPerms.PermissionsControllerRole; } internal static void SetPermissionsRole(Server server, string roleName) { - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); + serverPerms.PermissionsControllerRole = roleName; - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } internal static void SetVerbosity(Server server, bool val) { - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); + serverPerms.Verbose = val; - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetServerModulePermission(Server server, string moduleName, bool value) { - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); - var modules = serverPerms.Permissions.modules; + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); + + var modules = serverPerms.Permissions.Modules; if (modules.ContainsKey(moduleName)) modules[moduleName] = value; else modules.Add(moduleName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetServerCommandPermission(Server server, string commandName, bool value) { - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); - var commands = serverPerms.Permissions.commands; + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); + + var commands = serverPerms.Permissions.Commands; if (commands.ContainsKey(commandName)) commands[commandName] = value; else commands.Add(commandName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetChannelModulePermission(Channel channel, string moduleName, bool value) { var server = channel.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id)) serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name)); - var modules = serverPerms.ChannelPermissions[channel.Id].modules; + var modules = serverPerms.ChannelPermissions[channel.Id].Modules; if (modules.ContainsKey(moduleName)) modules[moduleName] = value; else modules.Add(moduleName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetChannelCommandPermission(Channel channel, string commandName, bool value) { var server = channel.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.ChannelPermissions.ContainsKey(channel.Id)) serverPerms.ChannelPermissions.Add(channel.Id, new Permissions(channel.Name)); - var commands = serverPerms.ChannelPermissions[channel.Id].commands; + var commands = serverPerms.ChannelPermissions[channel.Id].Commands; if (commands.ContainsKey(commandName)) commands[commandName] = value; else commands.Add(commandName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetRoleModulePermission(Role role, string moduleName, bool value) { var server = role.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.RolePermissions.ContainsKey(role.Id)) serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name)); - var modules = serverPerms.RolePermissions[role.Id].modules; + var modules = serverPerms.RolePermissions[role.Id].Modules; if (modules.ContainsKey(moduleName)) modules[moduleName] = value; else modules.Add(moduleName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetRoleCommandPermission(Role role, string commandName, bool value) { var server = role.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.RolePermissions.ContainsKey(role.Id)) serverPerms.RolePermissions.Add(role.Id, new Permissions(role.Name)); - var commands = serverPerms.RolePermissions[role.Id].commands; + var commands = serverPerms.RolePermissions[role.Id].Commands; if (commands.ContainsKey(commandName)) commands[commandName] = value; else commands.Add(commandName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetUserModulePermission(User user, string moduleName, bool value) { var server = user.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.UserPermissions.ContainsKey(user.Id)) serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name)); - var modules = serverPerms.UserPermissions[user.Id].modules; + var modules = serverPerms.UserPermissions[user.Id].Modules; if (modules.ContainsKey(moduleName)) modules[moduleName] = value; else modules.Add(moduleName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } public static void SetUserCommandPermission(User user, string commandName, bool value) { var server = user.Server; - ServerPermissions serverPerms = _permissionsDict.GetOrAdd(server.Id, - serverPerms = new ServerPermissions(server.Id, server.Name)); + var serverPerms = PermissionsDict.GetOrAdd(server.Id, + new ServerPermissions(server.Id, server.Name)); if (!serverPerms.UserPermissions.ContainsKey(user.Id)) serverPerms.UserPermissions.Add(user.Id, new Permissions(user.Name)); - var commands = serverPerms.UserPermissions[user.Id].commands; + var commands = serverPerms.UserPermissions[user.Id].Commands; if (commands.ContainsKey(commandName)) commands[commandName] = value; else commands.Add(commandName, value); - Task.Run(() => WriteServerToJson(server.Id)); + Task.Run(() => WriteServerToJson(serverPerms)); } } /// @@ -312,33 +313,31 @@ namespace NadekoBot.Classes.Permissions { /// /// Module name with allowed/disallowed /// - public Dictionary modules { get; set; } + public Dictionary Modules { get; set; } /// /// Command name with allowed/disallowed /// - public Dictionary commands { get; set; } + public Dictionary Commands { get; set; } public Permissions(string name) { Name = name; - modules = new Dictionary(); - commands = new Dictionary(); + Modules = new Dictionary(); + Commands = new Dictionary(); } public override string ToString() { - string toReturn = ""; - var bannedModules = modules.Where(kvp => kvp.Value == false); - if (bannedModules.Count() > 0) { + var toReturn = ""; + var bannedModules = Modules.Where(kvp => kvp.Value == false); + var bannedModulesArray = bannedModules as KeyValuePair[] ?? bannedModules.ToArray(); + if (bannedModulesArray.Any()) { toReturn += "`Banned Modules:`\n"; - foreach (var m in bannedModules) { - toReturn += $"\t`[x] {m.Key}`\n"; - } + toReturn = bannedModulesArray.Aggregate(toReturn, (current, m) => current + $"\t`[x] {m.Key}`\n"); } - var bannedCommands = commands.Where(kvp => kvp.Value == false); - if (bannedCommands.Count() > 0) { + var bannedCommands = Commands.Where(kvp => kvp.Value == false); + var bannedCommandsArr = bannedCommands as KeyValuePair[] ?? bannedCommands.ToArray(); + if (bannedCommandsArr.Any()) { toReturn += "`Banned Commands:`\n"; - foreach (var c in bannedCommands) { - toReturn += $"\t`[x] {c.Key}`\n"; - } + toReturn = bannedCommandsArr.Aggregate(toReturn, (current, c) => current + $"\t`[x] {c.Key}`\n"); } return toReturn; } diff --git a/NadekoBot/Classes/SearchHelper.cs b/NadekoBot/Classes/SearchHelper.cs index 0d7711fa..71b30fe2 100644 --- a/NadekoBot/Classes/SearchHelper.cs +++ b/NadekoBot/Classes/SearchHelper.cs @@ -20,31 +20,30 @@ namespace NadekoBot.Classes { public static class SearchHelper { private static DateTime lastRefreshed = DateTime.MinValue; - private static string token = ""; + private static string token { get; set; } = ""; public static async Task GetResponseStreamAsync(string url, IEnumerable> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentNullException(nameof(url)); - using (var httpClient = new HttpClient()) { - switch (method) { - case RequestHttpMethod.Get: - if (headers != null) { - foreach (var header in headers) { - httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); - } + var httpClient = new HttpClient(); + switch (method) { + case RequestHttpMethod.Get: + if (headers != null) { + foreach (var header in headers) { + httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); } - return await httpClient.GetStreamAsync(url); - case RequestHttpMethod.Post: - FormUrlEncodedContent formContent = null; - if (headers != null) { - formContent = new FormUrlEncodedContent(headers); - } - var message = await httpClient.PostAsync(url, formContent); - return await message.Content.ReadAsStreamAsync(); - default: - throw new NotImplementedException("That type of request is unsupported."); - } + } + return await httpClient.GetStreamAsync(url); + case RequestHttpMethod.Post: + FormUrlEncodedContent formContent = null; + if (headers != null) { + formContent = new FormUrlEncodedContent(headers); + } + var message = await httpClient.PostAsync(url, formContent); + return await message.Content.ReadAsStreamAsync(); + default: + throw new NotImplementedException("That type of request is unsupported."); } } @@ -64,13 +63,19 @@ namespace NadekoBot.Classes { await RefreshAnilistToken(); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); + try { + var headers = new Dictionary {{"'access_token'", "'"+token+"'"}}; + var smallContent = await GetResponseStringAsync(link, headers); + var smallObj = JArray.Parse(smallContent)[0]; + var content = await GetResponseStringAsync("http://anilist.co/api/anime/" + smallObj["id"], headers); - var headers = new Dictionary { { "access_token", token } }; - var smallContent = await GetResponseStringAsync(link, headers); - var smallObj = JArray.Parse(smallContent)[0]; - var content = await GetResponseStringAsync("http://anilist.co/api/anime/" + smallObj["id"], headers); + return await Task.Run(() => JsonConvert.DeserializeObject(content)); - return await Task.Run(() => JsonConvert.DeserializeObject(content)); + } + catch (Exception ex) { + Console.WriteLine(ex); + return new AnimeResult(); + } } public static async Task GetMangaQueryResultLink(string query) { @@ -90,6 +95,11 @@ namespace NadekoBot.Classes { } private static async Task RefreshAnilistToken() { + if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29)) + lastRefreshed=DateTime.Now; + else { + return; + } var headers = new Dictionary { {"grant_type", "client_credentials"}, {"client_id", "kwoth-w0ki9"}, diff --git a/NadekoBot/Commands/LoLCommands.cs b/NadekoBot/Commands/LoLCommands.cs index e5ff49db..a41bade0 100644 --- a/NadekoBot/Commands/LoLCommands.cs +++ b/NadekoBot/Commands/LoLCommands.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading.Tasks; using Discord.Commands; using System.Drawing; +using NadekoBot.Classes; using NadekoBot.Extensions; using Newtonsoft.Json.Linq; @@ -22,7 +23,7 @@ namespace NadekoBot.Commands { private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer(); - public LoLCommands() { + public LoLCommands() { clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds; clearTimer.Start(); clearTimer.Elapsed += (s, e) => { @@ -31,17 +32,16 @@ namespace NadekoBot.Commands { CachedChampionImages = CachedChampionImages .Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0)) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); - } - catch { } + } catch { } }; } - private string[] trashTalk = new[] { "Better ban your counters. You are going to carry the game anyway.", - "Go with the flow. Don't think. Just ban one of these.", - "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.", - "Ask your teammates what would they like to play, and ban that.", - "If you consider playing teemo, do it. If you consider teemo, you deserve him.", - "Doesn't matter what you ban really. Enemy will ban your main and you will lose." }; + private readonly string[] trashTalk = { "Better ban your counters. You are going to carry the game anyway.", + "Go with the flow. Don't think. Just ban one of these.", + "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.", + "Ask your teammates what would they like to play, and ban that.", + "If you consider playing teemo, do it. If you consider teemo, you deserve him.", + "Doesn't matter what you ban really. Enemy will ban your main and you will lose." }; public override Func DoFunc() { throw new NotImplementedException(); @@ -63,15 +63,14 @@ namespace NadekoBot.Commands { .Do(async e => { try { //get role - string role = ResolvePos(e.GetArg("position")); - string resolvedRole = role; + var role = ResolvePos(e.GetArg("position")); + var resolvedRole = role; var name = e.GetArg("champ").Replace(" ", ""); CachedChampion champ = null; lock (cacheLock) { CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ); } if (champ != null) { - Console.WriteLine("Sending lol image from cache."); champ.ImageStream.Position = 0; await e.Channel.SendFile("champ.png", champ.ImageStream); return; @@ -79,7 +78,7 @@ namespace NadekoBot.Commands { var allData = JArray.Parse(await Classes.SearchHelper.GetResponseStringAsync($"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++) { + for (var i = 0; i < allData.Count; i++) { if (allData[i]["role"].ToString().Equals(role)) { data = allData[i]; break; @@ -89,8 +88,7 @@ namespace NadekoBot.Commands { await e.Channel.SendMessage("💢 Data for that role does not exist."); return; } - } - else { + } else { data = allData[0]; role = allData[0]["role"].ToString(); resolvedRole = ResolvePos(role); @@ -107,14 +105,14 @@ namespace NadekoBot.Commands { //name = data["title"].ToString(); // get all possible roles, and "select" the shown one var roles = new string[allData.Count]; - for (int i = 0; i < allData.Count; i++) { + for (var i = 0; i < allData.Count; i++) { roles[i] = allData[i]["role"].ToString(); if (roles[i] == role) roles[i] = ">" + roles[i] + "<"; } - var general = JArray.Parse(await Classes.SearchHelper.GetResponseStringAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")) - .Where(jt => jt["role"].ToString() == role) - .FirstOrDefault()?["general"]; + var general = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.champion.gg/stats/" + + $"champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")) + .FirstOrDefault(jt => jt["role"].ToString() == role)?["general"]; if (general == null) { Console.WriteLine("General is null."); return; @@ -122,7 +120,7 @@ namespace NadekoBot.Commands { //get build data for this role var buildData = data["items"]["mostGames"]["items"]; var items = new string[6]; - for (int i = 0; i < 6; i++) { + for (var i = 0; i < 6; i++) { items[i] = buildData[i]["id"].ToString(); } @@ -147,13 +145,12 @@ namespace NadekoBot.Commands { var orderArr = (data["skills"]["mostGames"]["order"] as JArray); //todo save this for at least 1 hour - Image img = Image.FromFile("data/lol/bg.png"); - using (Graphics g = Graphics.FromImage(img)) { + var img = Image.FromFile("data/lol/bg.png"); + using (var g = Graphics.FromImage(img)) { g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; - int statsFontSize = 15; - int margin = 5; - int imageSize = 75; + const int margin = 5; + const int imageSize = 75; var normalFont = new Font("Monaco", 8, FontStyle.Regular); var smallFont = new Font("Monaco", 7, FontStyle.Regular); //draw champ image @@ -168,18 +165,26 @@ namespace NadekoBot.Commands { //todo //draw skill order float orderFormula = 120 / orderArr.Count; - float orderVerticalSpacing = 10; - for (int i = 0; i < orderArr.Count; i++) { - float orderX = margin + margin + imageSize + orderFormula * i + i; + const float orderVerticalSpacing = 10; + for (var i = 0; i < orderArr.Count; i++) { + var orderX = margin + margin + imageSize + orderFormula * i + i; float orderY = margin + 35; - string spellName = orderArr[i].ToString().ToLowerInvariant(); + var spellName = orderArr[i].ToString().ToLowerInvariant(); - if (spellName == "w") - orderY += orderVerticalSpacing; - else if (spellName == "e") - orderY += orderVerticalSpacing * 2; - else if (spellName == "r") - orderY += orderVerticalSpacing * 3; + switch (spellName) { + case "w": + orderY += orderVerticalSpacing; + break; + case "e": + orderY += orderVerticalSpacing * 2; + break; + case "r": + orderY += orderVerticalSpacing * 3; + break; + default: + orderY += orderVerticalSpacing * 3; + break; + } g.DrawString(spellName.ToUpperInvariant(), new Font("Monaco", 7), Brushes.LimeGreen, orderX, orderY); } @@ -200,9 +205,9 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% g.DrawString($"{runes}", smallFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 40); //draw counters g.DrawString($"Best against", smallFont, Brushes.WhiteSmoke, margin, img.Height - imageSize + margin); - int smallImgSize = 50; + var smallImgSize = 50; - for (int i = 0; i < counters.Length; i++) { + for (var i = 0; i < counters.Length; i++) { g.DrawImage(GetImage(counters[i]), new Rectangle(i * (smallImgSize + margin) + margin, img.Height - smallImgSize - margin, smallImgSize, @@ -211,8 +216,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% //draw countered by g.DrawString($"Worst against", smallFont, Brushes.WhiteSmoke, img.Width - 3 * (smallImgSize + margin), img.Height - imageSize + margin); - for (int i = 0; i < countered.Length; i++) { - int j = countered.Length - i; + for (var i = 0; i < countered.Length; i++) { + var j = countered.Length - i; g.DrawImage(GetImage(countered[i]), new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), img.Height - smallImgSize - margin, smallImgSize, @@ -221,10 +226,10 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% //draw item build g.DrawString("Popular build", normalFont, Brushes.WhiteSmoke, img.Width - (3 * (smallImgSize + margin) + margin), 77); - for (int i = 0; i < 6; i++) { - var inverse_i = 5 - i; - var j = inverse_i % 3 + 1; - var k = inverse_i / 3; + for (var i = 0; i < 6; i++) { + var inverseI = 5 - i; + var j = inverseI % 3 + 1; + var k = inverseI / 3; g.DrawImage(GetImage(items[i], GetImageType.Item), new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), 92 + k * (smallImgSize + margin), smallImgSize, @@ -234,10 +239,8 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole }; CachedChampionImages.Add(cachedChamp.Name, cachedChamp); await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream); - } - catch (Exception ex) { + } catch { await e.Channel.SendMessage("💢 Failed retreiving data for that champion."); - return; } }); @@ -245,7 +248,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% .Description("Shows top 6 banned champions ordered by ban rate. Ban these champions and you will be Plat 5 in no time.") .Do(async e => { - int showCount = 6; + var showCount = 6; //http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2 try { var data = JObject.Parse( @@ -253,10 +256,10 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% .SearchHelper .GetResponseStringAsync($"http://api.champion.gg/stats/champs/mostBanned?api_key={NadekoBot.Creds.LOLAPIKey}&page=1&limit={showCount}"))["data"] as JArray; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.AppendLine($"**Showing {showCount} top banned champions.**"); sb.AppendLine($"`{trashTalk[new Random().Next(0, trashTalk.Length)]}`"); - for (int i = 0; i < data.Count; i++) { + for (var i = 0; i < data.Count; i++) { if (i % 2 == 0 && i != 0) sb.AppendLine(); sb.Append($"`{i + 1}.` **{data[i]["name"]}** "); @@ -264,8 +267,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% } await e.Channel.SendMessage(sb.ToString()); - } - catch (Exception ex) { + } catch (Exception ex) { await e.Channel.SendMessage($"Fail:\n{ex}"); } }); @@ -275,7 +277,7 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% Champion, Item } - private Image GetImage(string id, GetImageType imageType = GetImageType.Champion) { + private static Image GetImage(string id, GetImageType imageType = GetImageType.Champion) { try { switch (imageType) { case GetImageType.Champion: @@ -284,13 +286,12 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% default: return Image.FromFile($"data/lol/items/{id}.png"); } - } - catch (Exception) { + } catch (Exception) { return Image.FromFile("data/lol/_ERROR.png"); } } - private string ResolvePos(string pos) { + private static string ResolvePos(string pos) { if (string.IsNullOrWhiteSpace(pos)) return null; switch (pos.ToLowerInvariant()) { diff --git a/NadekoBot/Commands/PlayingRotate.cs b/NadekoBot/Commands/PlayingRotate.cs index 3008ad32..f6680df8 100644 --- a/NadekoBot/Commands/PlayingRotate.cs +++ b/NadekoBot/Commands/PlayingRotate.cs @@ -5,55 +5,58 @@ using System.Text; using System.Threading.Tasks; using Discord.Commands; using System.Timers; +using NadekoBot.Modules; namespace NadekoBot.Commands { internal class PlayingRotate : DiscordCommand { private static List rotatingStatuses = new List(); - private static Timer timer = new Timer(12000); + private static readonly 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() }, - {"%playing%", () => { - var cnt = Modules.Music.musicPlayers.Where(kvp => kvp.Value.CurrentSong != null).Count(); - if(cnt == 1) { + public static Dictionary> PlayingPlaceholders { get; } = + new Dictionary> { + {"%servers%", () => NadekoBot.Client.Servers.Count().ToString()}, + {"%users%", () => NadekoBot.Client.Servers.SelectMany(s => s.Users).Count().ToString()}, { + "%playing%", () => { + var cnt = Music.MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null); + if (cnt != 1) return cnt.ToString(); try { - var mp = Modules.Music.musicPlayers.FirstOrDefault(); + var mp = Music.MusicPlayers.FirstOrDefault(); return mp.Value.CurrentSong.SongInfo.Title; - } catch { } + } + catch { + return "No songs"; + } } - return cnt.ToString(); - } - }, - {"%queued%", () => Modules.Music.musicPlayers.Sum(kvp=>kvp.Value.Playlist.Count).ToString() }, - {"%trivia%", () => Commands.Trivia.runningTrivias.Count.ToString() } - }; - private object playingPlaceholderLock => new object(); + }, + {"%queued%", () => Music.MusicPlayers.Sum(kvp => kvp.Value.Playlist.Count).ToString()}, + {"%trivia%", () => Trivia.runningTrivias.Count.ToString()} + }; + + private readonly object playingPlaceholderLock = new object(); public PlayingRotate() { - int i = -1; + var i = -1; timer.Elapsed += (s, e) => { try { i++; - string status = ""; + var status = ""; lock (playingPlaceholderLock) { - if (playingPlaceholders.Count == 0) + if (PlayingPlaceholders.Count == 0) return; - if (i >= playingPlaceholders.Count) { + if (i >= PlayingPlaceholders.Count) { i = -1; return; } status = rotatingStatuses[i]; - foreach (var kvp in playingPlaceholders) { - status = status.Replace(kvp.Key, kvp.Value()); - } + status = PlayingPlaceholders.Aggregate(status, + (current, kvp) => current.Replace(kvp.Key, kvp.Value())); } if (string.IsNullOrWhiteSpace(status)) return; - Task.Run(() => { try { NadekoBot.Client.SetGame(status); } catch { } }); + Task.Run(() => { NadekoBot.Client.SetGame(status); }); } - catch { } + catch {} }; } @@ -74,7 +77,8 @@ namespace NadekoBot.Commands { cgb.CreateCommand(".addplaying") .Alias(".adpl") - .Description("Adds a specified string to the list of playing strings to rotate. Supported placeholders: " + string.Join(", ", playingPlaceholders.Keys)) + .Description("Adds a specified string to the list of playing strings to rotate. " + + "Supported placeholders: " + string.Join(", ", PlayingPlaceholders.Keys)) .Parameter("text", ParameterType.Unparsed) .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .Do(async e => { @@ -93,31 +97,32 @@ namespace NadekoBot.Commands { .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) .Do(async e => { if (rotatingStatuses.Count == 0) - await e.Channel.SendMessage("`There are no playing strings. Add some with .addplaying [text] command.`"); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < rotatingStatuses.Count; i++) { + await e.Channel.SendMessage("`There are no playing strings. " + + "Add some with .addplaying [text] command.`"); + var sb = new StringBuilder(); + for (var i = 0; i < rotatingStatuses.Count; i++) { sb.AppendLine($"`{i + 1}.` {rotatingStatuses[i]}"); } await e.Channel.SendMessage(sb.ToString()); }); cgb.CreateCommand(".removeplaying") - .Alias(".repl") - .Description("Removes a playing string on a given number.") - .Parameter("number", ParameterType.Required) - .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) - .Do(async e => { - var arg = e.GetArg("number"); - int num; - string str; - lock (playingPlaceholderLock) { - if (!int.TryParse(arg.Trim(), out num) || num <= 0 || num > rotatingStatuses.Count) - return; - str = rotatingStatuses[num - 1]; - rotatingStatuses.RemoveAt(num - 1); - } - await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})"); - }); + .Alias(".repl", ".rmpl") + .Description("Removes a playing string on a given number.") + .Parameter("number", ParameterType.Required) + .AddCheck(Classes.Permissions.SimpleCheckers.OwnerOnly()) + .Do(async e => { + var arg = e.GetArg("number"); + int num; + string str; + lock (playingPlaceholderLock) { + if (!int.TryParse(arg.Trim(), out num) || num <= 0 || num > rotatingStatuses.Count) + return; + str = rotatingStatuses[num - 1]; + rotatingStatuses.RemoveAt(num - 1); + } + await e.Channel.SendMessage($"🆗 `Removed playing string #{num}`({str})"); + }); } } } diff --git a/NadekoBot/Commands/PollCommand.cs b/NadekoBot/Commands/PollCommand.cs index ad30aa91..61e84b02 100644 --- a/NadekoBot/Commands/PollCommand.cs +++ b/NadekoBot/Commands/PollCommand.cs @@ -20,19 +20,24 @@ namespace NadekoBot.Commands { cgb.CreateCommand(">poll") .Description("Creates a poll, only person who has manage server permission can do it.\n**Usage**: >poll Question?;Answer1;Answ 2;A_3") .Parameter("allargs", ParameterType.Unparsed) - .Do(e => { - if (!e.User.ServerPermissions.ManageChannels) - return; - if (ActivePolls.ContainsKey(e.Server)) - return; - var arg = e.GetArg("allargs"); - if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) - return; - var data = arg.Split(';'); - if (data.Length < 3) - return; + .Do(async e => { + await Task.Run(async () => { + if (!e.User.ServerPermissions.ManageChannels) + return; + if (ActivePolls.ContainsKey(e.Server)) + return; + var arg = e.GetArg("allargs"); + if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) + return; + var data = arg.Split(';'); + if (data.Length < 3) + return; - new Poll(e, data[0], data.Skip(1)); + var poll = new Poll(e, data[0], data.Skip(1)); + if (PollCommand.ActivePolls.TryAdd(e.Server, poll)) { + await poll.StartPoll(); + } + }); }); cgb.CreateCommand(">pollend") .Description("Stops active poll on this server and prints the results in this channel.") @@ -47,33 +52,27 @@ namespace NadekoBot.Commands { } internal class Poll { - private CommandEventArgs e; - private string[] answers; + private readonly CommandEventArgs e; + private readonly string[] answers; private ConcurrentDictionary participants = new ConcurrentDictionary(); - private string question; + private readonly string question; private DateTime started; private CancellationTokenSource pollCancellationSource = new CancellationTokenSource(); - public Poll(CommandEventArgs e, string v, IEnumerable enumerable) { + public Poll(CommandEventArgs e, string question, IEnumerable enumerable) { this.e = e; - this.question = v; - this.answers = enumerable.ToArray(); - - if (PollCommand.ActivePolls.TryAdd(e.Server, this)) { - Task.Factory.StartNew(async () => await StartPoll()); - } + this.question = question; + this.answers = enumerable as string[] ?? enumerable.ToArray(); } - private async Task StartPoll() { + public async Task StartPoll() { started = DateTime.Now; 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"; - int num = 1; - foreach (var answ in answers) { - msgToSend += $"`{num++}.` **{answ}**\n"; - } + var num = 1; + msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); msgToSend += "\n**Private Message me with the corresponding number of the answer.**"; await e.Channel.SendMessage(msgToSend); } @@ -87,16 +86,16 @@ namespace NadekoBot.Commands { .ToDictionary(x => x.Key, x => x.Sum(kvp => 1)) .OrderBy(kvp => kvp.Value); - int totalVotesCast = results.Sum(kvp => kvp.Value); + var totalVotesCast = results.Sum(kvp => kvp.Value); if (totalVotesCast == 0) { await ch.SendMessage("📄 **No votes have been cast.**"); return; } var closeMessage = $"--------------**POLL CLOSED**--------------\n" + $"📄 , here are the results:\n"; - foreach (var kvp in results) { - closeMessage += $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]** has {kvp.Value} votes.({kvp.Value * 1.0f / totalVotesCast * 100}%)\n"; - } + closeMessage = results.Aggregate(closeMessage, (current, kvp) => current + $"`{kvp.Key}.` **[{answers[kvp.Key - 1]}]**" + + $" has {kvp.Value} votes." + + $"({kvp.Value*1.0f/totalVotesCast*100}%)\n"); await ch.SendMessage($"📄 **Total votes cast**: {totalVotesCast}\n{closeMessage}"); } catch (Exception ex) { @@ -112,12 +111,11 @@ namespace NadekoBot.Commands { return; int vote; - if (int.TryParse(e.Message.Text, out vote)) { - if (vote < 1 || vote > answers.Length) - return; - if (participants.TryAdd(e.User, vote)) { - await e.User.SendMessage($"Thanks for voting **{e.User.Name}**."); - } + if (!int.TryParse(e.Message.Text, out vote)) return; + if (vote < 1 || vote > answers.Length) + return; + if (participants.TryAdd(e.User, vote)) { + await e.User.SendMessage($"Thanks for voting **{e.User.Name}**."); } } catch { } diff --git a/NadekoBot/Modules/Conversations.cs b/NadekoBot/Modules/Conversations.cs index 1f086a76..4267a3be 100644 --- a/NadekoBot/Modules/Conversations.cs +++ b/NadekoBot/Modules/Conversations.cs @@ -17,7 +17,7 @@ using NadekoBot.Commands; namespace NadekoBot.Modules { internal class Conversations : DiscordModule { private string firestr = "🔥 ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็ด้้้้้็็็็็้้้้้็็็็็้้้้้้้้็็็็็้้้้้็็็็็้้้้ 🔥"; - public Conversations() { + public Conversations() { commands.Add(new CopyCommand()); commands.Add(new RequestsCommand()); } @@ -221,7 +221,8 @@ namespace NadekoBot.Modules { .Do(async e => { var count = 1; int.TryParse(e.Args[0], out count); - + if (count == 0) + count = 1; if (count < 1 || count > 12) { await e.Channel.SendMessage("Number must be between 0 and 12"); return; @@ -257,8 +258,7 @@ namespace NadekoBot.Modules { if (invite != null) { try { await invite.Accept(); - } - catch { + } catch { await e.Channel.SendMessage("Failed to accept invite."); } await e.Channel.SendMessage("I got in!"); diff --git a/NadekoBot/Modules/Music.cs b/NadekoBot/Modules/Music.cs index ed178ba3..59b52769 100644 --- a/NadekoBot/Modules/Music.cs +++ b/NadekoBot/Modules/Music.cs @@ -13,10 +13,10 @@ using Timer = System.Timers.Timer; namespace NadekoBot.Modules { internal class Music : DiscordModule { - public static ConcurrentDictionary musicPlayers = new ConcurrentDictionary(); - public static ConcurrentDictionary defaultMusicVolumes = new ConcurrentDictionary(); + public static ConcurrentDictionary MusicPlayers = new ConcurrentDictionary(); + public static ConcurrentDictionary DefaultMusicVolumes = new ConcurrentDictionary(); - private Timer setgameTimer => new Timer(); + private readonly Timer setgameTimer = new Timer(); private bool setgameEnabled = false; @@ -25,8 +25,8 @@ namespace NadekoBot.Modules { setgameTimer.Interval = 20000; 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"); + var num = MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null); + NadekoBot.Client.SetGame($"{num} songs".SnPl(num) + $", {MusicPlayers.Sum(kvp => kvp.Value.Playlist.Count())} queued"); } catch { } }; @@ -46,7 +46,7 @@ namespace NadekoBot.Modules { .Description("Goes to the next song in the queue.") .Do(e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return; + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.Next(); }); @@ -55,7 +55,7 @@ namespace NadekoBot.Modules { .Description("Completely stops the music, unbinds the bot from the channel, and cleans up files.") .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return; + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.Stop(); var msg = await e.Channel.SendMessage("⚠Due to music issues, NadekoBot is unable to leave voice channels at this moment.\nIf this presents inconvenience, you can use `!m mv` command to make her join your current voice channel."); await Task.Delay(5000); @@ -69,7 +69,7 @@ namespace NadekoBot.Modules { .Description("Pauses or Unpauses the song.") .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) return; + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.TogglePause(); if (musicPlayer.Paused) await e.Channel.SendMessage("🎵`Music musicPlayer paused.`"); @@ -90,11 +90,11 @@ namespace NadekoBot.Modules { .Description("Lists up to 15 currently queued songs.") .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) { + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) { await e.Channel.SendMessage("🎵 No active music musicPlayer."); return; } - string toSend = "🎵 **" + musicPlayer.Playlist.Count + "** `videos currently queued.` "; + string toSend = "🎵 **" + musicPlayer.Playlist.Count + "** `tracks currently queued.` "; if (musicPlayer.Playlist.Count >= MusicPlayer.MaximumPlaylistSize) toSend += "**Song queue is full!**\n"; else @@ -108,7 +108,7 @@ namespace NadekoBot.Modules { .Description("Shows the song currently playing.") .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; await e.Channel.SendMessage($"🎵`Now Playing` {musicPlayer.CurrentSong.PrettyName}"); }); @@ -118,7 +118,7 @@ namespace NadekoBot.Modules { .Parameter("val", ParameterType.Required) .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; var arg = e.GetArg("val"); int volume; @@ -141,7 +141,7 @@ namespace NadekoBot.Modules { await e.Channel.SendMessage("Volume number invalid."); return; } - defaultMusicVolumes.AddOrUpdate(e.Server.Id, volume / 100, (key, newval) => volume / 100); + DefaultMusicVolumes.AddOrUpdate(e.Server.Id, volume / 100, (key, newval) => volume / 100); await e.Channel.SendMessage($"🎵 `Default volume set to {volume}%`"); }); @@ -149,7 +149,7 @@ namespace NadekoBot.Modules { .Description("Sets the music volume to 0%") .Do(e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.SetVolume(0); }); @@ -158,7 +158,7 @@ namespace NadekoBot.Modules { .Description("Sets the music volume to 100% (real max is actually 150%).") .Do(e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.SetVolume(100); }); @@ -167,7 +167,7 @@ namespace NadekoBot.Modules { .Description("Sets the music volume to 50%.") .Do(e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.SetVolume(50); }); @@ -176,7 +176,7 @@ namespace NadekoBot.Modules { .Description("Shuffles the current playlist.") .Do(async e => { MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; if (musicPlayer.Playlist.Count < 2) { await e.Channel.SendMessage("💢 Not enough songs in order to perform the shuffle."); @@ -266,7 +266,7 @@ namespace NadekoBot.Modules { .Do(e => { MusicPlayer musicPlayer; var voiceChannel = e.User.VoiceChannel; - if (voiceChannel == null || voiceChannel.Server != e.Server || !musicPlayers.TryGetValue(e.Server, out musicPlayer)) + if (voiceChannel == null || voiceChannel.Server != e.Server || !MusicPlayers.TryGetValue(e.Server, out musicPlayer)) return; musicPlayer.MoveToVoiceChannel(voiceChannel); }); @@ -277,7 +277,7 @@ namespace NadekoBot.Modules { .Do(async e => { var arg = e.GetArg("num"); MusicPlayer musicPlayer; - if (!musicPlayers.TryGetValue(e.Server, out musicPlayer)) { + if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer)) { return; } if (arg?.ToLower() == "all") { @@ -306,39 +306,40 @@ namespace NadekoBot.Modules { }); } - private async Task QueueSong(Channel TextCh, Channel VoiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { - if (VoiceCh == null || VoiceCh.Server != TextCh.Server) { + private async Task QueueSong(Channel textCh, Channel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) { + if (voiceCh == null || voiceCh.Server != textCh.Server) { if (!silent) - await TextCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining."); - throw new ArgumentNullException(nameof(VoiceCh)); + await textCh.SendMessage("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining."); + throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) throw new ArgumentException("💢 Invalid query for queue song.", nameof(query)); MusicPlayer musicPlayer = null; - if (!musicPlayers.TryGetValue(TextCh.Server, out musicPlayer)) { + if (!MusicPlayers.TryGetValue(textCh.Server, out musicPlayer)) { float? vol = null; float throwAway; - if (defaultMusicVolumes.TryGetValue(TextCh.Server.Id, out throwAway)) + if (DefaultMusicVolumes.TryGetValue(textCh.Server.Id, out throwAway)) vol = throwAway; - musicPlayer = new MusicPlayer(VoiceCh, vol) { - OnCompleted = async (song) => { + musicPlayer = new MusicPlayer(voiceCh, vol) { + OnCompleted = async song => { try { - await TextCh.SendMessage($"🎵`Finished`{song.PrettyName}"); - } catch { } + await textCh.SendMessage($"🎵`Finished`{song.PrettyName}"); + } + catch {} }, OnStarted = async (song) => { try { var msgTxt = $"🎵`Playing`{song.PrettyName} `Vol: {(int)(musicPlayer.Volume * 100)}%`"; - await TextCh.SendMessage(msgTxt); + await textCh.SendMessage(msgTxt); } catch { } }, }; - musicPlayers.TryAdd(TextCh.Server, musicPlayer); + MusicPlayers.TryAdd(textCh.Server, musicPlayer); } var resolvedSong = await Song.ResolveSong(query, musicType); resolvedSong.MusicPlayer = musicPlayer; if (!silent) - await TextCh.Send($"🎵`Queued`{resolvedSong.PrettyName}"); + await textCh.Send($"🎵`Queued`{resolvedSong.PrettyName}"); musicPlayer.AddSong(resolvedSong); } } diff --git a/NadekoBot/Modules/NSFW.cs b/NadekoBot/Modules/NSFW.cs index 0f74b89b..03708313 100644 --- a/NadekoBot/Modules/NSFW.cs +++ b/NadekoBot/Modules/NSFW.cs @@ -7,11 +7,7 @@ using NadekoBot.Classes; namespace NadekoBot.Modules { internal class NSFW : DiscordModule { - private Random _r = new Random(); - - public NSFW() { - - } + private readonly Random rng = new Random(); public override void Install(ModuleManager manager) { manager.CreateCommands("", cgb => { @@ -22,9 +18,7 @@ namespace NadekoBot.Modules { .Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { - string tag = e.GetArg("tag"); - if (tag == null) - tag = ""; + var tag = e.GetArg("tag")?.Trim() ?? ""; await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink(tag)); await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink(tag)); }); @@ -32,27 +26,21 @@ namespace NadekoBot.Modules { .Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { - string tag = e.GetArg("tag"); - if (tag == null) - tag = ""; + var tag = e.GetArg("tag")?.Trim() ?? ""; await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag)); }); cgb.CreateCommand("~gelbooru") .Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { - string tag = e.GetArg("tag"); - if (tag == null) - tag = ""; + var tag = e.GetArg("tag")?.Trim() ?? ""; await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag)); }); cgb.CreateCommand("~e621") .Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri+kissing") .Parameter("tag", ParameterType.Unparsed) .Do(async e => { - string tag = e.GetArg("tag"); - if (tag == null) - tag = ""; + var tag = e.GetArg("tag")?.Trim() ?? ""; await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag)); }); cgb.CreateCommand("~cp") @@ -65,12 +53,23 @@ namespace NadekoBot.Modules { .Description("Real adult content.") .Do(async e => { try { - var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{_r.Next(0, 9304)}"))[0]; + var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}"))[0]; await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }"); } catch (Exception ex) { await e.Channel.SendMessage($"💢 {ex.Message}"); } }); + cgb.CreateCommand("~butts") + .Alias("~ass","~butt") + .Description("Real adult content.") + .Do(async e => { + try { + var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}"))[0]; + await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }"); + } catch (Exception ex) { + await e.Channel.SendMessage($"💢 {ex.Message}"); + } + }); }); } } diff --git a/NadekoBot/Modules/Permissions.cs b/NadekoBot/Modules/Permissions.cs index dd415ba1..2f5bf86b 100644 --- a/NadekoBot/Modules/Permissions.cs +++ b/NadekoBot/Modules/Permissions.cs @@ -12,7 +12,7 @@ namespace NadekoBot.Modules { public PermissionModule() { //Empty for now } - + //todo word filtering/invite bans (?:discord(?:\.gg|app\.com\/invite)\/(?([\w]{16}|(?:[\w]+-?){3}))) public override void Install(ModuleManager manager) { var client = NadekoBot.Client; manager.CreateCommands("", cgb => { @@ -51,7 +51,7 @@ namespace NadekoBot.Modules { .Parameter("arg", ParameterType.Required) .Do(async e => { var arg = e.GetArg("arg"); - bool val = PermissionHelper.ValidateBool(arg); + var val = PermissionHelper.ValidateBool(arg); PermsHandler.SetVerbosity(e.Server, val); await e.Channel.SendMessage($"Verbosity set to {val}."); }); @@ -72,7 +72,7 @@ namespace NadekoBot.Modules { .Parameter("role", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("role"); - Discord.Role role = e.Server.EveryoneRole; + var role = e.Server.EveryoneRole; if (!string.IsNullOrWhiteSpace(arg)) try { role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); @@ -95,7 +95,7 @@ namespace NadekoBot.Modules { .Parameter("channel", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("channel"); - Discord.Channel channel = e.Channel; + var channel = e.Channel; if (!string.IsNullOrWhiteSpace(arg)) try { channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); @@ -117,7 +117,7 @@ namespace NadekoBot.Modules { .Parameter("user", ParameterType.Unparsed) .Do(async e => { var arg = e.GetArg("user"); - Discord.User user = e.User; + var user = e.User; if (!string.IsNullOrWhiteSpace(e.GetArg("user"))) try { user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); @@ -139,8 +139,8 @@ namespace NadekoBot.Modules { .Description("Sets a module's permission at the server level.\n**Usage**: ;sm [module_name] enable") .Do(async e => { try { - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); PermsHandler.SetServerModulePermission(e.Server, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server."); @@ -159,8 +159,8 @@ namespace NadekoBot.Modules { .Description("Sets a command's permission at the server level.\n**Usage**: ;sc [command_name] disable") .Do(async e => { try { - string command = PermissionHelper.ValidateCommand(e.GetArg("command")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(e.GetArg("command")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); PermsHandler.SetServerCommandPermission(e.Server, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server."); @@ -180,8 +180,8 @@ namespace NadekoBot.Modules { .Description("Sets a module's permission at the role level.\n**Usage**: ;rm [module_name] enable [role_name]") .Do(async e => { try { - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { @@ -190,7 +190,7 @@ namespace NadekoBot.Modules { await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles."); } else { - Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); PermsHandler.SetRoleModulePermission(role, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role."); @@ -211,8 +211,8 @@ namespace NadekoBot.Modules { .Description("Sets a command's permission at the role level.\n**Usage**: ;rc [command_name] disable [role_name]") .Do(async e => { try { - string command = PermissionHelper.ValidateCommand(e.GetArg("command")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(e.GetArg("command")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("role")?.ToLower() == "all") { foreach (var role in e.Server.Roles) { @@ -221,7 +221,7 @@ namespace NadekoBot.Modules { await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles."); } else { - Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); PermsHandler.SetRoleCommandPermission(role, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role."); @@ -242,8 +242,8 @@ namespace NadekoBot.Modules { .Description("Sets a module's permission at the channel level.\n**Usage**: ;cm [module_name] enable [channel_name]") .Do(async e => { try { - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("channel")?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { @@ -252,7 +252,7 @@ namespace NadekoBot.Modules { await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels."); } else { - Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); PermsHandler.SetChannelModulePermission(channel, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel."); @@ -273,8 +273,8 @@ namespace NadekoBot.Modules { .Description("Sets a command's permission at the channel level.\n**Usage**: ;cc [command_name] enable [channel_name]") .Do(async e => { try { - string command = PermissionHelper.ValidateCommand(e.GetArg("command")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var command = PermissionHelper.ValidateCommand(e.GetArg("command")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); if (e.GetArg("channel")?.ToLower() == "all") { foreach (var channel in e.Server.TextChannels) { @@ -283,7 +283,7 @@ namespace NadekoBot.Modules { await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels."); } else { - Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); PermsHandler.SetChannelCommandPermission(channel, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel."); @@ -304,9 +304,9 @@ namespace NadekoBot.Modules { .Description("Sets a module's permission at the user level.\n**Usage**: ;um [module_name] enable [user_name]") .Do(async e => { try { - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - Discord.User user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); PermsHandler.SetUserModulePermission(user, module, state); await e.Channel.SendMessage($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**."); @@ -326,9 +326,9 @@ namespace NadekoBot.Modules { .Description("Sets a command's permission at the user level.\n**Usage**: ;uc [command_name] enable [user_name]") .Do(async e => { try { - string command = PermissionHelper.ValidateCommand(e.GetArg("command")); - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - Discord.User user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); + var command = PermissionHelper.ValidateCommand(e.GetArg("command")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user")); PermsHandler.SetUserCommandPermission(user, command, state); await e.Channel.SendMessage($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**."); @@ -346,7 +346,7 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all modules at the server level.\n**Usage**: ;asm [enable/disable]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetServerModulePermission(e.Server, module.Name, state); @@ -367,8 +367,8 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all commands from a certain module at the server level.\n**Usage**: ;asc [module_name] [enable/disable]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - string module = PermissionHelper.ValidateModule(e.GetArg("module")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetServerCommandPermission(e.Server, command.Text, state); @@ -389,8 +389,8 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all modules at the channel level.\n**Usage**: ;acm [enable/disable] [channel_name]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetChannelModulePermission(channel, module.Name, state); } @@ -412,9 +412,9 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all commands from a certain module at the channel level.\n**Usage**: ;acc [module_name] [enable/disable] [channel_name]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - Discord.Channel channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel")); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetChannelCommandPermission(channel, command.Text, state); } @@ -434,8 +434,8 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all modules at the role level.\n**Usage**: ;arm [enable/disable] [role_name]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role")); foreach (var module in NadekoBot.Client.GetService().Modules) { PermsHandler.SetRoleModulePermission(role, module.Name, state); } @@ -457,9 +457,9 @@ namespace NadekoBot.Modules { .Description("Sets permissions for all commands from a certain module at the role level.\n**Usage**: ;arc [module_name] [enable/disable] [channel_name]") .Do(async e => { try { - bool state = PermissionHelper.ValidateBool(e.GetArg("bool")); - string module = PermissionHelper.ValidateModule(e.GetArg("module")); - Discord.Role role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel")); + var state = PermissionHelper.ValidateBool(e.GetArg("bool")); + var module = PermissionHelper.ValidateModule(e.GetArg("module")); + var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("channel")); foreach (var command in NadekoBot.Client.GetService().AllCommands.Where(c => c.Category == module)) { PermsHandler.SetRoleCommandPermission(role, command.Text, state); } diff --git a/NadekoBot/NadekoBot.cs b/NadekoBot/NadekoBot.cs index 7fa2c592..c0af279e 100644 --- a/NadekoBot/NadekoBot.cs +++ b/NadekoBot/NadekoBot.cs @@ -8,6 +8,7 @@ using Discord.Modules; using Discord.Audio; using System.Timers; using System.Linq; +using System.Text; using System.Threading.Tasks; using NadekoBot.Classes; using NadekoBot.Classes.JSONModels; @@ -23,6 +24,7 @@ namespace NadekoBot { private static Channel OwnerPrivateChannel { get; set; } private static void Main() { + Console.OutputEncoding = Encoding.Unicode; try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject(File.ReadAllText("credentials.json")); diff --git a/NadekoBot/NadekoBot.csproj b/NadekoBot/NadekoBot.csproj index 2f2f839b..e39ae325 100644 --- a/NadekoBot/NadekoBot.csproj +++ b/NadekoBot/NadekoBot.csproj @@ -118,6 +118,7 @@ + diff --git a/NadekoBot/bin/Debug/Discord.Net.Audio.dll b/NadekoBot/bin/Debug/Discord.Net.Audio.dll index 11773713..b7c2ab09 100644 Binary files a/NadekoBot/bin/Debug/Discord.Net.Audio.dll and b/NadekoBot/bin/Debug/Discord.Net.Audio.dll differ diff --git a/NadekoBot/bin/Debug/Discord.Net.Commands.dll b/NadekoBot/bin/Debug/Discord.Net.Commands.dll index 003b4515..2a9254f9 100644 Binary files a/NadekoBot/bin/Debug/Discord.Net.Commands.dll and b/NadekoBot/bin/Debug/Discord.Net.Commands.dll differ diff --git a/NadekoBot/bin/Debug/Discord.Net.Modules.dll b/NadekoBot/bin/Debug/Discord.Net.Modules.dll index 7110cea7..b59068a1 100644 Binary files a/NadekoBot/bin/Debug/Discord.Net.Modules.dll and b/NadekoBot/bin/Debug/Discord.Net.Modules.dll differ diff --git a/NadekoBot/bin/Debug/Discord.Net.dll b/NadekoBot/bin/Debug/Discord.Net.dll index a98ae3e7..62a21875 100644 Binary files a/NadekoBot/bin/Debug/Discord.Net.dll and b/NadekoBot/bin/Debug/Discord.Net.dll differ