diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index ee6fee52..b2866ff6 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -15,6 +15,7 @@ using System.Net.Http; using System.IO; using static NadekoBot.Modules.Permissions.Permissions; using System.Collections.Concurrent; +using NLog; namespace NadekoBot.Modules.Administration { @@ -24,13 +25,17 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary GuildMuteRoles { get; } = new ConcurrentDictionary(); - public Administration(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + private static Logger _log { get; } + + public Administration() : base() { - NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; } static Administration() { + _log = LogManager.GetCurrentClassLogger(); + NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; + using (var uow = DbHandler.UnitOfWork()) { var configs = NadekoBot.AllGuildConfigs; @@ -40,7 +45,7 @@ namespace NadekoBot.Modules.Administration } } - private async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) + private static async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) { try { @@ -802,7 +807,7 @@ namespace NadekoBot.Modules.Administration { var channel = (ITextChannel)umsg.Channel; - var channels = await Task.WhenAll(_client.GetGuilds().Select(g => + var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g => g.GetDefaultChannelAsync() )).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 06613873..3003a00f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -74,13 +74,13 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary antiSpamGuilds = new ConcurrentDictionary(); - private Logger _log { get; } + private static Logger _log { get; } - public AntiRaidCommands(ShardedDiscordClient client) + static AntiRaidCommands() { _log = LogManager.GetCurrentClassLogger(); - client.MessageReceived += (imsg) => + NadekoBot.Client.MessageReceived += (imsg) => { var msg = imsg as IUserMessage; if (msg == null || msg.Author.IsBot) @@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; }; - client.UserJoined += (usr) => + NadekoBot.Client.UserJoined += (usr) => { if (usr.IsBot) return Task.CompletedTask; @@ -148,7 +148,7 @@ namespace NadekoBot.Modules.Administration }; } - private async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus) + private static async Task PunishUsers(PunishmentAction action, IRole muteRole, ProtectionType pt, params IGuildUser[] gus) { foreach (var gu in gus) { diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 8cf15cb7..3511b454 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -15,13 +15,12 @@ namespace NadekoBot.Modules.Administration [Group] public class AutoAssignRoleCommands { - private Logger _log { get; } + private static Logger _log { get; } - public AutoAssignRoleCommands() + static AutoAssignRoleCommands() { - var _client = NadekoBot.Client; - this._log = LogManager.GetCurrentClassLogger(); - _client.UserJoined += (user) => + _log = LogManager.GetCurrentClassLogger(); + NadekoBot.Client.UserJoined += (user) => { var t = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 50dfaed7..fc71e58b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Administration [Group] public class CrossServerTextChannel { - public CrossServerTextChannel() + static CrossServerTextChannel() { _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += (imsg) => @@ -50,11 +50,11 @@ namespace NadekoBot.Modules.Administration }; } - private string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => + private static string GetText(IGuild server, ITextChannel channel, IGuildUser user, IUserMessage message) => $"**{server.Name} | {channel.Name}** `{user.Username}`: " + message.Content; public static readonly ConcurrentDictionary> Subscribers = new ConcurrentDictionary>(); - private Logger _log { get; } + private static Logger _log { get; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 953f2446..8f00eded 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration [Group] public class RepeatCommands { - public ConcurrentDictionary repeaters; + public static ConcurrentDictionary repeaters { get; } public class RepeatRunner { @@ -70,7 +70,7 @@ namespace NadekoBot.Modules.Administration } } - public RepeatCommands() + static RepeatCommands() { using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index 3e047508..4490603f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Administration [Group] public class PlayingRotateCommands { - private Logger _log { get; } + private static Logger _log { get; } public static List RotatingStatusMessages { get; } public static bool RotatingStatuses { get; private set; } = false; @@ -30,12 +30,9 @@ namespace NadekoBot.Modules.Administration RotatingStatusMessages = conf.RotatingStatusMessages; RotatingStatuses = conf.RotatingStatuses; } - } - public PlayingRotateCommands() - { _log = LogManager.GetCurrentClassLogger(); - Task.Run(async () => + var t = Task.Run(async () => { var index = 0; do diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 224461b5..fe9b4639 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -16,9 +16,7 @@ namespace NadekoBot.Modules.Administration public class RatelimitCommand { public static ConcurrentDictionary RatelimitingChannels = new ConcurrentDictionary(); - private Logger _log { get; } - - private ShardedDiscordClient _client { get; } + private static Logger _log { get; } public class Ratelimiter { @@ -61,12 +59,11 @@ namespace NadekoBot.Modules.Administration } } - public RatelimitCommand() + static RatelimitCommand() { - this._client = NadekoBot.Client; - this._log = LogManager.GetCurrentClassLogger(); + _log = LogManager.GetCurrentClassLogger(); - _client.MessageReceived += (umsg) => + NadekoBot.Client.MessageReceived += (umsg) => { var t = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index 77960838..94d0589b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -17,17 +17,16 @@ namespace NadekoBot.Modules.Administration [Group] public class ServerGreetCommands { - public static long Greeted = 0; - private Logger _log; + private static Logger _log { get; } - public ServerGreetCommands() + static ServerGreetCommands() { NadekoBot.Client.UserJoined += UserJoined; NadekoBot.Client.UserLeft += UserLeft; _log = LogManager.GetCurrentClassLogger(); } - private Task UserLeft(IGuildUser user) + private static Task UserLeft(IGuildUser user) { var leftTask = Task.Run(async () => { @@ -67,7 +66,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; } - private Task UserJoined(IGuildUser user) + private static Task UserJoined(IGuildUser user) { var joinedTask = Task.Run(async () => { diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 8c7c4e00..a6ca255f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -17,10 +17,10 @@ namespace NadekoBot.Modules.Administration [Group] public class VoicePlusTextCommands { - Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled); + private static Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled); - private ConcurrentHashSet voicePlusTextCache; - public VoicePlusTextCommands() + private static ConcurrentHashSet voicePlusTextCache { get; } + static VoicePlusTextCommands() { using (var uow = DbHandler.UnitOfWork()) { @@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Administration NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler; } - private Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after) + private static Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after) { var user = (iuser as IGuildUser); var guild = user?.Guild; @@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration return Task.CompletedTask; } - private string GetChannelName(string voiceName) => + private static string GetChannelName(string voiceName) => channelNameRegex.Replace(voiceName, "").Trim().Replace(" ", "-").TrimTo(90, true) + "-voice"; [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index c7cfdaad..4a61127a 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.ClashOfClans .ToDictionary(g => g.Key, g => g.ToList())); } } - public ClashOfClans(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public ClashOfClans() : base() { } diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 32614b05..7dfa0cb5 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.CustomReactions GlobalReactions = new ConcurrentHashSet(items.Where(g => g.GuildId == null || g.GuildId == 0)); } } - public CustomReactions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public CustomReactions() : base() { } diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index cc9db328..c5b129dc 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -6,12 +6,10 @@ namespace NadekoBot.Modules { public class DiscordModule { - protected CommandService _commands { get; } - protected ShardedDiscordClient _client { get; } protected Logger _log { get; } protected string _prefix { get; } - public DiscordModule(ILocalization loc, CommandService cmds, ShardedDiscordClient client) + public DiscordModule() { string prefix; if (NadekoBot.ModulePrefixes.TryGetValue(this.GetType().Name, out prefix)) @@ -19,8 +17,6 @@ namespace NadekoBot.Modules else _prefix = "?missing_prefix?"; - _commands = cmds; - _client = client; _log = LogManager.GetCurrentClassLogger(); } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index 9bda0461..9dc5de5b 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -18,11 +18,7 @@ namespace NadekoBot.Modules.Gambling [Group] public class AnimalRacing { - - public AnimalRacing() - { - } - public static ConcurrentDictionary AnimalRaces = new ConcurrentDictionary(); + public static ConcurrentDictionary AnimalRaces { get; } = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] @@ -119,7 +115,7 @@ namespace NadekoBot.Modules.Gambling await Task.Run(StartRace); End(); } - catch { } + catch { try { End(); } catch { } } }); } diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 0ea7bd5e..e5e84e11 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -15,10 +15,9 @@ namespace NadekoBot.Modules.Gambling [Group] public class FlipCoinCommands { - NadekoRandom rng { get; } = new NadekoRandom(); + private static NadekoRandom rng { get; } = new NadekoRandom(); private const string headsPath = "data/images/coins/heads.png"; private const string tailsPath = "data/images/coins/tails.png"; - public FlipCoinCommands() { } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 1ab94b4f..3dc865ca 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -20,7 +20,7 @@ namespace NadekoBot.Modules.Gambling public static string CurrencyPluralName { get; set; } public static string CurrencySign { get; set; } - public Gambling(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Gambling() : base() { using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 0ac7e6e1..3a0ef80c 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -31,23 +31,20 @@ namespace NadekoBot.Modules.Games [Group] public class PlantPickCommands { - private Random rng; - - private ConcurrentHashSet generationChannels = new ConcurrentHashSet(); + private static ConcurrentHashSet generationChannels { get; } = new ConcurrentHashSet(); //channelid/message - private ConcurrentDictionary> plantedFlowers = new ConcurrentDictionary>(); + private static ConcurrentDictionary> plantedFlowers { get; } = new ConcurrentDictionary>(); //channelId/last generation - private ConcurrentDictionary lastGenerations = new ConcurrentDictionary(); + private static ConcurrentDictionary lastGenerations { get; } = new ConcurrentDictionary(); - private float chance; - private int cooldown; - private Logger _log { get; } + private static float chance { get; } + private static int cooldown { get; } + private static Logger _log { get; } - public PlantPickCommands() + static PlantPickCommands() { _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += PotentialFlowerGeneration; - rng = new NadekoRandom(); using (var uow = DbHandler.UnitOfWork()) { @@ -60,7 +57,7 @@ namespace NadekoBot.Modules.Games } } - private Task PotentialFlowerGeneration(IMessage imsg) + private static Task PotentialFlowerGeneration(IMessage imsg) { var msg = imsg as IUserMessage; if (msg == null || msg.IsAuthor() || msg.Author.IsBot) @@ -76,6 +73,7 @@ namespace NadekoBot.Modules.Games var t = Task.Run(async () => { var lastGeneration = lastGenerations.GetOrAdd(channel.Id, DateTime.MinValue); + var rng = new NadekoRandom(); if (DateTime.Now - TimeSpan.FromSeconds(cooldown) < lastGeneration) //recently generated in this channel, don't generate again return; @@ -194,8 +192,11 @@ namespace NadekoBot.Modules.Games } } - private string GetRandomCurrencyImagePath() => - Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault(); + private static string GetRandomCurrencyImagePath() + { + var rng = new NadekoRandom(); + return Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault(); + } int GetRandomNumber() { diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 115fdb94..a95a9bd8 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Games } } } - public Games(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Games() : base() { } diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 0166cf4c..80bcc0a0 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -30,7 +30,7 @@ namespace NadekoBot.Modules.Help } } - public Help(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Help() : base() { } @@ -38,7 +38,7 @@ namespace NadekoBot.Modules.Help public async Task Modules(IUserMessage umsg) { - await umsg.Channel.SendMessageAsync("📜 **List of modules:** ```css\n• " + string.Join("\n• ", _commands.Modules.Select(m => m.Name)) + $"\n``` ℹ️ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") + await umsg.Channel.SendMessageAsync("📜 **List of modules:** ```css\n• " + string.Join("\n• ", NadekoBot.CommandService.Modules.Select(m => m.Name)) + $"\n``` ℹ️ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") .ConfigureAwait(false); } @@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Help module = module?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(module)) return; - var cmds = _commands.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) + var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) .OrderBy(c => c.Text) .Distinct(new CommandTextEqualityComparer()) .AsEnumerable(); @@ -84,7 +84,7 @@ namespace NadekoBot.Modules.Help await ch.SendMessageAsync(HelpString).ConfigureAwait(false); return; } - var com = _commands.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); + var com = NadekoBot.CommandService.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); if (com == null) { @@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Help helpstr.AppendLine(string.Join("\n", NadekoBot.CommandService.Modules.Where(m => m.Name.ToLowerInvariant() != "help").OrderBy(m => m.Name).Prepend(NadekoBot.CommandService.Modules.FirstOrDefault(m=>m.Name.ToLowerInvariant()=="help")).Select(m => $"- [{m.Name}](#{m.Name.ToLowerInvariant()})"))); helpstr.AppendLine(); string lastModule = null; - foreach (var com in _commands.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First())) + foreach (var com in NadekoBot.CommandService.Commands.OrderBy(com=>com.Module.Name).GroupBy(c=>c.Text).Select(g=>g.First())) { if (com.Module.Name != lastModule) { diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index c0586225..a095a258 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Music public const string MusicDataPath = "data/musicdata"; private IGoogleApiService _google; - public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base(loc, cmds, client) + public Music(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService google) : base() { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 4c16efbb..0d95ee21 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.NSFW [NadekoModule("NSFW", "~")] public class NSFW : DiscordModule { - public NSFW(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public NSFW() : base() { } diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index ac459dd0..8ef8f5c4 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Permissions public class CmdCdsCommands { public static ConcurrentDictionary> commandCooldowns { get; } - private static ConcurrentDictionary> activeCooldowns = new ConcurrentDictionary>(); + private static ConcurrentDictionary> activeCooldowns { get; } = new ConcurrentDictionary>(); static CmdCdsCommands() { diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index a581e007..d6f22fb5 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -14,14 +14,14 @@ namespace NadekoBot.Modules.Permissions [Group] public class FilterCommands { - public static ConcurrentHashSet InviteFilteringChannels { get; set; } - public static ConcurrentHashSet InviteFilteringServers { get; set; } + public static ConcurrentHashSet InviteFilteringChannels { get; } + public static ConcurrentHashSet InviteFilteringServers { get; } //serverid, filteredwords - private static ConcurrentDictionary> ServerFilteredWords { get; set; } + private static ConcurrentDictionary> ServerFilteredWords { get; } - public static ConcurrentHashSet WordFilteringChannels { get; set; } - public static ConcurrentHashSet WordFilteringServers { get; set; } + public static ConcurrentHashSet WordFilteringChannels { get; } + public static ConcurrentHashSet WordFilteringServers { get; } public static ConcurrentHashSet FilteredWordsForChannel(ulong channelId, ulong guildId) { diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 8d6c32ea..815896f6 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions } //guildid, root permission - public static ConcurrentDictionary Cache; + public static ConcurrentDictionary Cache { get; } static Permissions() { @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions } } - public Permissions(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Permissions() : base() { } diff --git a/src/NadekoBot/Modules/Pokemon/Pokemon.cs b/src/NadekoBot/Modules/Pokemon/Pokemon.cs index 35e1b703..31dbf2cb 100644 --- a/src/NadekoBot/Modules/Pokemon/Pokemon.cs +++ b/src/NadekoBot/Modules/Pokemon/Pokemon.cs @@ -27,7 +27,7 @@ namespace NadekoBot.Modules.Pokemon private Logger _pokelog { get; } - public Pokemon(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Pokemon() : base() { _pokelog = LogManager.GetCurrentClassLogger(); if (File.Exists(PokemonTypesFile)) diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index 8571846b..24789931 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -10,6 +10,7 @@ using NLog; using System; using System.Collections.Generic; using System.Net.Http; +using System.Threading; using System.Threading.Tasks; namespace NadekoBot.Modules.Searches @@ -19,14 +20,30 @@ namespace NadekoBot.Modules.Searches [Group] public class AnimeSearchCommands { - private Logger _log; + private static Timer anilistTokenRefresher { get; } + private static Logger _log { get; } + private static string anilistToken { get; set; } - private string anilistToken { get; set; } - private DateTime lastRefresh { get; set; } - - public AnimeSearchCommands() + static AnimeSearchCommands() { _log = LogManager.GetCurrentClassLogger(); + anilistTokenRefresher = new Timer(async (state) => + { + var headers = new Dictionary { + {"grant_type", "client_credentials"}, + {"client_id", "kwoth-w0ki9"}, + {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, + }; + + using (var http = new HttpClient()) + { + http.AddFakeHeaders(); + var formContent = new FormUrlEncodedContent(headers); + var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); + var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); + } + }, null, TimeSpan.FromSeconds(0), TimeSpan.FromMinutes(29)); } [NadekoCommand, Usage, Description, Aliases] @@ -119,7 +136,6 @@ namespace NadekoBot.Modules.Searches throw new ArgumentNullException(nameof(query)); try { - await RefreshAnilistToken().ConfigureAwait(false); var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query); using (var http = new HttpClient()) @@ -137,37 +153,12 @@ namespace NadekoBot.Modules.Searches } } - private async Task RefreshAnilistToken() - { - if (DateTime.Now - lastRefresh > TimeSpan.FromMinutes(29)) - lastRefresh = DateTime.Now; - else - { - return; - } - var headers = new Dictionary { - {"grant_type", "client_credentials"}, - {"client_id", "kwoth-w0ki9"}, - {"client_secret", "Qd6j4FIAi1ZK6Pc7N7V4Z"}, - }; - using (var http = new HttpClient()) - { - http.AddFakeHeaders(); - var formContent = new FormUrlEncodedContent(headers); - var response = await http.PostAsync("http://anilist.co/api/auth/access_token", formContent).ConfigureAwait(false); - var stringContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); - anilistToken = JObject.Parse(stringContent)["access_token"].ToString(); - } - - } - private async Task GetMangaData(string query) { if (string.IsNullOrWhiteSpace(query)) throw new ArgumentNullException(nameof(query)); try { - await RefreshAnilistToken().ConfigureAwait(false); using (var http = new HttpClient()) { var res = await http.GetStringAsync("http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query) + $"?access_token={anilistToken}").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index 98695f6f..f22fbf88 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -19,11 +19,11 @@ namespace NadekoBot.Modules.Searches [Group] public class JokeCommands { - private List wowJokes = new List(); - private List magicItems; - private Logger _log; + private static List wowJokes = new List(); + private static List magicItems; + private static Logger _log; - public JokeCommands() + static JokeCommands() { _log = LogManager.GetCurrentClassLogger(); if (File.Exists("data/wowjokes.json")) diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index b915a835..50ad53ea 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -23,7 +23,7 @@ namespace NadekoBot.Modules.Searches obj["name"].GetHashCode(); } - private string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.", + private static string[] trashTalk { get; } = { "Better ban your counters. You are going to carry the game anyway.", "Go with the flow. Don't think. Just ban one of these.", "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.", "Ask your teammates what would they like to play, and ban that.", diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index e3d663a5..de26d025 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -18,9 +18,9 @@ namespace NadekoBot.Modules.Searches [Group] public class OsuCommands { - private Logger _log; + private static Logger _log; - public OsuCommands() + static OsuCommands() { _log = LogManager.GetCurrentClassLogger(); } diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index efb7ee93..c2750c54 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -21,9 +21,9 @@ namespace NadekoBot.Modules.Searches public const string PokemonAbilitiesFile = "data/pokemon/pokemon_abilities.json"; public const string PokemonListFile = "data/pokemon/pokemon_list.json"; - private Logger _log; + private static Logger _log; - public PokemonSearchCommands() + static PokemonSearchCommands() { _log = LogManager.GetCurrentClassLogger(); if (File.Exists(PokemonListFile)) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 39b60c2b..b8b21bf5 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -69,14 +69,14 @@ namespace NadekoBot.Modules.Searches [Group] public class StreamNotificationCommands { - private Timer checkTimer { get; } - private ConcurrentDictionary oldCachedStatuses = new ConcurrentDictionary(); - private ConcurrentDictionary cachedStatuses = new ConcurrentDictionary(); - private Logger _log { get; } + private static Timer checkTimer { get; } + private static ConcurrentDictionary oldCachedStatuses = new ConcurrentDictionary(); + private static ConcurrentDictionary cachedStatuses = new ConcurrentDictionary(); + private static Logger _log { get; } - private bool FirstPass { get; set; } = true; + private static bool FirstPass { get; set; } = true; - public StreamNotificationCommands() + static StreamNotificationCommands() { _log = NLog.LogManager.GetCurrentClassLogger(); @@ -118,7 +118,7 @@ namespace NadekoBot.Modules.Searches }, null, TimeSpan.Zero, TimeSpan.FromSeconds(60)); } - private async Task GetStreamStatus(FollowedStream stream, bool checkCache = true) + private static async Task GetStreamStatus(FollowedStream stream, bool checkCache = true) { string response; StreamStatus result; diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index bd55e1e1..67a4fdc9 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -25,7 +25,7 @@ namespace NadekoBot.Modules.Searches { private IGoogleApiService _google { get; } - public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base(loc, cmds, client) + public Searches(ILocalization loc, CommandService cmds, ShardedDiscordClient client, IGoogleApiService youtube) : base() { _google = youtube; } diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index edf3d974..90f71c55 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility if (guild == null) server = channel.Guild; else - server = _client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault(); + server = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guild.ToUpperInvariant()).FirstOrDefault(); if (server == null) return; diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index c0a319f8..1e6fce9c 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Utility [NadekoModule("Utility", ".")] public partial class Utility : DiscordModule { - public Utility(ILocalization loc, CommandService cmds, ShardedDiscordClient client) : base(loc, cmds, client) + public Utility() : base() { } @@ -236,8 +236,11 @@ namespace NadekoBot.Modules.Utility var result = string.Join("\n", matches.Cast() .Select(m => $"**Name:** {m.Groups["name"]} **Link:** http://discordapp.com/api/emojis/{m.Groups["id"]}.png")); - - await msg.Channel.SendMessageAsync(result).ConfigureAwait(false); + + if (string.IsNullOrWhiteSpace(result)) + await msg.Channel.SendErrorAsync("No special emojis found."); + else + await msg.Channel.SendMessageAsync(result).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index e110a8e2..1de7c3d3 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -75,12 +75,12 @@ namespace NadekoBot CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); - //setup DI - var depMap = new DependencyMap(); - depMap.Add(Localizer); - depMap.Add(Client); - depMap.Add(CommandService); - depMap.Add(Google); + ////setup DI + //var depMap = new DependencyMap(); + //depMap.Add(Localizer); + //depMap.Add(Client); + //depMap.Add(CommandService); + //depMap.Add(Google); //setup typereaders @@ -104,7 +104,7 @@ namespace NadekoBot // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); - await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly, depMap).ConfigureAwait(false); + await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false); #if !GLOBAL_NADEKO await CommandService.Load(new Music(Localizer, CommandService, Client, Google)).ConfigureAwait(false); #endif diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 29d7e03d..0b5051c7 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -79,80 +79,7 @@ namespace NadekoBot.Extensions public static IEnumerable Members(this IRole role) => NadekoBot.Client.GetGuild(role.GuildId)?.GetUsers().Where(u => u.Roles.Contains(role)) ?? Enumerable.Empty(); - - public static async Task ReplyLong(this IUserMessage msg, string content, string[] breakOn = null, string addToPartialEnd = "", string addToPartialStart = "") - { - if (content.Length == 0) return null; - var characterLimit = 1750; - if (content.Length < characterLimit) return new[] { await msg.Channel.SendMessageAsync(content).ConfigureAwait(false) }; - if (breakOn == null) breakOn = new[] { "\n", " ", " " }; - var list = new List(); - var splitItems = new List(); - foreach (var breaker in breakOn) - { - if (splitItems.Count == 0) - { - splitItems = Regex.Split(content, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); - } - else - { - for (int i = 0; i < splitItems.Count; i++) - { - var temp = splitItems[i]; - if (temp.Length > characterLimit) - { - var splitDeep = Regex.Split(temp, $"(?={breaker})").Where(s => !string.IsNullOrWhiteSpace(s)); - splitItems.RemoveAt(i); - splitItems.InsertRange(i, splitDeep); - } - } - } - if (splitItems.All(s => s.Length < characterLimit)) break; - } - //We remove any entries that are larger than 2000 chars - if (splitItems.Any(s => s.Length >= characterLimit)) - { - splitItems = splitItems.Where(s => s.Length < characterLimit).ToList(); - } - //ensured every item can be sent (if individually) - var firstItem = true; - Queue buildItems = new Queue(splitItems); - StringBuilder builder = new StringBuilder(); - - while (buildItems.Count > 0) - { - if (builder.Length == 0) - { - //first item to add - if (!firstItem) - builder.Append(addToPartialStart); - else - firstItem = false; - builder.Append(buildItems.Dequeue()); - } - else - { - builder.Append(buildItems.Dequeue()); - } - if (buildItems.Count == 0) - { - list.Add(await msg.Channel.SendMessageAsync(builder.ToString())); - builder.Clear(); - } - else - { - var peeked = buildItems.Peek(); - if (builder.Length + peeked.Length + addToPartialEnd.Length > characterLimit) - { - builder.Append(addToPartialEnd); - list.Add(await msg.Channel.SendMessageAsync(builder.ToString())); - builder.Clear(); - } - } - } - return list.ToArray(); - } - + public static Task EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index b5fd1cbb..cbf49aa2 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -60,8 +60,11 @@ }, "configurations": { "GlobalNadeko": { - "buildOptions": { "define": [ "GLOBAL_NADEKO" ] }, - "compilationOptions": { "optimize": true } + "buildOptions": { + "define": [ "GLOBAL_NADEKO" ], + "nowarn": [ "CS1573", "CS1591" ], + "optimize": true + } } } }