From ac476214763b5458090c46d8785aae5ffdbeb725 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 19:43:57 +0100 Subject: [PATCH 01/30] A lot of work on moving to b2 --- src/NadekoBot/Attributes/NadekoModule.cs | 4 +- .../Attributes/OwnerOnlyAttribute.cs | 5 +- .../Modules/Administration/Administration.cs | 337 ++++++++---------- .../Commands/AntiRaidCommands.cs | 20 +- .../Commands/AutoAssignRoleCommands.cs | 4 +- .../Commands/CrossServerTextChannel.cs | 26 +- .../Commands/DMForwardCommands.cs | 14 +- .../Administration/Commands/LogCommand.cs | 38 +- .../Commands/MessageRepeater.cs | 16 +- .../Administration/Commands/Migration.cs | 8 +- .../Administration/Commands/MuteCommands.cs | 34 +- .../Commands/PlayingRotateCommands.cs | 16 +- .../Commands/RatelimitCommand.cs | 14 +- .../Commands/SelfAssignedRolesCommand.cs | 32 +- .../Administration/Commands/SelfCommands.cs | 4 +- .../Commands/ServerGreetCommands.cs | 38 +- .../Commands/VoicePlusTextCommands.cs | 16 +- .../Modules/ClashOfClans/ClashOfClans.cs | 34 +- .../CustomReactions/CustomReactions.cs | 62 ++-- .../Modules/CustomReactions/Extensions.cs | 2 +- src/NadekoBot/Modules/DiscordModule.cs | 2 +- .../Modules/Gambling/Commands/AnimalRacing.cs | 10 +- .../Gambling/Commands/DiceRollCommand.cs | 26 +- .../Modules/Gambling/Commands/DrawCommand.cs | 10 +- .../Gambling/Commands/FlipCoinCommand.cs | 20 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 56 +-- .../Games/Commands/CleverBotCommands.cs | 22 +- .../Games/Commands/Hangman/HangmanGame.cs | 14 +- .../Modules/Games/Commands/HangmanCommands.cs | 12 +- .../Modules/Games/Commands/LeetCommands.cs | 2 +- .../Games/Commands/PlantAndPickCommands.cs | 26 +- .../Modules/Games/Commands/PollCommands.cs | 32 +- .../Games/Commands/SpeedTypingCommands.cs | 28 +- .../Games/Commands/Trivia/TriviaGame.cs | 12 +- .../Modules/Games/Commands/TriviaCommands.cs | 12 +- src/NadekoBot/Modules/Games/Games.cs | 14 +- src/NadekoBot/Modules/Help/Help.cs | 28 +- src/NadekoBot/Modules/Music/Music.cs | 128 +++---- src/NadekoBot/Modules/NSFW/NSFW.cs | 28 +- .../Permissions/Commands/BlacklistCommands.cs | 2 +- .../Permissions/Commands/CmdCdsCommands.cs | 14 +- .../Permissions/Commands/FilterCommands.cs | 22 +- .../Permissions/PermissionExtensions.cs | 4 +- .../Modules/Permissions/Permissions.cs | 76 ++-- src/NadekoBot/Modules/Pokemon/Pokemon.cs | 25 +- .../Searches/Commands/AnimeSearchCommands.cs | 82 ++--- .../Modules/Searches/Commands/JokeCommands.cs | 26 +- .../Modules/Searches/Commands/LoLCommands.cs | 10 +- .../Searches/Commands/MemegenCommands.cs | 9 +- .../Searches/Commands/OMDB/OmdbProvider.cs | 5 +- .../Modules/Searches/Commands/OsuCommands.cs | 14 +- .../Searches/Commands/OverwatchCommands.cs | 49 ++- .../Searches/Commands/PlaceCommands.cs | 12 +- .../Commands/PokemonSearchCommands.cs | 22 +- .../Commands/StreamNotificationCommands.cs | 63 ++-- .../Modules/Searches/Commands/Translator.cs | 37 +- .../Modules/Searches/Commands/XkcdCommands.cs | 22 +- src/NadekoBot/Modules/Searches/Searches.cs | 104 +++--- src/NadekoBot/Modules/Trello/Trello.cs | 8 +- .../Modules/Utility/Commands/CalcCommand.cs | 10 +- .../Modules/Utility/Commands/InfoCommands.cs | 28 +- .../Modules/Utility/Commands/QuoteCommands.cs | 54 ++- .../Modules/Utility/Commands/Remind.cs | 24 +- .../Utility/Commands/UnitConversion.cs | 14 +- src/NadekoBot/Modules/Utility/Utility.cs | 149 +++----- src/NadekoBot/NadekoBot.cs | 12 +- src/NadekoBot/Services/CommandHandler.cs | 62 ++-- src/NadekoBot/Services/Impl/BotCredentials.cs | 2 +- src/NadekoBot/Services/Impl/StatsService.cs | 2 +- src/NadekoBot/ShardedDiscordClient.cs | 57 ++- .../TypeReaders/BotCommandTypeReader.cs | 5 +- src/NadekoBot/TypeReaders/GuildTypeReader.cs | 2 +- src/NadekoBot/TypeReaders/ModuleTypeReader.cs | 2 +- .../TypeReaders/PermissionActionTypeReader.cs | 2 +- src/NadekoBot/_Extensions/Extensions.cs | 32 +- src/NadekoBot/project.json | 10 +- 76 files changed, 1049 insertions(+), 1230 deletions(-) diff --git a/src/NadekoBot/Attributes/NadekoModule.cs b/src/NadekoBot/Attributes/NadekoModule.cs index a4aba6c6..832d7ad4 100644 --- a/src/NadekoBot/Attributes/NadekoModule.cs +++ b/src/NadekoBot/Attributes/NadekoModule.cs @@ -7,7 +7,7 @@ using System.Linq; namespace NadekoBot.Attributes { [System.AttributeUsage(AttributeTargets.Class)] - sealed class NadekoModuleAttribute : ModuleAttribute + sealed class NadekoModuleAttribute : GroupAttribute { //modulename / prefix private static Dictionary modulePrefixes = null; @@ -28,7 +28,7 @@ namespace NadekoBot.Attributes public NadekoModuleAttribute(string moduleName, string defaultPrefix) : base(GetModulePrefix(moduleName, defaultPrefix)) { - AppendSpace = false; + //AppendSpace = false; } private static string GetModulePrefix(string moduleName, string defaultPrefix) diff --git a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs index f04b6ef2..ecb5c552 100644 --- a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs +++ b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs @@ -1,12 +1,13 @@ ๏ปฟusing System.Threading.Tasks; using Discord.Commands; using Discord; +using System; namespace NadekoBot.Attributes { public class OwnerOnlyAttribute : PreconditionAttribute { - public override Task CheckPermissions(IUserMessage context, Command executingCommand, object moduleInstance) => - Task.FromResult((NadekoBot.Credentials.IsOwner(context.Author) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner"))); + public override Task CheckPermissions(CommandContext context, CommandInfo executingCommand,IDependencyMap depMap) => + Task.FromResult((NadekoBot.Credentials.IsOwner(context.User) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner"))); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 196aaea5..bacb683d 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -41,11 +41,11 @@ namespace NadekoBot.Modules.Administration } - private static async Task DelMsgOnCmd_Handler(IUserMessage msg, Command cmd) + private static async Task DelMsgOnCmd_Handler(SocketUserMessage msg, CommandInfo cmd) { try { - var channel = msg.Channel as ITextChannel; + var channel = Context.Channel as SocketTextChannel; if (channel == null) return; @@ -67,14 +67,12 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] - public async Task ResetPermissions(IUserMessage imsg) + [RequireUserPermission(GuildPermission.Administrator)] + public async Task ResetPermissions() { - var channel = (ITextChannel)imsg.Channel; - using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.PermissionsFor(channel.Guild.Id); + var config = uow.GuildConfigs.PermissionsFor(Context.Guild.Id); config.RootPermission = Permission.GetDefaultRoot(); var toAdd = new PermissionCache() { @@ -82,148 +80,136 @@ namespace NadekoBot.Modules.Administration PermRole = config.PermissionRole, Verbose = config.VerbosePermissions, }; - Permissions.Permissions.Cache.AddOrUpdate(channel.Guild.Id, - toAdd, (id, old) => toAdd); + Permissions.Permissions.Cache.AddOrUpdate(Context.Guild.Id, toAdd, (id, old) => toAdd); await uow.CompleteAsync(); } - await channel.SendConfirmAsync($"{imsg.Author.Mention} ๐Ÿ†— **Permissions for this server are reset.**"); + await Context.Channel.SendConfirmAsync($"{Context.Message.Author.Mention} ๐Ÿ†— **Permissions for this server are reset.**"); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] - public async Task Delmsgoncmd(IUserMessage umsg) + [RequireUserPermission(GuildPermission.Administrator)] + public async Task Delmsgoncmd() { - var channel = (ITextChannel)umsg.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { - var conf = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var conf = uow.GuildConfigs.For(Context.Guild.Id, set => set); enabled = conf.DeleteMessageOnCommand = !conf.DeleteMessageOnCommand; await uow.CompleteAsync(); } if (enabled) - await channel.SendConfirmAsync("โœ… **Now automatically deleting successful command invokations.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **Now automatically deleting successful command invokations.**").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ—**Stopped automatic deletion of successful command invokations.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ—**Stopped automatic deletion of successful command invokations.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task Setrole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task Setrole(IGuildUser usr, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; try { await usr.AddRolesAsync(role).ConfigureAwait(false); - await channel.SendConfirmAsync($"โ„น๏ธ Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Successfully added role **{role.Name}** to user **{usr.Username}**").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync("โš ๏ธ Failed to add role. **Bot has insufficient permissions.**\n").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Failed to add role. **Bot has insufficient permissions.**\n").ConfigureAwait(false); Console.WriteLine(ex.ToString()); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task Removerole(IUserMessage umsg, IGuildUser usr, [Remainder] IRole role) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task Removerole(IGuildUser usr, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; try { await usr.RemoveRolesAsync(role).ConfigureAwait(false); - await channel.SendConfirmAsync($"โ„น๏ธ Successfully removed role **{role.Name}** from user **{usr.Username}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Successfully removed role **{role.Name}** from user **{usr.Username}**").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ Failed to remove role. Most likely reason: **Insufficient permissions.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Failed to remove role. Most likely reason: **Insufficient permissions.**").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task RenameRole(IUserMessage umsg, IRole roleToEdit, string newname) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task RenameRole(IRole roleToEdit, string newname) { - var channel = (ITextChannel)umsg.Channel; try { - if (roleToEdit.Position > (await channel.Guild.GetCurrentUserAsync().ConfigureAwait(false)).Roles.Max(r => r.Position)) + if (roleToEdit.Position > (await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false)).Roles.Max(r => r.Position)) { - await channel.SendErrorAsync("๐Ÿšซ You can't edit roles higher than your highest role.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿšซ You can't edit roles higher than your highest role.").ConfigureAwait(false); return; } await roleToEdit.ModifyAsync(g => g.Name = newname).ConfigureAwait(false); - await channel.SendConfirmAsync("โœ… Role renamed.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Role renamed.").ConfigureAwait(false); } catch (Exception) { - await channel.SendErrorAsync("โš ๏ธ Failed to rename role. Probably **insufficient permissions.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Failed to rename role. Probably **insufficient permissions.**").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task RemoveAllRoles(IUserMessage umsg, [Remainder] IGuildUser user) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task RemoveAllRoles([Remainder] IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; - try { await user.RemoveRolesAsync(user.Roles).ConfigureAwait(false); - await channel.SendConfirmAsync($"๐Ÿ—‘ Successfully removed **all** roles from user **{user.Username}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ Successfully removed **all** roles from user **{user.Username}**").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ Failed to remove roles. Most likely reason: **Insufficient permissions.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Failed to remove roles. Most likely reason: **Insufficient permissions.**").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task CreateRole(IUserMessage umsg, [Remainder] string roleName = null) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task CreateRole([Remainder] string roleName = null) { - var channel = (ITextChannel)umsg.Channel; - - if (string.IsNullOrWhiteSpace(roleName)) return; try { - var r = await channel.Guild.CreateRoleAsync(roleName).ConfigureAwait(false); - await channel.SendConfirmAsync($"โœ… Successfully created role **{r.Name}**.").ConfigureAwait(false); + var r = await Context.Guild.CreateRoleAsync(roleName).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ… Successfully created role **{r.Name}**.").ConfigureAwait(false); } catch (Exception) { - await channel.SendErrorAsync("โš ๏ธ Unspecified error.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Unspecified error.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task RoleColor(IUserMessage umsg, params string[] args) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task RoleColor(params string[] args) { - var channel = (ITextChannel)umsg.Channel; - if (args.Count() != 2 && args.Count() != 4) { - await channel.SendErrorAsync("โŒ The parameters specified are **invalid.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โŒ The parameters specified are **invalid.**").ConfigureAwait(false); return; } var roleName = args[0].ToUpperInvariant(); - var role = channel.Guild.Roles.Where(r=>r.Name.ToUpperInvariant() == roleName).FirstOrDefault(); + var role = Context.Guild.Roles.Where(r=>r.Name.ToUpperInvariant() == roleName).FirstOrDefault(); if (role == null) { - await channel.SendErrorAsync("๐Ÿšซ That role **does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿšซ That role **does not exist.**").ConfigureAwait(false); return; } try @@ -236,108 +222,104 @@ namespace NadekoBot.Modules.Administration var blue = Convert.ToByte(rgb ? int.Parse(args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16)); await role.ModifyAsync(r => r.Color = new Discord.Color(red, green, blue).RawValue).ConfigureAwait(false); - await channel.SendConfirmAsync($"โ˜‘๏ธ Role **{role.Name}'s** color has been changed.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ˜‘๏ธ Role **{role.Name}'s** color has been changed.").ConfigureAwait(false); } catch (Exception) { - await channel.SendErrorAsync("โš ๏ธ Error occured, most likely **invalid parameters** or **insufficient permissions.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Error occured, most likely **invalid parameters** or **insufficient permissions.**").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.BanMembers)] - public async Task Ban(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null) + [RequireUserPermission(GuildPermission.BanMembers)] + public async Task Ban(IGuildUser user, [Remainder] string msg = null) { - var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(msg)) { msg = "โ—๏ธNo reason provided."; } - if (umsg.Author.Id != user.Guild.OwnerId && user.Roles.Select(r=>r.Position).Max() >= ((IGuildUser)umsg.Author).Roles.Select(r => r.Position).Max()) + if (Context.User.Id != user.Guild.OwnerId && Context.User.Roles.Select(r=>r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) { - await channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); + await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy.").ConfigureAwait(false); return; } try { - await (await user.CreateDMChannelAsync()).SendErrorAsync($"โ›”๏ธ **You have been BANNED from `{channel.Guild.Name}` server.**\n" + + await (await user.CreateDMChannelAsync()).SendErrorAsync($"โ›”๏ธ **You have been BANNED from `{Context.Guild.Name}` server.**\n" + $"โš– *Reason:* {msg}").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); } catch { } try { - await channel.Guild.AddBanAsync(user, 7).ConfigureAwait(false); + await Context.Guild.AddBanAsync(user, 7).ConfigureAwait(false); - await channel.SendConfirmAsync("โ›”๏ธ **Banned** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ›”๏ธ **Banned** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ **Error.** Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ **Error.** Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.KickMembers)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Softban(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null) + [RequireUserPermission(GuildPermission.KickMembers)] + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Softban(IGuildUser user, [Remainder] string msg = null) { - var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(msg)) { msg = "โ—๏ธNo reason provided."; } - if (umsg.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)umsg.Author).Roles.Select(r => r.Position).Max()) + if (Context.User.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) { - await channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); + await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; } try { - await user.SendErrorAsync($"โ˜ฃ **You have been SOFT-BANNED from `{channel.Guild.Name}` server.**\n" + + await user.SendErrorAsync($"โ˜ฃ **You have been SOFT-BANNED from `{Context.Guild.Name}` server.**\n" + $"โš– *Reason:* {msg}").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); } catch { } try { - await channel.Guild.AddBanAsync(user, 7).ConfigureAwait(false); - try { await channel.Guild.RemoveBanAsync(user).ConfigureAwait(false); } - catch { await channel.Guild.RemoveBanAsync(user).ConfigureAwait(false); } + await Context.Guild.AddBanAsync(user, 7).ConfigureAwait(false); + try { await Context.Guild.RemoveBanAsync(user).ConfigureAwait(false); } + catch { await Context.Guild.RemoveBanAsync(user).ConfigureAwait(false); } - await channel.SendConfirmAsync("โ˜ฃ **Soft-Banned** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ˜ฃ **Soft-Banned** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.KickMembers)] - public async Task Kick(IUserMessage umsg, IGuildUser user, [Remainder] string msg = null) + [RequireUserPermission(GuildPermission.KickMembers)] + public async Task Kick(IGuildUser user, [Remainder] string msg = null) { - var channel = (ITextChannel)umsg.Channel; - if (user == null) { - await channel.SendErrorAsync("โ—๏ธUser not found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โ—๏ธUser not found.").ConfigureAwait(false); return; } - if (umsg.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)umsg.Author).Roles.Select(r => r.Position).Max()) + if (Context.Message.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) { - await channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); + await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; } if (!string.IsNullOrWhiteSpace(msg)) { try { - await user.SendErrorAsync($"โ€ผ๏ธ**You have been KICKED from `{channel.Guild.Name}` server.**\n" + + await user.SendErrorAsync($"โ€ผ๏ธ**You have been KICKED from `{Context.Guild.Name}` server.**\n" + $"โš– *Reason:* {msg}").ConfigureAwait(false); await Task.Delay(2000).ConfigureAwait(false); } @@ -346,21 +328,19 @@ namespace NadekoBot.Modules.Administration try { await user.KickAsync().ConfigureAwait(false); - await channel.SendConfirmAsync("โ€ผ๏ธ**Kicked** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ€ผ๏ธ**Kicked** user **" + user.Username + "** ID: `" + user.Id + "`").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.DeafenMembers)] - public async Task Deafen(IUserMessage umsg, params IGuildUser[] users) + [RequireUserPermission(GuildPermission.DeafenMembers)] + public async Task Deafen(params IGuildUser[] users) { - var channel = (ITextChannel)umsg.Channel; - if (!users.Any()) return; try @@ -369,21 +349,19 @@ namespace NadekoBot.Modules.Administration { await u.ModifyAsync(usr=>usr.Deaf = true).ConfigureAwait(false); } - await channel.SendConfirmAsync("๐Ÿ”‡ **Deafen** successful.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ”‡ **Deafen** successful.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.DeafenMembers)] - public async Task UnDeafen(IUserMessage umsg, params IGuildUser[] users) + [RequireUserPermission(GuildPermission.DeafenMembers)] + public async Task UnDeafen(params IGuildUser[] users) { - var channel = (ITextChannel)umsg.Channel; - if (!users.Any()) return; try @@ -392,138 +370,131 @@ namespace NadekoBot.Modules.Administration { await u.ModifyAsync(usr=> usr.Deaf = false).ConfigureAwait(false); } - await channel.SendConfirmAsync("๐Ÿ”Š **Undeafen** successful.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ”Š **Undeafen** successful.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task DelVoiChanl(IUserMessage umsg, [Remainder] IVoiceChannel voiceChannel) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task DelVoiChanl([Remainder] IVoiceChannel voiceChannel) { await voiceChannel.DeleteAsync().ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync($"๐Ÿ—‘ Removed voice channel **{voiceChannel.Name}** successfully.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ Removed voice channel **{voiceChannel.Name}** successfully.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task CreatVoiChanl(IUserMessage umsg, [Remainder] string channelName) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task CreatVoiChanl([Remainder] string channelName) { - var channel = (ITextChannel)umsg.Channel; - var ch = await channel.Guild.CreateVoiceChannelAsync(channelName).ConfigureAwait(false); - await channel.SendConfirmAsync($"โœ… Created voice channel **{ch.Name}**. ID: `{ch.Id}`").ConfigureAwait(false); + var ch = await Context.Guild.CreateVoiceChannelAsync(channelName).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ… Created voice channel **{ch.Name}**. ID: `{ch.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task DelTxtChanl(IUserMessage umsg, [Remainder] ITextChannel toDelete) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task DelTxtChanl([Remainder] ITextChannel toDelete) { await toDelete.DeleteAsync().ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync($"๐Ÿ—‘ Removed text channel **{toDelete.Name}**. ID: `{toDelete.Id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ Removed text channel **{toDelete.Name}**. ID: `{toDelete.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task CreaTxtChanl(IUserMessage umsg, [Remainder] string channelName) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task CreaTxtChanl([Remainder] string channelName) { - var channel = (ITextChannel)umsg.Channel; - var txtCh = await channel.Guild.CreateTextChannelAsync(channelName).ConfigureAwait(false); - await channel.SendConfirmAsync($"โœ… Added text channel **{txtCh.Name}**. ID: `{txtCh.Id}`").ConfigureAwait(false); + var txtCh = await Context.Guild.CreateTextChannelAsync(channelName).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ… Added text channel **{txtCh.Name}**. ID: `{txtCh.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task SetTopic(IUserMessage umsg, [Remainder] string topic = null) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task SetTopic([Remainder] string topic = null) { - var channel = (ITextChannel)umsg.Channel; topic = topic ?? ""; - await channel.ModifyAsync(c => c.Topic = topic); - await channel.SendConfirmAsync("๐Ÿ†— **New channel topic set.**").ConfigureAwait(false); + await Context.Channel.ModifyAsync(c => c.Topic = topic); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **New channel topic set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task SetChanlName(IUserMessage umsg, [Remainder] string name) + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task SetChanlName([Remainder] string name) { - var channel = (ITextChannel)umsg.Channel; - - await channel.ModifyAsync(c => c.Name = name).ConfigureAwait(false); - await channel.SendConfirmAsync("๐Ÿ†— **New channel name set.**").ConfigureAwait(false); + await Context.Channel.ModifyAsync(c => c.Name = name).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **New channel name set.**").ConfigureAwait(false); } //delets her own messages, no perm required [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Prune(IUserMessage umsg) - { - var channel = (ITextChannel)umsg.Channel; + public async Task Prune() + { + var user = await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false); - var user = channel.Guild.GetCurrentUser(); - - var enumerable = (await umsg.Channel.GetMessagesAsync()).AsEnumerable(); + var enumerable = (await Context.Channel.GetMessagesAsync().Flatten()).AsEnumerable(); enumerable = enumerable.Where(x => x.Author.Id == user.Id); - await umsg.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); + await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); } // prune x [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(ChannelPermission.ManageMessages)] - public async Task Prune(IUserMessage msg, int count) + [RequireUserPermission(ChannelPermission.ManageMessages)] + public async Task Prune(int count) { - var channel = (ITextChannel)msg.Channel; - await (msg as IUserMessage).DeleteAsync(); + + await (Context.Message as IUserMessage).DeleteAsync(); int limit = (count < 100) ? count : 100; - var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit)); - await msg.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); + var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten().ConfigureAwait(false)); + await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); } //prune @user [x] [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(ChannelPermission.ManageMessages)] - public async Task Prune(IUserMessage msg, IGuildUser user, int count = 100) + [RequireUserPermission(ChannelPermission.ManageMessages)] + public async Task Prune(IGuildUser user, int count = 100) { - var channel = (ITextChannel)msg.Channel; + int limit = (count < 100) ? count : 100; - var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit)).Where(m => m.Author == user); - await msg.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); + var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten()).Where(m => m.Author == user); + await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task Die(IUserMessage umsg) + public async Task Die() { - try { await umsg.Channel.SendConfirmAsync("โ„น๏ธ **Shutting down.**").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await Context.Channel.SendConfirmAsync("โ„น๏ธ **Shutting down.**").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } await Task.Delay(2000).ConfigureAwait(false); Environment.Exit(0); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task SetName(IUserMessage umsg, [Remainder] string newName) + public async Task SetName([Remainder] string newName) { if (string.IsNullOrWhiteSpace(newName)) return; - await (await NadekoBot.Client.GetCurrentUserAsync()).ModifyAsync(u => u.Username = newName).ConfigureAwait(false); + await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Username = newName).ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync($"โ„น๏ธ Successfully changed name to **{newName}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Successfully changed name to **{newName}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task SetAvatar(IUserMessage umsg, [Remainder] string img = null) + public async Task SetAvatar([Remainder] string img = null) { if (string.IsNullOrWhiteSpace(img)) return; @@ -536,38 +507,38 @@ namespace NadekoBot.Modules.Administration await sr.CopyToAsync(imgStream); imgStream.Position = 0; - await (await NadekoBot.Client.GetCurrentUserAsync().ConfigureAwait(false)).ModifyAsync(u => u.Avatar = imgStream).ConfigureAwait(false); + await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = imgStream).ConfigureAwait(false); } } - await umsg.Channel.SendConfirmAsync("๐Ÿ†’ **New avatar set.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†’ **New avatar set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task SetGame(IUserMessage umsg, [Remainder] string game = null) + public async Task SetGame([Remainder] string game = null) { game = game ?? ""; await NadekoBot.Client.SetGame(game).ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync("๐Ÿ‘พ **New game set.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ‘พ **New game set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task SetStream(IUserMessage umsg, string url, [Remainder] string name = null) + public async Task SetStream(string url, [Remainder] string name = null) { name = name ?? ""; await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync("โ„น๏ธ **New stream set.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ **New stream set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task Send(IUserMessage umsg, string where, [Remainder] string msg = null) + public async Task Send(string where, [Remainder] string msg = null) { if (string.IsNullOrWhiteSpace(msg)) return; @@ -584,7 +555,7 @@ namespace NadekoBot.Modules.Administration if (ids[1].ToUpperInvariant().StartsWith("C:")) { var cid = ulong.Parse(ids[1].Substring(2)); - var ch = server.GetTextChannels().Where(c => c.Id == cid).FirstOrDefault(); + var ch = (await server.GetTextChannelsAsync()).Where(c => c.Id == cid).FirstOrDefault(); if (ch == null) { return; @@ -594,7 +565,7 @@ namespace NadekoBot.Modules.Administration else if (ids[1].ToUpperInvariant().StartsWith("U:")) { var uid = ulong.Parse(ids[1].Substring(2)); - var user = server.GetUsers().Where(u => u.Id == uid).FirstOrDefault(); + var user = (await server.GetUsersAsync()).Where(u => u.Id == uid).FirstOrDefault(); if (user == null) { return; @@ -603,42 +574,40 @@ namespace NadekoBot.Modules.Administration } else { - await umsg.Channel.SendErrorAsync("โš ๏ธ Invalid format.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Invalid format.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task Announce(IUserMessage umsg, [Remainder] string message) + public async Task Announce([Remainder] string message) { var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g => g.GetDefaultChannelAsync() )).ConfigureAwait(false); - await Task.WhenAll(channels.Select(c => c.SendConfirmAsync($"๐Ÿ†• Message from {umsg.Author} `[Bot Owner]`:", message))) + await Task.WhenAll(channels.Select(c => c.SendConfirmAsync($"๐Ÿ†• Message from {Context.User} `[Bot Owner]`:", message))) .ConfigureAwait(false); - await umsg.Channel.SendConfirmAsync("๐Ÿ†—").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†—").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task SaveChat(IUserMessage umsg, int cnt) + public async Task SaveChat(int cnt) { - var channel = (ITextChannel)umsg.Channel; - ulong? lastmsgId = null; var sb = new StringBuilder(); var msgs = new List(cnt); while (cnt > 0) { var dlcnt = cnt < 100 ? cnt : 100; - IReadOnlyCollection dledMsgs; + IEnumerable dledMsgs; if (lastmsgId == null) - dledMsgs = await umsg.Channel.GetMessagesAsync(cnt).ConfigureAwait(false); + dledMsgs = await Context.Channel.GetMessagesAsync(cnt).Flatten().ConfigureAwait(false); else - dledMsgs = await umsg.Channel.GetMessagesAsync(lastmsgId.Value, Direction.Before, dlcnt); + dledMsgs = await Context.Channel.GetMessagesAsync(lastmsgId.Value, Direction.Before, dlcnt).Flatten().ConfigureAwait(false); if (!dledMsgs.Any()) break; @@ -647,8 +616,8 @@ namespace NadekoBot.Modules.Administration lastmsgId = msgs[msgs.Count - 1].Id; cnt -= 100; } - var title = $"Chatlog-{channel.Guild.Name}/#{channel.Name}-{DateTime.Now}.txt"; - await (umsg.Author as IGuildUser).SendFileAsync( + var title = $"Chatlog-{Context.Guild.Name}/#{Context.Channel.Name}-{DateTime.Now}.txt"; + await (Context.User as IGuildUser).SendFileAsync( await JsonConvert.SerializeObject(new { Messages = msgs.Select(s => $"ใ€{s.Timestamp:HH:mm:ss}ใ€‘{s.Author}:" + s.ToString()) }, Formatting.Indented).ToStream().ConfigureAwait(false), title, title).ConfigureAwait(false); } @@ -656,32 +625,30 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.MentionEveryone)] - public async Task MentionRole(IUserMessage umsg, params IRole[] roles) + [RequireUserPermission(GuildPermission.MentionEveryone)] + public async Task MentionRole(params IRole[] roles) { - var channel = (ITextChannel)umsg.Channel; - - string send = $"โ•{umsg.Author.Mention} has invoked a mention on the following roles โ•"; + string send = $"โ•{Context.User.Mention} has invoked a mention on the following roles โ•"; foreach (var role in roles) { send += $"\n**{role.Name}**\n"; - send += string.Join(", ", (await channel.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Distinct().Select(u=>u.Mention)); + send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Distinct().Select(u=>u.Mention)); } while (send.Length > 2000) { var curstr = send.Substring(0, 2000); - await channel.SendMessageAsync(curstr.Substring(0, + await Context.Channel.SendMessageAsync(curstr.Substring(0, curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + send.Substring(2000); } - await channel.SendMessageAsync(send).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(send).ConfigureAwait(false); } IGuild nadekoSupportServer; [NadekoCommand, Usage, Description, Aliases] - public async Task Donators(IUserMessage umsg) + public async Task Donators() { IEnumerable donatorsOrdered; @@ -689,7 +656,7 @@ namespace NadekoBot.Modules.Administration { donatorsOrdered = uow.Donators.GetDonatorsOrdered(); } - await umsg.Channel.SendConfirmAsync("Thanks to the people listed below for making this project happen!", string.Join("โญ", donatorsOrdered.Select(d => d.Name))).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Thanks to the people listed below for making this project happen!", string.Join("โญ", donatorsOrdered.Select(d => d.Name))).ConfigureAwait(false); nadekoSupportServer = nadekoSupportServer ?? NadekoBot.Client.GetGuild(117523346618318850); @@ -700,14 +667,14 @@ namespace NadekoBot.Modules.Administration if (patreonRole == null) return; - var usrs = nadekoSupportServer.GetUsers().Where(u => u.Roles.Contains(patreonRole)); - await umsg.Channel.SendConfirmAsync("Patreon supporters", string.Join("โญ", usrs.Select(d => d.Username))).ConfigureAwait(false); + var usrs = (await nadekoSupportServer.GetUsersAsync()).Where(u => u.RoleIds.Contains(236667642088259585u)); + await Context.Channel.SendConfirmAsync("Patreon supporters", string.Join("โญ", usrs.Select(d => d.Username))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task Donadd(IUserMessage umsg, IUser donator, int amount) + public async Task Donadd(IUser donator, int amount) { Donator don; using (var uow = DbHandler.UnitOfWork()) @@ -716,7 +683,7 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } - await umsg.Channel.SendConfirmAsync($"Successfuly added a new donator. Total donated amount from this user: {don.Amount} ๐Ÿ‘‘").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Successfuly added a new donator. Total donated amount from this user: {don.Amount} ๐Ÿ‘‘").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 29f465df..14fd957a 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -84,10 +84,10 @@ namespace NadekoBot.Modules.Administration NadekoBot.Client.MessageReceived += (imsg) => { var msg = imsg as IUserMessage; - if (msg == null || msg.Author.IsBot) + if (msg == null || Context.User.IsBot) return Task.CompletedTask; - var channel = msg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -99,14 +99,14 @@ namespace NadekoBot.Modules.Administration if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings)) return; - var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, new UserSpamStats(msg.Content), + var stats = spamSettings.UserStats.AddOrUpdate(Context.User.Id, new UserSpamStats(msg.Content), (id, old) => { old.ApplyNextMessage(msg.Content); return old; }); if (stats.Count >= spamSettings.MessageThreshold) { - if (spamSettings.UserStats.TryRemove(msg.Author.Id, out stats)) + if (spamSettings.UserStats.TryRemove(Context.User.Id, out stats)) { - await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)msg.Author) + await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)Context.User) .ConfigureAwait(false); } } @@ -196,10 +196,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiRaid(IUserMessage imsg, int userThreshold, int seconds, PunishmentAction action) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (userThreshold < 2 || userThreshold > 30) { @@ -234,16 +234,16 @@ namespace NadekoBot.Modules.Administration }; antiRaidGuilds.AddOrUpdate(channel.Guild.Id, setting, (id, old) => setting); - await channel.SendConfirmAsync($"โ„น๏ธ {imsg.Author.Mention} If **{userThreshold}** or more users join within **{seconds}** seconds, I will **{action}** them.") + await channel.SendConfirmAsync($"โ„น๏ธ {Context.User.Mention} If **{userThreshold}** or more users join within **{seconds}** seconds, I will **{action}** them.") .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiSpam(IUserMessage imsg, int messageCount=3, PunishmentAction action = PunishmentAction.Mute) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (messageCount < 2 || messageCount > 10) return; diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index e834e80b..1009936c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -45,10 +45,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] public async Task AutoAssignRole(IUserMessage umsg, [Remainder] IRole role = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; GuildConfig conf; using (var uow = DbHandler.UnitOfWork()) diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 7867a078..d7f517b5 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -21,28 +21,28 @@ namespace NadekoBot.Modules.Administration _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += (imsg) => { - if (imsg.Author.IsBot) + if (Context.User.IsBot) return Task.CompletedTask; var msg = imsg as IUserMessage; if (msg == null) return Task.CompletedTask; - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; Task.Run(async () => { - if (msg.Author.Id == NadekoBot.Client.GetCurrentUser().Id) return; + if (Context.User.Id == NadekoBot.Client.CurrentUser().Id) return; foreach (var subscriber in Subscribers) { var set = subscriber.Value; - if (!set.Contains(msg.Channel)) + if (!set.Contains(Context.Channel)) continue; foreach (var chan in set.Except(new[] { channel })) { - try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)msg.Author, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)Context.User, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } } }); @@ -59,24 +59,24 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Scsc(IUserMessage msg) + public async Task Scsc() { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var token = new NadekoRandom().Next(); var set = new ConcurrentHashSet(); if (Subscribers.TryAdd(token, set)) { set.Add(channel); - await ((IGuildUser)msg.Author).SendConfirmAsync("This is your CSC token", token.ToString()).ConfigureAwait(false); + await ((IGuildUser)Context.User).SendConfirmAsync("This is your CSC token", token.ToString()).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Jcsc(IUserMessage imsg, int token) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; ConcurrentHashSet set; if (!Subscribers.TryGetValue(token, out set)) @@ -87,10 +87,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] - public async Task Lcsc(IUserMessage imsg) + [RequireUserPermission(GuildPermission.ManageGuild)] + public async Task Lcsc() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; foreach (var subscriber in Subscribers) { diff --git a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs index fac9949e..cc304cf8 100644 --- a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs @@ -29,9 +29,9 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task ForwardMessages(IUserMessage imsg) + public async Task ForwardMessages() { - var channel = imsg.Channel; + var channel = Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -47,9 +47,9 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task ForwardToAll(IUserMessage imsg) + public async Task ForwardToAll() { - var channel = imsg.Channel; + var channel = Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -68,16 +68,16 @@ namespace NadekoBot.Modules.Administration { if (ForwardDMs && ownerChannels.Any()) { - var title = $"DM from [{msg.Author}]({msg.Author.Id})"; + var title = $"DM from [{Context.User}]({Context.User.Id})"; if (ForwardDMsToAllOwners) { - var msgs = await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != msg.Author.Id) + var msgs = await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != Context.User.Id) .Select(ch => ch.SendConfirmAsync(title, msg.Content))).ConfigureAwait(false); } else { var firstOwnerChannel = ownerChannels.First(); - if (firstOwnerChannel.Recipient.Id != msg.Author.Id) + if (firstOwnerChannel.Recipient.Id != Context.User.Id) try { await firstOwnerChannel.SendConfirmAsync(title, msg.Content).ConfigureAwait(false); } catch { } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 06ebe4e8..2113d064 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -469,7 +469,7 @@ namespace NadekoBot.Modules.Administration if (msg == null || msg.IsAuthor()) return Task.CompletedTask; - var channel = msg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -488,7 +488,7 @@ namespace NadekoBot.Modules.Administration { try { - var str = $@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{msg.Author.Username}#{msg.Author.Discriminator}**__ **| Deleted Message |** ๐Ÿ†” `{msg.Author.Id}` #โƒฃ `{channel.Name}` + var str = $@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{Context.User.Username}#{Context.User.Discriminator}**__ **| Deleted Message |** ๐Ÿ†” `{Context.User.Id}` #โƒฃ `{channel.Name}` ๐Ÿ—‘ {msg.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator)}"; if (msg.Attachments.Any()) str += $"{Environment.NewLine}๐Ÿ“Ž {string.Join(", ", msg.Attachments.Select(a => a.ProxyUrl))}"; @@ -581,11 +581,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task LogServer(IUserMessage msg) + public async Task LogServer() { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; LogSetting logSetting; using (var uow = DbHandler.UnitOfWork()) { @@ -605,11 +605,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task LogIgnore(IUserMessage imsg) + public async Task LogIgnore() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) { @@ -635,9 +635,9 @@ namespace NadekoBot.Modules.Administration //[LocalizedCommand, LocalizedRemarks, LocalizedSummary, LocalizedAlias] //[RequireContext(ContextType.Guild)] //[OwnerOnly] - //public async Task LogAdd(IUserMessage msg, [Remainder] string eventName) + //public async Task LogAdd([Remainder] string eventName) //{ - // var channel = (ITextChannel)msg.Channel; + // var channel = (ITextChannel)Context.Channel; // //eventName = eventName?.Replace(" ","").ToLowerInvariant(); // switch (eventName.ToLowerInvariant()) @@ -669,9 +669,9 @@ namespace NadekoBot.Modules.Administration //[LocalizedCommand, LocalizedDescription, LocalizedSummary, LocalizedAlias] //[RequireContext(ContextType.Guild)] - //public async Task LogRemove(IUserMessage msg, string eventName) + //public async Task LogRemove(string eventName) //{ - // var channel = (ITextChannel)msg.Channel; + // var channel = (ITextChannel)Context.Channel; // eventName = eventName.ToLowerInvariant(); // switch (eventName) @@ -704,10 +704,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] - public async Task UserPresence(IUserMessage imsg) + [RequireUserPermission(GuildPermission.Administrator)] + public async Task UserPresence() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { @@ -727,10 +727,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] - public async Task VoicePresence(IUserMessage imsg) + [RequireUserPermission(GuildPermission.Administrator)] + public async Task VoicePresence() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { @@ -754,7 +754,7 @@ namespace NadekoBot.Modules.Administration //[RequireContext(ContextType.Guild)] //public async Task VoiPresIgnore(IUserMessage imsg, IVoiceChannel voiceChannel) //{ - // var channel = (ITextChannel)imsg.Channel; + // var channel = (ITextChannel)Context.Channel; // int removed; // using (var uow = DbHandler.UnitOfWork()) // { diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 583f0f05..9e0975af 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -81,10 +81,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task RepeatInvoke(IUserMessage imsg) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task RepeatInvoke() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; RepeatRunner rep; if (!repeaters.TryGetValue(channel.Id, out rep)) @@ -98,10 +98,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Repeat(IUserMessage imsg) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Repeat() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; RepeatRunner rep; if (repeaters.TryRemove(channel.Id, out rep)) { @@ -119,10 +119,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] + [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (minutes < 1 || minutes > 10080) return; diff --git a/src/NadekoBot/Modules/Administration/Commands/Migration.cs b/src/NadekoBot/Modules/Administration/Commands/Migration.cs index 7027488a..a16dad79 100644 --- a/src/NadekoBot/Modules/Administration/Commands/Migration.cs +++ b/src/NadekoBot/Modules/Administration/Commands/Migration.cs @@ -34,9 +34,9 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task MigrateData(IUserMessage umsg) + public async Task MigrateData() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var version = 0; using (var uow = DbHandler.UnitOfWork()) @@ -54,12 +54,12 @@ namespace NadekoBot.Modules.Administration break; } } - await umsg.Channel.SendMessageAsync("๐Ÿ†™ **Migration done.**").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("๐Ÿ†™ **Migration done.**").ConfigureAwait(false); } catch (Exception ex) { _log.Error(ex); - await umsg.Channel.SendMessageAsync("โš ๏ธ **Error while migrating, check `logs` for more informations.**").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("โš ๏ธ **Error while migrating, check `logs` for more informations.**").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index b4ce345a..1efe2e90 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -137,11 +137,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(1)] public async Task SetMuteRole(IUserMessage imsg, [Remainder] string name) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; name = name.Trim(); if (string.IsNullOrWhiteSpace(name)) return; @@ -158,18 +158,18 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(0)] public Task SetMuteRole(IUserMessage imsg, [Remainder] IRole role) => SetMuteRole(imsg, role.Name); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - [RequirePermission(GuildPermission.MuteMembers)] + [RequireUserPermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.MuteMembers)] public async Task Mute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -184,11 +184,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - [RequirePermission(GuildPermission.MuteMembers)] + [RequireUserPermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.MuteMembers)] public async Task Unmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -203,10 +203,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] public async Task ChatMute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -222,10 +222,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] public async Task ChatUnmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -241,10 +241,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.MuteMembers)] + [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceMute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -260,10 +260,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.MuteMembers)] + [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceUnmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { await user.ModifyAsync(usr => usr.Mute = false).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index 2d8e7921..15d11e3f 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task RotatePlaying(IUserMessage umsg) + public async Task RotatePlaying() { using (var uow = DbHandler.UnitOfWork()) { @@ -98,9 +98,9 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } if (RotatingStatuses) - await umsg.Channel.SendConfirmAsync("๐Ÿ†— **Rotating playing status enabled.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **Rotating playing status enabled.**").ConfigureAwait(false); else - await umsg.Channel.SendConfirmAsync("โ„น๏ธ **Rotating playing status disabled.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ **Rotating playing status disabled.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -116,19 +116,19 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } - await umsg.Channel.SendConfirmAsync("โœ… **Added.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **Added.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task ListPlaying(IUserMessage umsg) + public async Task ListPlaying() { if (!RotatingStatusMessages.Any()) - await umsg.Channel.SendErrorAsync("โŽ **No rotating playing statuses set.**"); + await Context.Channel.SendErrorAsync("โŽ **No rotating playing statuses set.**"); else { var i = 1; - await umsg.Channel.SendConfirmAsync($"โ„น๏ธ {umsg.Author.Mention} `Here is a list of rotating statuses:`\n\n\t" + string.Join("\n\t", RotatingStatusMessages.Select(rs => $"`{i++}.` {rs.Status}"))); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ {Context.User.Mention} `Here is a list of rotating statuses:`\n\n\t" + string.Join("\n\t", RotatingStatusMessages.Select(rs => $"`{i++}.` {rs.Status}"))); } } @@ -151,7 +151,7 @@ namespace NadekoBot.Modules.Administration RotatingStatusMessages.RemoveAt(index); await uow.CompleteAsync(); } - await umsg.Channel.SendConfirmAsync($"๐Ÿ—‘ **Removed the the playing message:** {msg}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ **Removed the the playing message:** {msg}").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index d4e74299..610b3bb7 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Administration var t = Task.Run(async () => { var usrMsg = umsg as IUserMessage; - var channel = usrMsg.Channel as ITextChannel; + var channel = usrContext.Channel as ITextChannel; if (channel == null || usrMsg.IsAuthor()) return; @@ -76,7 +76,7 @@ namespace NadekoBot.Modules.Administration if (!RatelimitingChannels.TryGetValue(channel.Id, out limiter)) return; - if (limiter.CheckUserRatelimit(usrMsg.Author.Id)) + if (limiter.CheckUserRatelimit(usrContext.User.Id)) try { await usrMsg.DeleteAsync(); } catch (Exception ex) { _log.Warn(ex); } }); return Task.CompletedTask; @@ -85,10 +85,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Slowmode(IUserMessage umsg) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Slowmode() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; Ratelimiter throwaway; if (RatelimitingChannels.TryRemove(channel.Id, out throwaway)) @@ -101,11 +101,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] + [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Slowmode(IUserMessage umsg, int msg, int perSec) { await Slowmode(umsg).ConfigureAwait(false); // disable if exists - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (msg < 1 || perSec < 1 || msg > 100 || perSec > 3600) { diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs index dfd8b0a7..e05a7a09 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -21,10 +21,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task AdSarm(IUserMessage imsg) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task AdSarm() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool newval; using (var uow = DbHandler.UnitOfWork()) { @@ -39,10 +39,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] public async Task Asar(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; IEnumerable roles; @@ -70,10 +70,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageRoles)] public async Task Rsar(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; bool success; using (var uow = DbHandler.UnitOfWork()) @@ -91,9 +91,9 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Lsar(IUserMessage umsg) + public async Task Lsar() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var toRemove = new ConcurrentHashSet(); var removeMsg = new StringBuilder(); @@ -128,10 +128,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task Tesar(IUserMessage umsg) + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task Tesar() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; bool areExclusive; using (var uow = DbHandler.UnitOfWork()) @@ -149,8 +149,8 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] public async Task Iam(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; - var guildUser = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + var guildUser = (IGuildUser)Context.User; var usrMsg = (IUserMessage)umsg; GuildConfig conf; @@ -208,8 +208,8 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] public async Task Iamnot(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; - var guildUser = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + var guildUser = (IGuildUser)Context.User; bool autoDeleteSelfAssignedRoleMessages; IEnumerable roles; diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index b750a26c..9b888321 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task Leave(IUserMessage umsg, [Remainder] string guildStr) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; guildStr = guildStr.Trim().ToUpperInvariant(); var server = _client.GetGuilds().FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == guildStr) ?? @@ -35,7 +35,7 @@ namespace NadekoBot.Modules.Administration await channel.SendErrorAsync("โš ๏ธ Cannot find that server").ConfigureAwait(false); return; } - if (server.OwnerId != _client.GetCurrentUser().Id) + if (server.OwnerId != _client.CurrentUser().Id) { await server.LeaveAsync().ConfigureAwait(false); await channel.SendConfirmAsync("โœ… Left server " + server.Name).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index 1a42e613..96dcf125 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -124,10 +124,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDel(IUserMessage umsg, int timer = 30) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (timer < 0 || timer > 600) return; @@ -155,10 +155,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] - public async Task Greet(IUserMessage umsg) + [RequireUserPermission(GuildPermission.ManageGuild)] + public async Task Greet() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var enabled = await ServerGreetCommands.SetGreet(channel.Guild.Id, channel.Id).ConfigureAwait(false); @@ -184,10 +184,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { @@ -228,10 +228,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] - public async Task GreetDm(IUserMessage umsg) + [RequireUserPermission(GuildPermission.ManageGuild)] + public async Task GreetDm() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var enabled = await ServerGreetCommands.SetGreetDm(channel.Guild.Id).ConfigureAwait(false); @@ -256,10 +256,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDmMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { @@ -300,10 +300,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] - public async Task Bye(IUserMessage umsg) + [RequireUserPermission(GuildPermission.ManageGuild)] + public async Task Bye() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var enabled = await ServerGreetCommands.SetBye(channel.Guild.Id, channel.Id).ConfigureAwait(false); @@ -329,10 +329,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task ByeMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { @@ -373,10 +373,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageGuild)] + [RequireUserPermission(GuildPermission.ManageGuild)] public async Task ByeDel(IUserMessage umsg, int timer = 30) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await ServerGreetCommands.SetByeDel(channel.Guild.Id, timer).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 4ffff33a..0abb0527 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -106,11 +106,11 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageRoles)] - [RequirePermission(GuildPermission.ManageChannels)] - public async Task VoicePlusText(IUserMessage msg) + [RequireUserPermission(GuildPermission.ManageRoles)] + [RequireUserPermission(GuildPermission.ManageChannels)] + public async Task VoicePlusText() { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var guild = channel.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); @@ -159,11 +159,11 @@ namespace NadekoBot.Modules.Administration } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageChannels)] - [RequirePermission(GuildPermission.ManageRoles)] - public async Task CleanVPlusT(IUserMessage msg) + [RequireUserPermission(GuildPermission.ManageChannels)] + [RequireUserPermission(GuildPermission.ManageRoles)] + public async Task CleanVPlusT() { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var guild = channel.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); if (!botUser.GuildPermissions.Administrator) diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 81be7144..253e751e 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -59,9 +59,9 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task CreateWar(IUserMessage umsg, int size, [Remainder] string enemyClan = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; - if (!(umsg.Author as IGuildUser).GuildPermissions.ManageChannels) + if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) return; if (string.IsNullOrWhiteSpace(enemyClan)) @@ -81,7 +81,7 @@ namespace NadekoBot.Modules.ClashOfClans } - var cw = await CreateWar(enemyClan, size, channel.Guild.Id, umsg.Channel.Id); + var cw = await CreateWar(enemyClan, size, channel.Guild.Id, Context.Channel.Id); wars.Add(cw); await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); @@ -91,7 +91,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task StartWar(IUserMessage umsg, [Remainder] string number = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; int num = 0; int.TryParse(number, out num); @@ -119,7 +119,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ListWar(IUserMessage umsg, [Remainder] string number = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; // if number is null, print all wars in a short way if (string.IsNullOrWhiteSpace(number)) @@ -162,7 +162,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task Claim(IUserMessage umsg, int number, int baseNumber, [Remainder] string other_name = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { @@ -171,7 +171,7 @@ namespace NadekoBot.Modules.ClashOfClans } var usr = string.IsNullOrWhiteSpace(other_name) ? - umsg.Author.Username : + Context.User.Username : other_name; try { @@ -190,7 +190,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish1(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1, 1); } @@ -198,7 +198,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish2(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1, 2); } @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1); } @@ -214,7 +214,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task EndWar(IUserMessage umsg, int number) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg,number); if (warsInfo == null) @@ -235,7 +235,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task Unclaim(IUserMessage umsg, int number, [Remainder] string otherName = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg, number); if (warsInfo == null || warsInfo.Item1.Count == 0) @@ -245,7 +245,7 @@ namespace NadekoBot.Modules.ClashOfClans } var usr = string.IsNullOrWhiteSpace(otherName) ? - umsg.Author.Username : + Context.User.Username : otherName; try { @@ -262,7 +262,7 @@ namespace NadekoBot.Modules.ClashOfClans private async Task FinishClaim(IUserMessage umsg, int number, int baseNumber, int stars = 3) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var warInfo = GetWarInfo(umsg, number); if (warInfo == null || warInfo.Item1.Count == 0) { @@ -274,14 +274,14 @@ namespace NadekoBot.Modules.ClashOfClans { if (baseNumber == -1) { - baseNumber = war.FinishClaim(umsg.Author.Username, stars); + baseNumber = war.FinishClaim(Context.User.Username, stars); SaveWar(war); } else { war.FinishClaim(baseNumber, stars); } - await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ{umsg.Author.Mention} **DESTROYED** a base #{baseNumber + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); + await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ{Context.User.Mention} **DESTROYED** a base #{baseNumber + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); } catch (Exception ex) { @@ -291,7 +291,7 @@ namespace NadekoBot.Modules.ClashOfClans private static Tuple, int> GetWarInfo(IUserMessage umsg, int num) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; //check if there are any wars List wars = null; ClashWars.TryGetValue(channel.Guild.Id, out wars); diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index d7c28f91..71bb62bc 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -33,9 +33,9 @@ namespace NadekoBot.Modules.CustomReactions public void ClearStats() => ReactionStats.Clear(); - public static async Task TryExecuteCustomReaction(IUserMessage umsg) + public static async Task TryExecuteCustomReaction() { - var channel = umsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (channel == null) return false; @@ -78,15 +78,15 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task AddCustReact(IUserMessage imsg, string key, [Remainder] string message) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(key)) return; key = key.ToLowerInvariant(); - if ((channel == null && !NadekoBot.Credentials.IsOwner(imsg.Author)) || (channel != null && !((IGuildUser)imsg.Author).GuildPermissions.Administrator)) + if ((channel == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { - try { await imsg.Channel.SendErrorAsync("Insufficient permissions. Requires Bot ownership for global custom reactions, and Administrator for guild custom reactions."); } catch { } + try { await Context.Channel.SendErrorAsync("Insufficient permissions. Requires Bot ownership for global custom reactions, and Administrator for guild custom reactions."); } catch { } return; } @@ -115,19 +115,19 @@ namespace NadekoBot.Modules.CustomReactions reactions.Add(cr); } - await imsg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle("New Custom Reaction") .WithDescription($"#{cr.Id}") .AddField(efb => efb.WithName("Trigger").WithValue(key)) .AddField(efb => efb.WithName("Response").WithValue(message)) - .Build()).ConfigureAwait(false); + ).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task ListCustReact(IUserMessage imsg, int page = 1) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (page < 1 || page > 1000) return; @@ -138,9 +138,9 @@ namespace NadekoBot.Modules.CustomReactions customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) - await imsg.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); else - await imsg.Channel.SendConfirmAsync( + await Context.Channel.SendConfirmAsync( $"Page {page} of custom reactions:", string.Join("\n", customReactions.OrderBy(cr => cr.Trigger) .Skip((page - 1) * 20) @@ -158,7 +158,7 @@ namespace NadekoBot.Modules.CustomReactions [Priority(1)] public async Task ListCustReact(IUserMessage imsg, All x) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; ConcurrentHashSet customReactions; if (channel == null) @@ -167,7 +167,7 @@ namespace NadekoBot.Modules.CustomReactions customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) - await imsg.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); else { var txtStream = await customReactions.GroupBy(cr => cr.Trigger) @@ -177,16 +177,16 @@ namespace NadekoBot.Modules.CustomReactions .ToStream() .ConfigureAwait(false); if (channel == null) // its a private one, just send back - await imsg.Channel.SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); + await Context.Channel.SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); else - await ((IGuildUser)imsg.Author).SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); + await ((IGuildUser)Context.User).SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task ListCustReactG(IUserMessage imsg, int page = 1) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (page < 1 || page > 10000) return; ConcurrentHashSet customReactions; @@ -196,9 +196,9 @@ namespace NadekoBot.Modules.CustomReactions customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) - await imsg.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); else - await imsg.Channel.SendConfirmAsync($"Page {page} of custom reactions (grouped):", + await Context.Channel.SendConfirmAsync($"Page {page} of custom reactions (grouped):", string.Join("\r\n", customReactions .GroupBy(cr => cr.Trigger) .OrderBy(cr => cr.Key) @@ -211,7 +211,7 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task ShowCustReact(IUserMessage imsg, int id) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; ConcurrentHashSet customReactions; if (channel == null) @@ -222,25 +222,25 @@ namespace NadekoBot.Modules.CustomReactions var found = customReactions.FirstOrDefault(cr => cr.Id == id); if (found == null) - await imsg.Channel.SendErrorAsync("No custom reaction found with that id.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No custom reaction found with that id.").ConfigureAwait(false); else { - await imsg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithDescription($"#{id}") .AddField(efb => efb.WithName("Trigger").WithValue(found.Trigger)) .AddField(efb => efb.WithName("Response").WithValue(found.Response + "\n```css\n" + found.Response + "```")) - .Build()).ConfigureAwait(false); + ).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] public async Task DelCustReact(IUserMessage imsg, int id) { - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; - if ((channel == null && !NadekoBot.Credentials.IsOwner(imsg.Author)) || (channel != null && !((IGuildUser)imsg.Author).GuildPermissions.Administrator)) + if ((channel == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { - try { await imsg.Channel.SendErrorAsync("Insufficient permissions. Requires Bot ownership for global custom reactions, and Administrator for guild custom reactions."); } catch { } + try { await Context.Channel.SendErrorAsync("Insufficient permissions. Requires Bot ownership for global custom reactions, and Administrator for guild custom reactions."); } catch { } return; } @@ -269,9 +269,9 @@ namespace NadekoBot.Modules.CustomReactions } if (success) - await imsg.Channel.SendConfirmAsync("Deleted custom reaction", toDelete.ToString()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Deleted custom reaction", toDelete.ToString()).ConfigureAwait(false); else - await imsg.Channel.SendErrorAsync("Failed to find that custom reaction.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed to find that custom reaction.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -280,18 +280,18 @@ namespace NadekoBot.Modules.CustomReactions if (string.IsNullOrWhiteSpace(trigger)) { ClearStats(); - await imsg.Channel.SendConfirmAsync($"Custom reaction stats cleared.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Custom reaction stats cleared.").ConfigureAwait(false); } else { uint throwaway; if (ReactionStats.TryRemove(trigger, out throwaway)) { - await imsg.Channel.SendConfirmAsync($"Stats cleared for `{trigger}` custom reaction.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Stats cleared for `{trigger}` custom reaction.").ConfigureAwait(false); } else { - await imsg.Channel.SendErrorAsync("No stats for that trigger found, no action taken.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No stats for that trigger found, no action taken.").ConfigureAwait(false); } } } @@ -301,12 +301,12 @@ namespace NadekoBot.Modules.CustomReactions { if (page < 1) return; - await imsg.Channel.EmbedAsync(ReactionStats.OrderByDescending(x => x.Value) + await Context.Channel.EmbedAsync(ReactionStats.OrderByDescending(x => x.Value) .Skip((page - 1)*9) .Take(9) .Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor).WithTitle($"Custom Reaction stats page #{page}"), (agg, cur) => agg.AddField(efb => efb.WithName(cur.Key).WithValue(cur.Value.ToString()).WithIsInline(true))) - .Build()) + ) .ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/CustomReactions/Extensions.cs b/src/NadekoBot/Modules/CustomReactions/Extensions.cs index 49b2909f..c6fe16c7 100644 --- a/src/NadekoBot/Modules/CustomReactions/Extensions.cs +++ b/src/NadekoBot/Modules/CustomReactions/Extensions.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.CustomReactions public static Dictionary> placeholders = new Dictionary>() { - {"%mention%", (ctx) => { return $"<@{NadekoBot.Client.GetCurrentUser().Id}>"; } }, + {"%mention%", (ctx) => { return $"<@{NadekoBot.Client.CurrentUser().Id}>"; } }, {"%user%", (ctx) => { return ctx.Author.Mention; } }, {"%rnduser%", (ctx) => { var ch = ctx.Channel as ITextChannel; diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index c5b129dc..cd72023d 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -4,7 +4,7 @@ using NLog; namespace NadekoBot.Modules { - public class DiscordModule + public class DiscordModule : ModuleBase { protected Logger _log { get; } protected string _prefix { get; } diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index d462d572..926903f8 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -22,9 +22,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Race(IUserMessage umsg) + public async Task Race() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var ar = new AnimalRace(channel.Guild.Id, channel); @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task JoinRace(IUserMessage umsg, int amount = 0) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (amount < 0) amount = 0; @@ -48,7 +48,7 @@ namespace NadekoBot.Modules.Gambling await channel.SendErrorAsync("No race exists on this server"); return; } - await ar.JoinRace(umsg.Author as IGuildUser, amount); + await ar.JoinRace(Context.User as IGuildUser, amount); } public class AnimalRace @@ -199,7 +199,7 @@ namespace NadekoBot.Modules.Gambling var msg = imsg as IUserMessage; if (msg == null) return Task.CompletedTask; - if (msg.IsAuthor() || !(imsg.Channel is ITextChannel) || imsg.Channel != raceChannel) + if (msg.IsAuthor() || !(Context.Channel is ITextChannel) || Context.Channel != raceChannel) return Task.CompletedTask; messagesSinceGameStarted++; return Task.CompletedTask; diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index 22d58035..06571677 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -22,9 +22,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Roll(IUserMessage umsg) + public async Task Roll() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; var rng = new NadekoRandom(); @@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling catch { return new MemoryStream(); } }); - await channel.SendFileAsync(imageStream, "dice.png", $"{umsg.Author.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); + await channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } //todo merge into internallDndRoll and internalRoll [NadekoCommand, Usage, Description, Aliases] @@ -52,7 +52,7 @@ namespace NadekoBot.Modules.Gambling [Priority(1)] public async Task Roll(IUserMessage umsg, string arg) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; - await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Gambling [Priority(0)] public async Task Roll(IUserMessage umsg, int num) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -134,14 +134,14 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, string arg) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -167,7 +167,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; - await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } @@ -176,7 +176,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, int num) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -222,14 +222,14 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task NRoll(IUserMessage umsg, [Remainder] string range) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -249,7 +249,7 @@ namespace NadekoBot.Modules.Gambling rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } - await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled **{rolled}**.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index 58785882..53571526 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -31,9 +31,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Draw(IUserMessage msg, int num = 1) + public async Task Draw(int num = 1) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var cards = AllDecks.GetOrAdd(channel.Guild, (s) => new Cards()); var images = new List(); var cardObjects = new List(); @@ -54,7 +54,7 @@ namespace NadekoBot.Modules.Gambling images.Merge().SaveAsPng(bitmapStream); bitmapStream.Position = 0; //todo CARD NAMES? - var toSend = $"{msg.Author.Mention}"; + var toSend = $"{Context.User.Mention}"; if (cardObjects.Count == 5) toSend += $" drew `{Cards.GetHandValue(cardObjects)}`"; @@ -63,9 +63,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ShuffleDeck(IUserMessage imsg) + public async Task ShuffleDeck() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; AllDecks.AddOrUpdate(channel.Guild, (g) => new Cards(), diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 867db68e..66fb228e 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -23,13 +23,13 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Flip(IUserMessage imsg, int count = 1) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (count == 1) { if (rng.Next(0, 2) == 1) - await channel.SendFileAsync(headsPath, $"{imsg.Author.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false); + await channel.SendFileAsync(headsPath, $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false); else - await channel.SendFileAsync(tailsPath, $"{imsg.Author.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false); + await channel.SendFileAsync(tailsPath, $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false); return; } if (count > 10 || count < 1) @@ -51,8 +51,8 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Betflip(IUserMessage umsg, int amount, string guess) { - var channel = (ITextChannel)umsg.Channel; - var guildUser = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + var guildUser = (IGuildUser)Context.User; var guessStr = guess.Trim().ToUpperInvariant(); if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS") return; @@ -67,12 +67,12 @@ namespace NadekoBot.Modules.Gambling long userFlowers; using (var uow = DbHandler.UnitOfWork()) { - userFlowers = uow.Currency.GetOrCreate(umsg.Author.Id).Amount; + userFlowers = uow.Currency.GetOrCreate(Context.User.Id).Amount; } if (userFlowers < amount) { - await channel.SendErrorAsync($"{umsg.Author.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); return; } @@ -97,12 +97,12 @@ namespace NadekoBot.Modules.Gambling if (isHeads == result) { var toWin = (int)Math.Round(amount * 1.8); - str = $"{umsg.Author.Mention}`You guessed it!` You won {toWin}{Gambling.CurrencySign}"; - await CurrencyHandler.AddCurrencyAsync((IGuildUser)umsg.Author, "Betflip Gamble", toWin, false).ConfigureAwait(false); + str = $"{Context.User.Mention}`You guessed it!` You won {toWin}{Gambling.CurrencySign}"; + await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false); } else { - str = $"{umsg.Author.Mention}`Better luck next time.`"; + str = $"{Context.User.Mention}`Better luck next time.`"; } await channel.SendFileAsync(imgPathToSend, str).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index efd0f1fa..066d4fd1 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Raffle(IUserMessage umsg, [Remainder] IRole role = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; role = role ?? channel.Guild.EveryoneRole; @@ -58,9 +58,9 @@ namespace NadekoBot.Modules.Gambling [Priority(0)] public async Task Cash(IUserMessage umsg, [Remainder] IUser user = null) { - var channel = umsg.Channel; + var channel = Context.Channel; - user = user ?? umsg.Author; + user = user ?? Context.User; await channel.SendConfirmAsync($"{user.Username} has {GetCurrency(user.Id)} {CurrencySign}").ConfigureAwait(false); } @@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Gambling [Priority(1)] public async Task Cash(IUserMessage umsg, ulong userId) { - var channel = umsg.Channel; + var channel = Context.Channel; await channel.SendConfirmAsync($"`{userId}` has {GetCurrency(userId)} {CurrencySign}").ConfigureAwait(false); } @@ -78,17 +78,17 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Give(IUserMessage umsg, long amount, [Remainder] IGuildUser receiver) { - var channel = (ITextChannel)umsg.Channel; - if (amount <= 0 || umsg.Author.Id == receiver.Id) + var channel = (ITextChannel)Context.Channel; + if (amount <= 0 || Context.User.Id == receiver.Id) return; - var success = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)umsg.Author, $"Gift to {receiver.Username} ({receiver.Id}).", amount, true).ConfigureAwait(false); + var success = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, $"Gift to {receiver.Username} ({receiver.Id}).", amount, true).ConfigureAwait(false); if (!success) { - await channel.SendErrorAsync($"{umsg.Author.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); return; } - await CurrencyHandler.AddCurrencyAsync(receiver, $"Gift from {umsg.Author.Username} ({umsg.Author.Id}).", amount, true).ConfigureAwait(false); - await channel.SendConfirmAsync($"{umsg.Author.Mention} successfully sent {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to {receiver.Mention}!").ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(receiver, $"Gift from {Context.User.Username} ({Context.User.Id}).", amount, true).ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} successfully sent {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to {receiver.Mention}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -104,14 +104,14 @@ namespace NadekoBot.Modules.Gambling [Priority(1)] public async Task Award(IUserMessage umsg, int amount, ulong usrId) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; - await CurrencyHandler.AddCurrencyAsync(usrId, $"Awarded by bot owner. ({umsg.Author.Username}/{umsg.Author.Id})", amount).ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(usrId, $"Awarded by bot owner. ({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false); - await channel.SendConfirmAsync($"{umsg.Author.Mention} successfully awarded {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to <@{usrId}>!").ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} successfully awarded {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to <@{usrId}>!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -120,12 +120,12 @@ namespace NadekoBot.Modules.Gambling [Priority(0)] public async Task Award(IUserMessage umsg, int amount, [Remainder] IRole role) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var users = channel.Guild.GetUsers() .Where(u => u.Roles.Contains(role)) .ToList(); await Task.WhenAll(users.Select(u => CurrencyHandler.AddCurrencyAsync(u.Id, - $"Awarded by bot owner to **{role.Name}** role. ({umsg.Author.Username}/{umsg.Author.Id})", + $"Awarded by bot owner to **{role.Name}** role. ({Context.User.Username}/{Context.User.Id})", amount))) .ConfigureAwait(false); @@ -139,14 +139,14 @@ namespace NadekoBot.Modules.Gambling [OwnerOnly] public async Task Take(IUserMessage umsg, long amount, [Remainder] IGuildUser user) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; - if(await CurrencyHandler.RemoveCurrencyAsync(user, $"Taken by bot owner.({umsg.Author.Username}/{umsg.Author.Id})", amount, true).ConfigureAwait(false)) - await channel.SendConfirmAsync($"{umsg.Author.Mention} successfully took {amount} {(amount == 1? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); + if(await CurrencyHandler.RemoveCurrencyAsync(user, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount, true).ConfigureAwait(false)) + await channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); else - await channel.SendErrorAsync($"{umsg.Author.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user} because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user} because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } @@ -155,31 +155,31 @@ namespace NadekoBot.Modules.Gambling [OwnerOnly] public async Task Take(IUserMessage umsg, long amount, [Remainder] ulong usrId) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; - if(await CurrencyHandler.RemoveCurrencyAsync(usrId, $"Taken by bot owner.({umsg.Author.Username}/{umsg.Author.Id})", amount).ConfigureAwait(false)) - await channel.SendConfirmAsync($"{umsg.Author.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from <@{usrId}>!").ConfigureAwait(false); + if(await CurrencyHandler.RemoveCurrencyAsync(usrId, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false)) + await channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from <@{usrId}>!").ConfigureAwait(false); else - await channel.SendErrorAsync($"{umsg.Author.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from `{usrId}` because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from `{usrId}` because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task BetRoll(IUserMessage umsg, long amount) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (amount < 1) return; - var guildUser = (IGuildUser)umsg.Author; + var guildUser = (IGuildUser)Context.User; long userFlowers; using (var uow = DbHandler.UnitOfWork()) { - userFlowers = uow.Currency.GetOrCreate(umsg.Author.Id).Amount; + userFlowers = uow.Currency.GetOrCreate(Context.User.Id).Amount; } if (userFlowers < amount) @@ -217,9 +217,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Leaderboard(IUserMessage umsg) + public async Task Leaderboard() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; IEnumerable richest = new List(); using (var uow = DbHandler.UnitOfWork()) diff --git a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs index f3b148cd..5062b251 100644 --- a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs @@ -41,8 +41,8 @@ namespace NadekoBot.Modules.Games } } - public static async Task TryAsk(IUserMessage msg) { - var channel = msg.Channel as ITextChannel; + public static async Task TryAsk() { + var channel = Context.Channel as ITextChannel; if (channel == null) return false; @@ -51,7 +51,7 @@ namespace NadekoBot.Modules.Games if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out cleverbot)) return false; - var nadekoId = NadekoBot.Client.GetCurrentUser().Id; + var nadekoId = NadekoBot.Client.CurrentUser().Id; var normalMention = $"<@{nadekoId}> "; var nickMention = $"<@!{nadekoId}> "; string message; @@ -68,26 +68,26 @@ namespace NadekoBot.Modules.Games return false; } - await msg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); var response = await cleverbot.Think(message).ConfigureAwait(false); try { - await msg.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); } catch { - await msg.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); // try twice :\ + await Context.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); // try twice :\ } return true; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(ChannelPermission.ManageMessages)] - public async Task Cleverbot(IUserMessage imsg) + [RequireUserPermission(ChannelPermission.ManageMessages)] + public async Task Cleverbot() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; ChatterBotSession throwaway; if (CleverbotGuilds.TryRemove(channel.Guild.Id, out throwaway)) @@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Games uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, false); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{imsg.Author.Mention} Disabled cleverbot on this server.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} Disabled cleverbot on this server.").ConfigureAwait(false); return; } @@ -112,7 +112,7 @@ namespace NadekoBot.Modules.Games await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{imsg.Author.Mention} Enabled cleverbot on this server.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} Enabled cleverbot on this server.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index 575e8edf..4e8c699e 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -118,14 +118,14 @@ namespace NadekoBot.Modules.Games.Commands.Hangman .AddField(efb => efb.WithName("It was").WithValue(Term.Word)) .WithImage(eib => eib.WithUrl(Term.ImageUrl)); if (Errors >= MaxErrors) - await GameChannel.EmbedAsync(embed.WithColor(NadekoBot.ErrorColor).Build()).ConfigureAwait(false); + await GameChannel.EmbedAsync(embed.WithColor(NadekoBot.ErrorColor)).ConfigureAwait(false); else - await GameChannel.EmbedAsync(embed.WithColor(NadekoBot.OkColor).Build()).ConfigureAwait(false); + await GameChannel.EmbedAsync(embed.WithColor(NadekoBot.OkColor)).ConfigureAwait(false); } private Task PotentialGuess(IMessage msg) { - if (msg.Channel != GameChannel) + if (Context.Channel != GameChannel) return Task.CompletedTask; // message's channel has to be the same as game's if (msg.Content.Length != 1) // message must be 1 char long { @@ -155,7 +155,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman { ++Errors; if (Errors < MaxErrors) - await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author.Mention} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); + await GameChannel.SendErrorAsync("Hangman Game", $"{Context.User.Mention} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); else await End().ConfigureAwait(false); return; @@ -167,19 +167,19 @@ namespace NadekoBot.Modules.Games.Commands.Hangman { if (GuessedAll) { - try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author.Mention} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { } + try { await GameChannel.SendConfirmAsync("Hangman Game", $"{Context.User.Mention} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { } await End().ConfigureAwait(false); return; } - try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author.Mention} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); } catch { } + try { await GameChannel.SendConfirmAsync("Hangman Game", $"{Context.User.Mention} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); } catch { } } else { ++Errors; if (Errors < MaxErrors) - await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author.Mention} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); + await GameChannel.SendErrorAsync("Hangman Game", $"{Context.User.Mention} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); else await End().ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs index b3041d31..388e5a4d 100644 --- a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs @@ -36,19 +36,19 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - public async Task Hangmanlist(IUserMessage imsg) + public async Task Hangmanlist() { - await imsg.Channel.SendConfirmAsync(typesStr); + await Context.Channel.SendConfirmAsync(typesStr); } [NadekoCommand, Usage, Description, Aliases] public async Task Hangman(IUserMessage imsg, HangmanTermPool.HangmanTermType type = HangmanTermPool.HangmanTermType.All) { - var hm = new HangmanGame(imsg.Channel, type); + var hm = new HangmanGame(Context.Channel, type); - if (!HangmanGames.TryAdd(imsg.Channel.Id, hm)) + if (!HangmanGames.TryAdd(Context.Channel.Id, hm)) { - await imsg.Channel.SendErrorAsync("Hangman game already running on this channel.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Hangman game already running on this channel.").ConfigureAwait(false); return; } @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Games }; hm.Start(); - await imsg.Channel.SendConfirmAsync("Hangman game started", hm.ScrambledWord + "\n" + hm.GetHangman() + "\n" + hm.ScrambledWord); + await Context.Channel.SendConfirmAsync("Hangman game started", hm.ScrambledWord + "\n" + hm.GetHangman() + "\n" + hm.ScrambledWord); } } } diff --git a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs index f877ebe7..d883a3d5 100644 --- a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Leet(IUserMessage umsg, int level, [Remainder] string text = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; text = text.Trim(); if (string.IsNullOrWhiteSpace(text)) diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 61a9a10d..42b6055f 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -60,10 +60,10 @@ namespace NadekoBot.Modules.Games private static Task PotentialFlowerGeneration(IMessage imsg) { var msg = imsg as IUserMessage; - if (msg == null || msg.IsAuthor() || msg.Author.IsBot) + if (msg == null || msg.IsAuthor() || Context.User.IsBot) return Task.CompletedTask; - var channel = imsg.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -99,9 +99,9 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Pick(IUserMessage imsg) + public async Task Pick() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (!channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { @@ -117,8 +117,8 @@ namespace NadekoBot.Modules.Games await Task.WhenAll(msgs.Select(toDelete => toDelete.DeleteAsync())).ConfigureAwait(false); - await CurrencyHandler.AddCurrencyAsync((IGuildUser)imsg.Author, "Picked flower(s).", msgs.Count, false).ConfigureAwait(false); - var msg = await channel.SendConfirmAsync($"**{imsg.Author}** picked {msgs.Count}{Gambling.Gambling.CurrencySign}!").ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, "Picked flower(s).", msgs.Count, false).ConfigureAwait(false); + var msg = await channel.SendConfirmAsync($"**{Context.User}** picked {msgs.Count}{Gambling.Gambling.CurrencySign}!").ConfigureAwait(false); var t = Task.Run(async () => { await Task.Delay(10000).ConfigureAwait(false); @@ -128,11 +128,11 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Plant(IUserMessage imsg) + public async Task Plant() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; - var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)imsg.Author, "Planted a flower.", 1, false).ConfigureAwait(false); + var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, "Planted a flower.", 1, false).ConfigureAwait(false); if (!removed) { await channel.SendErrorAsync($"You don't have any {Gambling.Gambling.CurrencyPluralName}.").ConfigureAwait(false); @@ -143,7 +143,7 @@ namespace NadekoBot.Modules.Games IUserMessage msg; var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(Gambling.Gambling.CurrencyName[0]); - var msgToSend = $"Oh how Nice! **{imsg.Author.Username}** planted {(vowelFirst ? "an" : "a")} {Gambling.Gambling.CurrencyName}. Pick it using {NadekoBot.ModulePrefixes[typeof(Games).Name]}pick"; + var msgToSend = $"Oh how Nice! **{Context.User.Username}** planted {(vowelFirst ? "an" : "a")} {Gambling.Gambling.CurrencyName}. Pick it using {NadekoBot.ModulePrefixes[typeof(Games).Name]}pick"; if (file == null) { msg = await channel.SendConfirmAsync(Gambling.Gambling.CurrencySign).ConfigureAwait(false); @@ -157,10 +157,10 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task GenCurrency(IUserMessage imsg) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task GenCurrency() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index 840abdf1..b5da738e 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -16,22 +16,22 @@ namespace NadekoBot.Modules.Games public static ConcurrentDictionary ActivePolls = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] - [RequirePermission(GuildPermission.ManageMessages)] + [RequireUserPermission(GuildPermission.ManageMessages)] [RequireContext(ContextType.Guild)] public Task Poll(IUserMessage umsg, [Remainder] string arg = null) => InternalStartPoll(umsg, arg, isPublic: false); [NadekoCommand, Usage, Description, Aliases] - [RequirePermission(GuildPermission.ManageMessages)] + [RequireUserPermission(GuildPermission.ManageMessages)] [RequireContext(ContextType.Guild)] public Task PublicPoll(IUserMessage umsg, [Remainder] string arg = null) => InternalStartPoll(umsg, arg, isPublic: true); private async Task InternalStartPoll(IUserMessage umsg, string arg, bool isPublic = false) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; - if (!(umsg.Author as IGuildUser).GuildPermissions.ManageChannels) + if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) return; if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) return; @@ -49,11 +49,11 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - [RequirePermission(GuildPermission.ManageMessages)] + [RequireUserPermission(GuildPermission.ManageMessages)] [RequireContext(ContextType.Guild)] - public async Task Pollend(IUserMessage umsg) + public async Task Pollend() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; Poll poll; ActivePolls.TryRemove(channel.Guild, out poll); @@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Games public Poll(IUserMessage umsg, string question, IEnumerable enumerable, bool isPublic = false) { this.originalMessage = umsg; - this.guild = ((ITextChannel)umsg.Channel).Guild; + this.guild = ((ITextChannel)Context.Channel).Guild; this.question = question; this.answers = enumerable as string[] ?? enumerable.ToArray(); this.isPublic = isPublic; @@ -128,7 +128,7 @@ namespace NadekoBot.Modules.Games { // has to be a user message var msg = imsg as IUserMessage; - if (msg == null || msg.Author.IsBot) + if (msg == null || Context.User.IsBot) return Task.CompletedTask; // has to be an integer @@ -146,32 +146,32 @@ namespace NadekoBot.Modules.Games if (isPublic) { //if public, channel must be the same the poll started in - if (originalMessage.Channel.Id != imsg.Channel.Id) + if (originalMessage.Channel.Id != Context.Channel.Id) return; - ch = imsg.Channel; + ch = Context.Channel; } else { //if private, channel must be dm channel - if ((ch = msg.Channel as IDMChannel) == null) + if ((ch = Context.Channel as IDMChannel) == null) return; // user must be a member of the guild this poll is in var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); - if (!guildUsers.Any(u => u.Id == imsg.Author.Id)) + if (!guildUsers.Any(u => u.Id == Context.User.Id)) return; } //user can vote only once - if (participants.TryAdd(msg.Author.Id, vote)) + if (participants.TryAdd(Context.User.Id, vote)) { if (!isPublic) { - await ch.SendConfirmAsync($"Thanks for voting **{msg.Author.Username}**.").ConfigureAwait(false); + await ch.SendConfirmAsync($"Thanks for voting **{Context.User.Username}**.").ConfigureAwait(false); } else { - var toDelete = await ch.SendConfirmAsync($"{msg.Author.Mention} cast their vote.").ConfigureAwait(false); + var toDelete = await ch.SendConfirmAsync($"{Context.User.Mention} cast their vote.").ConfigureAwait(false); await Task.Delay(5000); await toDelete.DeleteAsync().ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index 8ea17e2c..e2a33802 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -107,7 +107,7 @@ namespace NadekoBot.Modules.Games private Task AnswerReceived(IMessage imsg) { - if (imsg.Author.IsBot) + if (Context.User.IsBot) return Task.CompletedTask; var msg = imsg as IUserMessage; if (msg == null) @@ -122,16 +122,16 @@ namespace NadekoBot.Modules.Games var distance = CurrentSentence.LevenshteinDistance(guess); var decision = Judge(distance, guess.Length); - if (decision && !finishedUserIds.Contains(msg.Author.Id)) + if (decision && !finishedUserIds.Contains(Context.User.Id)) { var wpm = CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60; - finishedUserIds.Add(msg.Author.Id); + finishedUserIds.Add(Context.User.Id); await Extensions.Extensions.EmbedAsync(this.Channel, (Discord.API.Embed)new EmbedBuilder().WithColor((uint)NadekoBot.OkColor) - .WithTitle((string)$"{msg.Author} finished the race!") + .WithTitle((string)$"{Context.User} finished the race!") .AddField(efb => efb.WithName("Place").WithValue($"#{finishedUserIds.Count}").WithIsInline(true)) .AddField(efb => efb.WithName("WPM").WithValue($"{wpm:F2} *[{sw.Elapsed.Seconds.ToString()}sec]*").WithIsInline(true)) .AddField(efb => efb.WithName((string)"Errors").WithValue((string)distance.ToString()).WithIsInline((bool)true)) - .Build()).ConfigureAwait(false); + ).ConfigureAwait(false); if (finishedUserIds.Count % 4 == 0) { await Extensions.Extensions.SendConfirmAsync(this.Channel, (string)$":exclamation: A lot of people finished, here is the text for those still typing:\n\n**{Format.Sanitize((string)CurrentSentence.Replace((string)" ", (string)" \x200B")).SanitizeMentions()}**").ConfigureAwait(false); @@ -168,9 +168,9 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task TypeStart(IUserMessage msg) + public async Task TypeStart() { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var game = RunningContests.GetOrAdd(channel.Guild.Id, id => new TypingGame(channel)); @@ -189,9 +189,9 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task TypeStop(IUserMessage imsg) + public async Task TypeStop() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; TypingGame game; if (RunningContests.TryRemove(channel.Guild.Id, out game)) { @@ -207,11 +207,11 @@ namespace NadekoBot.Modules.Games [OwnerOnly] public async Task Typeadd(IUserMessage imsg, [Remainder] string text) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; TypingArticles.Add(new TypingArticle { - Title = $"Text added on {DateTime.UtcNow} by {imsg.Author}", + Title = $"Text added on {DateTime.UtcNow} by {Context.User}", Text = text.SanitizeMentions(), }); @@ -224,7 +224,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Typelist(IUserMessage imsg, int page = 1) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (page < 1) return; @@ -233,7 +233,7 @@ namespace NadekoBot.Modules.Games if (!articles.Any()) { - await channel.SendErrorAsync($"{imsg.Author.Mention} `No articles found on that page.`").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} `No articles found on that page.`").ConfigureAwait(false); return; } var i = (page - 1) * 15; @@ -246,7 +246,7 @@ namespace NadekoBot.Modules.Games [OwnerOnly] public async Task Typedel(IUserMessage imsg, int index) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; index -= 1; if (index < 0 || index >= TypingArticles.Count) diff --git a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs index 534c5040..2ecfa08c 100644 --- a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs @@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Games.Trivia await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle("Leaderboard") .WithDescription(GetLeaderboard()) - .Build(), "Trivia game ended.").ConfigureAwait(false); + , "Trivia game ended.").ConfigureAwait(false); } catch { } } @@ -128,7 +128,7 @@ namespace NadekoBot.Modules.Games.Trivia private Task PotentialGuess(IMessage imsg) { - if (imsg.Author.IsBot) + if (Context.User.IsBot) return Task.CompletedTask; var umsg = imsg as IUserMessage; if (umsg == null) @@ -137,11 +137,11 @@ namespace NadekoBot.Modules.Games.Trivia { try { - if (!(umsg.Channel is IGuildChannel && umsg.Channel is ITextChannel)) return; - if ((umsg.Channel as ITextChannel).Guild != guild) return; - if (umsg.Author.Id == NadekoBot.Client.GetCurrentUser().Id) return; + if (!(Context.Channel is IGuildChannel && Context.Channel is ITextChannel)) return; + if ((Context.Channel as ITextChannel).Guild != guild) return; + if (Context.User.Id == NadekoBot.Client.CurrentUser().Id) return; - var guildUser = umsg.Author as IGuildUser; + var guildUser = Context.User as IGuildUser; var guess = false; await _guessLock.WaitAsync().ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs index 25051444..27504087 100644 --- a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Trivia(IUserMessage umsg, params string[] args) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; TriviaGame trivia; if (!RunningTrivias.TryGetValue(channel.Guild.Id, out trivia)) @@ -35,7 +35,7 @@ namespace NadekoBot.Modules.Games }).Where(t => t.Item1).Select(t => t.Item2).FirstOrDefault(); if (number < 0) return; - var triviaGame = new TriviaGame(channel.Guild, (ITextChannel)umsg.Channel, showHints, number == 0 ? 10 : number); + var triviaGame = new TriviaGame(channel.Guild, (ITextChannel)Context.Channel, showHints, number == 0 ? 10 : number); if (RunningTrivias.TryAdd(channel.Guild.Id, triviaGame)) await channel.SendConfirmAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); else @@ -47,9 +47,9 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Tl(IUserMessage umsg) + public async Task Tl() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; TriviaGame trivia; if (RunningTrivias.TryGetValue(channel.Guild.Id, out trivia)) @@ -60,9 +60,9 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Tq(IUserMessage umsg) + public async Task Tq() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; TriviaGame trivia; if (RunningTrivias.TryGetValue(channel.Guild.Id, out trivia)) diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 592881d1..bdf96a88 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Choose(IUserMessage umsg, [Remainder] string list = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(list)) return; var listArr = list.Split(';'); @@ -43,7 +43,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task _8Ball(IUserMessage umsg, [Remainder] string question = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(question)) return; @@ -52,14 +52,14 @@ namespace NadekoBot.Modules.Games await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .AddField(efb => efb.WithName("โ“ Question").WithValue(question).WithIsInline(false)) .AddField(efb => efb.WithName("๐ŸŽฑ 8Ball").WithValue(_8BallResponses.Shuffle().FirstOrDefault()).WithIsInline(false)) - .Build()); + ); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Rps(IUserMessage umsg, string input) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; Func GetRPSPick = (p) => { @@ -98,9 +98,9 @@ namespace NadekoBot.Modules.Games else if ((pick == 0 && nadekoPick == 1) || (pick == 1 && nadekoPick == 2) || (pick == 2 && nadekoPick == 0)) - msg = $"{NadekoBot.Client.GetCurrentUser().Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}"; + msg = $"{NadekoBot.Client.CurrentUser().Mention} won! {GetRPSPick(nadekoPick)} beats {GetRPSPick(pick)}"; else - msg = $"{umsg.Author.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}"; + msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}"; await channel.SendConfirmAsync(msg).ConfigureAwait(false); } @@ -109,7 +109,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Linux(IUserMessage umsg, string guhnoo, string loonix) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await channel.SendConfirmAsync( $@"I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 2b824111..b2a8b9b0 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -35,17 +35,17 @@ namespace NadekoBot.Modules.Help } [NadekoCommand, Usage, Description, Aliases] - public async Task Modules(IUserMessage umsg) + public async Task Modules() { - 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`") + await Context.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); } [NadekoCommand, Usage, Description, Aliases] public async Task Commands(IUserMessage umsg, [Remainder] string module = null) { - var channel = umsg.Channel; + var channel = Context.Channel; module = module?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(module)) @@ -75,12 +75,12 @@ namespace NadekoBot.Modules.Help [NadekoCommand, Usage, Description, Aliases] public async Task H(IUserMessage umsg, [Remainder] string comToFind = null) { - var channel = umsg.Channel; + var channel = Context.Channel; comToFind = comToFind?.ToLowerInvariant(); if (string.IsNullOrWhiteSpace(comToFind)) { - IMessageChannel ch = channel is ITextChannel ? await ((IGuildUser)umsg.Author).CreateDMChannelAsync() : channel; + IMessageChannel ch = channel is ITextChannel ? await ((IGuildUser)Context.User).CreateDMChannelAsync() : channel; await ch.SendMessageAsync(HelpString).ConfigureAwait(false); return; } @@ -99,18 +99,18 @@ namespace NadekoBot.Modules.Help .AddField(fb => fb.WithIndex(1).WithName(str).WithValue($"{ string.Format(com.Summary, com.Module.Prefix)} { GetCommandRequirements(com)}").WithIsInline(true)) .AddField(fb => fb.WithIndex(2).WithName("**Usage**").WithValue($"{string.Format(com.Remarks, com.Module.Prefix)}").WithIsInline(false)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } private string GetCommandRequirements(Command cmd) { return String.Join(" ", cmd.Source.CustomAttributes - .Where(ca => ca.AttributeType == typeof(OwnerOnlyAttribute) || ca.AttributeType == typeof(RequirePermissionAttribute)) + .Where(ca => ca.AttributeType == typeof(OwnerOnlyAttribute) || ca.AttributeType == typeof(RequireUserPermissionAttribute)) .Select(ca => { if (ca.AttributeType == typeof(OwnerOnlyAttribute)) return "**Bot Owner only.**"; - else if (ca.AttributeType == typeof(RequirePermissionAttribute)) + else if (ca.AttributeType == typeof(RequireUserPermissionAttribute)) return $"**Requires {(GuildPermission)ca.ConstructorArguments.FirstOrDefault().Value} server permission.**".Replace("Guild", "Server"); else return $"**Requires {(GuildPermission)ca.ConstructorArguments.FirstOrDefault().Value} channel permission.**".Replace("Guild", "Server"); @@ -120,7 +120,7 @@ namespace NadekoBot.Modules.Help [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public Task Hgit(IUserMessage umsg) + public Task Hgit() { var helpstr = new StringBuilder(); helpstr.AppendLine("You can support the project on patreon: or paypal: \n"); @@ -145,16 +145,16 @@ namespace NadekoBot.Modules.Help } helpstr.AppendLine($"`{com.Text}` {string.Join(" ", com.Aliases.Skip(1).Select(a=>"`"+a+"`"))} | {string.Format(com.Summary, com.Module.Prefix)} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.Prefix)}"); } - helpstr = helpstr.Replace(NadekoBot.Client.GetCurrentUser().Username , "@BotName"); + helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser().Username , "@BotName"); File.WriteAllText("../../docs/Commands List.md", helpstr.ToString()); return Task.CompletedTask; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Guide(IUserMessage umsg) + public async Task Guide() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await channel.SendConfirmAsync( @"**LIST OF COMMANDS**: @@ -163,9 +163,9 @@ namespace NadekoBot.Modules.Help [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Donate(IUserMessage umsg) + public async Task Donate() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await channel.SendConfirmAsync( $@"You can support the NadekoBot project on patreon. or diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 81e5c95d..d0a4dff5 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -62,14 +62,14 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public Task Next(IUserMessage umsg, int skipCount = 1) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (skipCount < 1) return Task.CompletedTask; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; - if (musicPlayer.PlaybackVoiceChannel == ((IGuildUser)umsg.Author).VoiceChannel) + if (musicPlayer.PlaybackVoiceChannel == ((IGuildUser)Context.User).VoiceChannel) { while (--skipCount > 0) { @@ -82,13 +82,13 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Stop(IUserMessage umsg) + public Task Stop() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; - if (((IGuildUser)umsg.Author).VoiceChannel == musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel == musicPlayer.PlaybackVoiceChannel) { musicPlayer.Autoplay = false; musicPlayer.Stop(); @@ -98,13 +98,13 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Destroy(IUserMessage umsg) + public Task Destroy() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; - if (((IGuildUser)umsg.Author).VoiceChannel == musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel == musicPlayer.PlaybackVoiceChannel) if(MusicPlayers.TryRemove(channel.Guild.Id, out musicPlayer)) musicPlayer.Destroy(); return Task.CompletedTask; @@ -112,13 +112,13 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Pause(IUserMessage umsg) + public Task Pause() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return Task.CompletedTask; musicPlayer.TogglePause(); return Task.CompletedTask; @@ -128,9 +128,9 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Queue(IUserMessage umsg, [Remainder] string query) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, query).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, query).ConfigureAwait(false); if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -142,9 +142,9 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SoundCloudQueue(IUserMessage umsg, [Remainder] string query) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -156,7 +156,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task ListQueue(IUserMessage umsg, int page = 1) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) { @@ -194,9 +194,9 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task NowPlaying(IUserMessage umsg) + public async Task NowPlaying() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) @@ -225,18 +225,18 @@ namespace NadekoBot.Modules.Music { embed.WithThumbnail(tn => tn.Url = $"{currentSong.SongInfo.AlbumArt}"); } - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Volume(IUserMessage umsg, int val) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (val < 0) return; @@ -248,7 +248,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Defvol(IUserMessage umsg, [Remainder] int val) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (val < 0 || val > 100) { @@ -265,13 +265,13 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ShufflePlaylist(IUserMessage umsg) + public async Task ShufflePlaylist() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (musicPlayer.Playlist.Count < 2) { @@ -287,11 +287,11 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Playlist(IUserMessage umsg, [Remainder] string playlist) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = playlist; if (string.IsNullOrWhiteSpace(arg)) return; - if (((IGuildUser)umsg.Author).VoiceChannel?.Guild != channel.Guild) + if (((IGuildUser)Context.User).VoiceChannel?.Guild != channel.Guild) { await channel.SendErrorAsync("๐Ÿ’ข You need to be in a **voice channel** on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); return; @@ -316,7 +316,7 @@ namespace NadekoBot.Modules.Music { try { - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, id, true).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, id, true).ConfigureAwait(false); } catch (SongNotFoundException) { } catch { break; } @@ -328,7 +328,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SoundCloudPl(IUserMessage umsg, [Remainder] string pl) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; pl = pl?.Trim(); if (string.IsNullOrWhiteSpace(pl)) @@ -337,7 +337,7 @@ namespace NadekoBot.Modules.Music using (var http = new HttpClient()) { var scvids = JObject.Parse(await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={pl}&client_id={NadekoBot.Credentials.SoundCloudClientId}").ConfigureAwait(false))["tracks"].ToObject(); - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false); MusicPlayer mp; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out mp)) @@ -354,7 +354,7 @@ namespace NadekoBot.Modules.Music Uri = svideo.StreamLink, ProviderType = MusicType.Normal, Query = svideo.TrackLink, - }), ((IGuildUser)umsg.Author).Username); + }), ((IGuildUser)Context.User).Username); } catch (PlaylistFullException) { break; } } @@ -366,7 +366,7 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task LocalPl(IUserMessage umsg, [Remainder] string directory) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = directory; if (string.IsNullOrWhiteSpace(arg)) return; @@ -379,7 +379,7 @@ namespace NadekoBot.Modules.Music { try { - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false); } catch (PlaylistFullException) { @@ -396,13 +396,13 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Radio(IUserMessage umsg, string radio_link) { - var channel = (ITextChannel)umsg.Channel; - if (((IGuildUser)umsg.Author).VoiceChannel?.Guild != channel.Guild) + var channel = (ITextChannel)Context.Channel; + if (((IGuildUser)Context.User).VoiceChannel?.Guild != channel.Guild) { await channel.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); return; } - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); @@ -415,21 +415,21 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task Local(IUserMessage umsg, [Remainder] string path) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = path; if (string.IsNullOrWhiteSpace(arg)) return; - await QueueSong(((IGuildUser)umsg.Author), channel, ((IGuildUser)umsg.Author).VoiceChannel, path, musicType: MusicType.Local).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, path, musicType: MusicType.Local).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Move(IUserMessage umsg) + public async Task Move() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; - var voiceChannel = ((IGuildUser)umsg.Author).VoiceChannel; + var voiceChannel = ((IGuildUser)Context.User).VoiceChannel; if (voiceChannel == null || voiceChannel.Guild != channel.Guild || !MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; await musicPlayer.MoveToVoiceChannel(voiceChannel); @@ -440,14 +440,14 @@ namespace NadekoBot.Modules.Music [Priority(0)] public async Task Remove(IUserMessage umsg, int num) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) { return; } - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (num <= 0 || num > musicPlayer.Playlist.Count) return; @@ -461,7 +461,7 @@ namespace NadekoBot.Modules.Music [Priority(1)] public async Task Remove(IUserMessage umsg, string all) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (all.Trim().ToUpperInvariant() != "ALL") return; @@ -476,7 +476,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task MoveSong(IUserMessage umsg, [Remainder] string fromto) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) { @@ -510,7 +510,7 @@ namespace NadekoBot.Modules.Music .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); //await channel.SendConfirmAsync($"๐ŸŽตMoved {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); @@ -521,7 +521,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SetMaxQueue(IUserMessage umsg, uint size) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) { @@ -533,9 +533,9 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ReptCurSong(IUserMessage umsg) + public async Task ReptCurSong() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; @@ -551,9 +551,9 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RepeatPl(IUserMessage umsg) + public async Task RepeatPl() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; @@ -565,7 +565,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Save(IUserMessage umsg, [Remainder] string name) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; @@ -586,8 +586,8 @@ namespace NadekoBot.Modules.Music playlist = new MusicPlaylist { Name = name, - Author = umsg.Author.Username, - AuthorId = umsg.Author.Id, + Author = Context.User.Username, + AuthorId = Context.User.Id, Songs = songs, }; uow.MusicPlaylists.Add(playlist); @@ -601,7 +601,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Load(IUserMessage umsg, [Remainder] int id) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlaylist mpl; using (var uow = DbHandler.UnitOfWork()) @@ -618,7 +618,7 @@ namespace NadekoBot.Modules.Music try { msg = await channel.SendMessageAsync($"๐ŸŽถ Attempting to load **{mpl.Songs.Count}** songs...").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } foreach (var item in mpl.Songs) { - var usr = (IGuildUser)umsg.Author; + var usr = (IGuildUser)Context.User; try { await QueueSong(usr, channel, usr.VoiceChannel, item.Query, true, item.ProviderType).ConfigureAwait(false); @@ -634,7 +634,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Playlists(IUserMessage umsg, [Remainder] int num = 1) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (num <= 0) return; @@ -656,7 +656,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task DeletePlaylist(IUserMessage umsg, [Remainder] int id) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; bool success = false; MusicPlaylist pl = null; @@ -668,7 +668,7 @@ namespace NadekoBot.Modules.Music if (pl != null) { - if (NadekoBot.Credentials.IsOwner(umsg.Author) || pl.AuthorId == umsg.Author.Id) + if (NadekoBot.Credentials.IsOwner(Context.User) || pl.AuthorId == Context.User.Id) { uow.MusicPlaylists.Remove(pl); await uow.CompleteAsync().ConfigureAwait(false); @@ -694,12 +694,12 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Goto(IUserMessage umsg, int time) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (time < 0) @@ -731,7 +731,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task GetLink(IUserMessage umsg, int index = 0) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; @@ -764,9 +764,9 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Autoplay(IUserMessage umsg) + public async Task Autoplay() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 0fba9e0e..8b856b1b 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Hentai(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; @@ -60,7 +60,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task HentaiBomb(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; tag = "rating%3Aexplicit+" + tag; @@ -102,7 +102,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Yandere(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetYandereImageLink(tag).ConfigureAwait(false); @@ -116,7 +116,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Danbooru(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetDanbooruImageLink(tag).ConfigureAwait(false); @@ -130,7 +130,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Konachan(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetKonachanImageLink(tag).ConfigureAwait(false); @@ -144,7 +144,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Gelbooru(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetGelbooruImageLink(tag).ConfigureAwait(false); @@ -158,7 +158,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task Rule34(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetRule34ImageLink(tag).ConfigureAwait(false); @@ -172,7 +172,7 @@ namespace NadekoBot.Modules.NSFW [RequireContext(ContextType.Guild)] public async Task E621(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetE621ImageLink(tag).ConfigureAwait(false); @@ -184,18 +184,18 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Cp(IUserMessage umsg) + public async Task Cp() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; await channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Boobs(IUserMessage umsg) + public async Task Boobs() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { JToken obj; @@ -213,9 +213,9 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Butts(IUserMessage umsg) + public async Task Butts() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { diff --git a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs index 2d90a2e7..b4a0932e 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs @@ -60,7 +60,7 @@ namespace NadekoBot.Modules.Permissions private async Task Blacklist(IUserMessage imsg, AddRemove action, ulong id, BlacklistType type) { - var channel = imsg.Channel; + var channel = Context.Channel; using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index c18bf8ed..b9b32b56 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions } [Group] - public class CmdCdsCommands + public class CmdCdsCommands : ModuleBase { public static ConcurrentDictionary> commandCooldowns { get; } private static ConcurrentDictionary> activeCooldowns { get; } = new ConcurrentDictionary>(); @@ -36,9 +36,9 @@ namespace NadekoBot.Modules.Permissions } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CmdCooldown(IUserMessage imsg, Command command, int secs) + public async Task CmdCooldown(IUserMessage imsg, CommandInfo command, int secs) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (secs < 0 || secs > 3600) { await channel.SendErrorAsync("Invalid second parameter. (Must be a number between 0 and 3600)").ConfigureAwait(false); @@ -50,8 +50,8 @@ namespace NadekoBot.Modules.Permissions var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.CommandCooldowns)); var localSet = commandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); - config.CommandCooldowns.RemoveWhere(cc => cc.CommandName == command.Text.ToLowerInvariant()); - localSet.RemoveWhere(cc => cc.CommandName == command.Text.ToLowerInvariant()); + config.CommandCooldowns.RemoveWhere(cc => cc.CommandName == command.Aliases.First().ToLowerInvariant()); + localSet.RemoveWhere(cc => cc.CommandName == command.Aliases.First().ToLowerInvariant()); if (secs != 0) { var cc = new CommandCooldown() @@ -80,9 +80,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AllCmdCooldowns(IUserMessage imsg) + public async Task AllCmdCooldowns() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; var localSet = commandCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (!localSet.Any()) diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index d6f22fb5..cc92b01a 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -62,9 +62,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrFilterInv(IUserMessage imsg) + public async Task SrvrFilterInv() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) @@ -88,9 +88,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlFilterInv(IUserMessage imsg) + public async Task ChnlFilterInv() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) @@ -121,9 +121,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrFilterWords(IUserMessage imsg) + public async Task SrvrFilterWords() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) @@ -147,9 +147,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlFilterWords(IUserMessage imsg) + public async Task ChnlFilterWords() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) @@ -182,7 +182,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task FilterWord(IUserMessage imsg, [Remainder] string word) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; word = word?.Trim().ToLowerInvariant(); @@ -220,9 +220,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task LstFilterWords(IUserMessage imsg) + public async Task LstFilterWords() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; ConcurrentHashSet filteredWords; ServerFilteredWords.TryGetValue(channel.Guild.Id, out filteredWords); diff --git a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs index 8340b2f5..9a1489e7 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs +++ b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs @@ -10,7 +10,7 @@ namespace NadekoBot.Modules.Permissions { public static class PermissionExtensions { - public static bool CheckPermissions(this IEnumerable permsEnumerable, IUserMessage message, Command command) + public static bool CheckPermissions(this IEnumerable permsEnumerable, IUserMessage message, CommandInfo command) { var perms = permsEnumerable as List ?? permsEnumerable.ToList(); int throwaway; @@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Permissions case PrimaryPermissionType.Role: if (guildUser == null) break; - if (guildUser.Roles.Any(r => r.Id == perm.PrimaryTargetId)) + if (guildUser.RoleIds.Contains(perm.PrimaryTargetId)) return perm.State; break; case PrimaryPermissionType.Server: diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index d3de046c..d71a991f 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -46,9 +46,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Verbose(IUserMessage msg, PermissionAction action) + public async Task Verbose(PermissionAction action) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -68,9 +68,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task PermRole(IUserMessage msg, [Remainder] IRole role = null) + public async Task PermRole([Remainder] IRole role = null) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); @@ -96,9 +96,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ListPerms(IUserMessage msg, int page = 1) + public async Task ListPerms(int page = 1) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; if (page < 1 || page > 4) return; @@ -117,7 +117,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task RemovePerm(IUserMessage imsg, int index) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; index -= 1; try { @@ -154,7 +154,7 @@ namespace NadekoBot.Modules.Permissions uow2._context.SaveChanges(); } - await channel.SendConfirmAsync($"โœ… {imsg.Author.Mention} removed permission **{p.GetCommand(channel.Guild)}** from position #{index + 1}.").ConfigureAwait(false); + await channel.SendConfirmAsync($"โœ… {Context.User.Mention} removed permission **{p.GetCommand(channel.Guild)}** from position #{index + 1}.").ConfigureAwait(false); } catch (ArgumentOutOfRangeException) { @@ -168,7 +168,7 @@ namespace NadekoBot.Modules.Permissions { from -= 1; to -= 1; - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; if (!(from == to || from < 0 || to < 0)) { try @@ -274,9 +274,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrCmd(IUserMessage imsg, Command command, PermissionAction action) + public async Task SrvrCmd(IUserMessage imsg, CommandInfo command, PermissionAction action) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -285,7 +285,7 @@ namespace NadekoBot.Modules.Permissions PrimaryTarget = PrimaryPermissionType.Server, PrimaryTargetId = 0, SecondaryTarget = SecondaryPermissionType.Command, - SecondaryTargetName = command.Text.ToLowerInvariant(), + SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); @@ -298,14 +298,14 @@ namespace NadekoBot.Modules.Permissions await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Text}` command on this server.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command on this server.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrMdl(IUserMessage imsg, Module module, PermissionAction action) + public async Task SrvrMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -331,9 +331,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UsrCmd(IUserMessage imsg, Command command, PermissionAction action, [Remainder] IGuildUser user) + public async Task UsrCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] IGuildUser user) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -342,7 +342,7 @@ namespace NadekoBot.Modules.Permissions PrimaryTarget = PrimaryPermissionType.User, PrimaryTargetId = user.Id, SecondaryTarget = SecondaryPermissionType.Command, - SecondaryTargetName = command.Text.ToLowerInvariant(), + SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); @@ -354,14 +354,14 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Text}` command for `{user}` user.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{user}` user.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UsrMdl(IUserMessage imsg, Module module, PermissionAction action, [Remainder] IGuildUser user) + public async Task UsrMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] IGuildUser user) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -387,9 +387,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RoleCmd(IUserMessage imsg, Command command, PermissionAction action, [Remainder] IRole role) + public async Task RoleCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -398,7 +398,7 @@ namespace NadekoBot.Modules.Permissions PrimaryTarget = PrimaryPermissionType.Role, PrimaryTargetId = role.Id, SecondaryTarget = SecondaryPermissionType.Command, - SecondaryTargetName = command.Text.ToLowerInvariant(), + SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); @@ -410,14 +410,14 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Text}` command for `{role}` role.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{role}` role.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RoleMdl(IUserMessage imsg, Module module, PermissionAction action, [Remainder] IRole role) + public async Task RoleMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -443,9 +443,9 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlCmd(IUserMessage imsg, Command command, PermissionAction action, [Remainder] ITextChannel chnl) + public async Task ChnlCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; try { using (var uow = DbHandler.UnitOfWork()) @@ -455,7 +455,7 @@ namespace NadekoBot.Modules.Permissions PrimaryTarget = PrimaryPermissionType.Channel, PrimaryTargetId = chnl.Id, SecondaryTarget = SecondaryPermissionType.Command, - SecondaryTargetName = command.Text.ToLowerInvariant(), + SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); @@ -471,14 +471,14 @@ namespace NadekoBot.Modules.Permissions catch (Exception ex) { _log.Error(ex); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Text}` command for `{chnl}` channel.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{chnl}` channel.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlMdl(IUserMessage imsg, Module module, PermissionAction action, [Remainder] ITextChannel chnl) + public async Task ChnlMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -506,7 +506,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllChnlMdls(IUserMessage imsg, PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -534,7 +534,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllRoleMdls(IUserMessage imsg, PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -562,7 +562,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllUsrMdls(IUserMessage imsg, PermissionAction action, [Remainder] IUser user) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -590,7 +590,7 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task AllSrvrMdls(IUserMessage imsg, PermissionAction action) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -607,7 +607,7 @@ namespace NadekoBot.Modules.Permissions var allowUser = new Permission { PrimaryTarget = PrimaryPermissionType.User, - PrimaryTargetId = imsg.Author.Id, + PrimaryTargetId = Context.User.Id, SecondaryTarget = SecondaryPermissionType.AllModules, SecondaryTargetName = "*", State = true, diff --git a/src/NadekoBot/Modules/Pokemon/Pokemon.cs b/src/NadekoBot/Modules/Pokemon/Pokemon.cs index 31dbf2cb..5000dcb9 100644 --- a/src/NadekoBot/Modules/Pokemon/Pokemon.cs +++ b/src/NadekoBot/Modules/Pokemon/Pokemon.cs @@ -16,7 +16,6 @@ using static NadekoBot.Modules.Gambling.Gambling; namespace NadekoBot.Modules.Pokemon { - [NadekoModule("Pokemon", ">")] public partial class Pokemon : DiscordModule { @@ -99,8 +98,8 @@ namespace NadekoBot.Modules.Pokemon [RequireContext(ContextType.Guild)] public async Task Attack(IUserMessage umsg, string move, IGuildUser targetUser = null) { - var channel = (ITextChannel)umsg.Channel; - IGuildUser user = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + IGuildUser user = (IGuildUser)Context.User; if (string.IsNullOrWhiteSpace(move)) { return; @@ -215,10 +214,10 @@ namespace NadekoBot.Modules.Pokemon [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Movelist(IUserMessage umsg) + public async Task Movelist() { - var channel = (ITextChannel)umsg.Channel; - IGuildUser user = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + IGuildUser user = (IGuildUser)Context.User; var userType = GetPokeType(user.Id); var movesList = userType.Moves; @@ -234,8 +233,8 @@ namespace NadekoBot.Modules.Pokemon [RequireContext(ContextType.Guild)] public async Task Heal(IUserMessage umsg, IGuildUser targetUser = null) { - var channel = (ITextChannel)umsg.Channel; - IGuildUser user = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + IGuildUser user = (IGuildUser)Context.User; if (targetUser == null) { await channel.SendMessageAsync("No such person.").ConfigureAwait(false); @@ -293,8 +292,8 @@ namespace NadekoBot.Modules.Pokemon [RequireContext(ContextType.Guild)] public async Task Type(IUserMessage umsg, IGuildUser targetUser = null) { - var channel = (ITextChannel)umsg.Channel; - IGuildUser user = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + IGuildUser user = (IGuildUser)Context.User; if (targetUser == null) { @@ -310,13 +309,13 @@ namespace NadekoBot.Modules.Pokemon [RequireContext(ContextType.Guild)] public async Task Settype(IUserMessage umsg, [Remainder] string typeTargeted = null) { - var channel = (ITextChannel)umsg.Channel; - IGuildUser user = (IGuildUser)umsg.Author; + var channel = (ITextChannel)Context.Channel; + IGuildUser user = (IGuildUser)Context.User; var targetType = StringToPokemonType(typeTargeted); if (targetType == null) { - await channel.EmbedAsync(PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"), (eb, pt) => eb.AddField(efb => efb.WithName(pt.Name).WithValue(pt.Icon).WithIsInline(true))).WithColor(NadekoBot.OkColor).Build()).ConfigureAwait(false); + await channel.EmbedAsync(PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"), (eb, pt) => eb.AddField(efb => efb.WithName(pt.Name).WithValue(pt.Icon).WithIsInline(true))).WithColor(NadekoBot.OkColor)).ConfigureAwait(false); return; } if (targetType == GetPokeType(user.Id)) diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index a21ea1f5..d3444687 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class AnimeSearchCommands + public class AnimeSearchCommands : ModuleBase { private static Timer anilistTokenRefresher { get; } private static Logger _log { get; } @@ -56,7 +56,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Anime(IUserMessage umsg, [Remainder] string query) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(query)) return; @@ -65,37 +65,17 @@ namespace NadekoBot.Modules.Searches if (animeData == null) { - await umsg.Channel.SendErrorAsync("Failed finding that animu.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed finding that animu.").ConfigureAwait(false); return; } - - var embed = new Discord.API.Embed() - { - Description = animeData.Synopsis, - Title = animeData.title_english, - Url = animeData.Link, - Image = new Discord.API.EmbedImage() { - Url = animeData.image_url_lge - }, - Fields = new[] { - new Discord.API.EmbedField() { - Inline = true, - Name = "Episodes", - Value = animeData.total_episodes.ToString() - }, - new Discord.API.EmbedField() { - Inline = true, - Name = "Status", - Value = animeData.AiringStatus.ToString() - }, - new Discord.API.EmbedField() { - Inline = true, - Name = "Genres", - Value = String.Join(", ", animeData.Genres) - } - }, - Color = NadekoBot.OkColor - }; + var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithDescription(animeData.Synopsis) + .WithTitle(animeData.title_english) + .WithUrl(animeData.Link) + .WithImageUrl(animeData.image_url_lge) + .AddField(efb => efb.WithName("Episodes").WithValue(animeData.total_episodes.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName("Status").WithValue(animeData.AiringStatus.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName("Genres").WithValue(String.Join(", ", animeData.Genres)).WithIsInline(true)); await channel.EmbedAsync(embed).ConfigureAwait(false); } @@ -103,7 +83,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Manga(IUserMessage umsg, [Remainder] string query) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(query)) return; @@ -112,38 +92,18 @@ namespace NadekoBot.Modules.Searches if (mangaData == null) { - await umsg.Channel.SendErrorAsync("Failed finding that mango.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed finding that mango.").ConfigureAwait(false); return; } - var embed = new Discord.API.Embed() - { - Description = mangaData.Synopsis, - Title = mangaData.title_english, - Url = mangaData.Link, - Image = new Discord.API.EmbedImage() - { - Url = mangaData.image_url_lge - }, - Fields = new[] { - new Discord.API.EmbedField() { - Inline = true, - Name = "Chapters", - Value = mangaData.total_chapters.ToString() - }, - new Discord.API.EmbedField() { - Inline = true, - Name = "Status", - Value = mangaData.publishing_status.ToString() - }, - new Discord.API.EmbedField() { - Inline = true, - Name = "Genres", - Value = String.Join(", ", mangaData.Genres) - } - }, - Color = NadekoBot.OkColor - }; + var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithDescription(mangaData.Synopsis) + .WithTitle(mangaData.title_english) + .WithUrl(mangaData.Link) + .WithImageUrl(mangaData.image_url_lge) + .AddField(efb => efb.WithName("Episodes").WithValue(mangaData.total_chapters.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName("Status").WithValue(mangaData.publishing_status.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName("Genres").WithValue(String.Join(", ", mangaData.Genres)).WithIsInline(true)); await channel.EmbedAsync(embed).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index b5327810..f84f9469 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class JokeCommands + public class JokeCommands : ModuleBase { private static List wowJokes { get; } = new List(); private static List magicItems { get; } = new List(); @@ -44,62 +44,62 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Yomama(IUserMessage msg) + public async Task Yomama() { using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://api.yomomma.info/").ConfigureAwait(false); - await msg.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Randjoke(IUserMessage msg) + public async Task Randjoke() { using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false); - await msg.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(JObject.Parse(response)["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChuckNorris(IUserMessage msg) + public async Task ChuckNorris() { using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://api.icndb.com/jokes/random/").ConfigureAwait(false); - await msg.Channel.SendConfirmAsync(JObject.Parse(response)["value"]["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(JObject.Parse(response)["value"]["joke"].ToString() + " ๐Ÿ˜†").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task WowJoke(IUserMessage msg) + public async Task WowJoke() { if (!wowJokes.Any()) { - await msg.Channel.SendErrorAsync("Jokes not loaded.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Jokes not loaded.").ConfigureAwait(false); return; } var joke = wowJokes[new NadekoRandom().Next(0, wowJokes.Count)]; - await msg.Channel.SendConfirmAsync(joke.Question, joke.Answer).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(joke.Question, joke.Answer).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task MagicItem(IUserMessage msg) + public async Task MagicItem() { if (!wowJokes.Any()) { - await msg.Channel.SendErrorAsync("MagicItems not loaded.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("MagicItems not loaded.").ConfigureAwait(false); return; } var item = magicItems[new NadekoRandom().Next(0, magicItems.Count)]; - await msg.Channel.SendConfirmAsync("โœจ" + item.Name, item.Description).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœจ" + item.Name, item.Description).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index e50f2060..991fec8f 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -34,12 +34,8 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Lolban(IUserMessage umsg) + public async Task Lolban() { - var channel = (ITextChannel)umsg.Channel; - - - var showCount = 8; //http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2 try @@ -58,12 +54,12 @@ namespace NadekoBot.Modules.Searches eb.AddField(efb => efb.WithName(champ["name"].ToString()).WithValue(champ["general"]["banRate"] + "%").WithIsInline(true)); } - await channel.EmbedAsync(eb.Build(), Format.Italics(trashTalk[new NadekoRandom().Next(0, trashTalk.Length)])).ConfigureAwait(false); + await Context.Channel.EmbedAsync(eb, Format.Italics(trashTalk[new NadekoRandom().Next(0, trashTalk.Length)])).ConfigureAwait(false); } } catch (Exception) { - await channel.SendMessageAsync("Something went wrong.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("Something went wrong.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs index 3c48eab0..f4e1d317 100644 --- a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs @@ -16,9 +16,8 @@ namespace NadekoBot.Modules.Searches { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Memelist(IUserMessage umsg) + public async Task Memelist() { - var channel = (ITextChannel)umsg.Channel; HttpClientHandler handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; @@ -29,7 +28,7 @@ namespace NadekoBot.Modules.Searches var data = JsonConvert.DeserializeObject>(rawJson) .Select(kvp => Path.GetFileName(kvp.Value)); - await channel.SendTableAsync(data, x => $"{x,-17}", 3).ConfigureAwait(false); + await Context.Channel.SendTableAsync(data, x => $"{x,-17}", 3).ConfigureAwait(false); } } @@ -37,11 +36,9 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Memegen(IUserMessage umsg, string meme, string topText, string botText) { - var channel = (ITextChannel)umsg.Channel; - var top = Uri.EscapeDataString(topText.Replace(' ', '-')); var bot = Uri.EscapeDataString(botText.Replace(' ', '-')); - await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg") + await Context.Channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg") .ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs index 02373bb3..9b4c0c1b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs @@ -34,7 +34,7 @@ namespace NadekoBot.Modules.Searches.Commands.OMDB public string Plot { get; set; } public string Poster { get; set; } - public Embed GetEmbed() => + public EmbedBuilder GetEmbed() => new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle(Title) .WithUrl($"http://www.imdb.com/title/{ImdbId}/") @@ -42,8 +42,7 @@ namespace NadekoBot.Modules.Searches.Commands.OMDB .AddField(efb => efb.WithName("Rating").WithValue(ImdbRating).WithIsInline(true)) .AddField(efb => efb.WithName("Genre").WithValue(Genre).WithIsInline(true)) .AddField(efb => efb.WithName("Year").WithValue(Year).WithIsInline(true)) - .WithImage(eib => eib.WithUrl(Poster)) - .Build(); + .WithImageUrl(Poster); public override string ToString() => $@"`Title:` {Title} diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index 58d7dfdc..fa665d5b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class OsuCommands + public class OsuCommands : ModuleBase { private static Logger _log { get; } @@ -26,10 +26,8 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Osu(IUserMessage umsg, string usr, [Remainder] string mode = null) + public async Task Osu(string usr, [Remainder] string mode = null) { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(usr)) return; @@ -48,11 +46,11 @@ namespace NadekoBot.Modules.Searches MemoryStream ms = new MemoryStream(); res.CopyTo(ms); ms.Position = 0; - await channel.SendFileAsync(ms, $"{usr}.png", $"๐ŸŽง **Profile Link: **https://osu.ppy.sh/u/{Uri.EscapeDataString(usr)}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); + await Context.Channel.SendFileAsync(ms, $"{usr}.png", $"๐ŸŽง **Profile Link: **https://osu.ppy.sh/u/{Uri.EscapeDataString(usr)}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync("Failed retrieving osu signature.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed retrieving osu signature.").ConfigureAwait(false); _log.Warn(ex, "Osu command failed"); } } @@ -62,7 +60,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Osub(IUserMessage umsg, [Remainder] string map) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) { @@ -99,7 +97,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Osu5(IUserMessage umsg, string user, [Remainder] string mode = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) { await channel.SendErrorAsync("An osu! API key is required.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs index ec3ddfb1..ca1d1a7d 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class OverwatchCommands + public class OverwatchCommands : ModuleBase { private Logger _log; public OverwatchCommands() @@ -27,7 +27,6 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Overwatch(IUserMessage umsg, string region, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(query)) return; var battletag = Regex.Replace(query, "#", "-", RegexOptions.IgnoreCase); @@ -43,7 +42,7 @@ namespace NadekoBot.Modules.Searches .WithAuthor(eau => eau.WithName($"{model.username}") .WithUrl($"https://www.overbuff.com/players/pc/{battletag}") .WithIconUrl($"{model.avatar}")) - .WithThumbnail(th => th.WithUrl("https://cdn.discordapp.com/attachments/155726317222887425/255653487512256512/YZ4w2ey.png")) + .WithThumbnailUrl("https://cdn.discordapp.com/attachments/155726317222887425/255653487512256512/YZ4w2ey.png") .AddField(fb => fb.WithName("**Level**").WithValue($"{model.level}").WithIsInline(true)) .AddField(fb => fb.WithName("**Quick Wins**").WithValue($"{model.Games.Quick.wins}").WithIsInline(true)) .AddField(fb => fb.WithName("**Current Competitive Wins**").WithValue($"{model.Games.Competitive.wins}").WithIsInline(true)) @@ -53,7 +52,7 @@ namespace NadekoBot.Modules.Searches .AddField(fb => fb.WithName("**Competitive Playtime**").WithValue($"{model.Playtime.competitive}").WithIsInline(true)) .AddField(fb => fb.WithName("**Quick Playtime**").WithValue($"{model.Playtime.quick}").WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } else { @@ -61,7 +60,7 @@ namespace NadekoBot.Modules.Searches .WithAuthor(eau => eau.WithName($"{model.username}") .WithUrl($"https://www.overbuff.com/players/pc/{battletag}") .WithIconUrl($"{model.avatar}")) - .WithThumbnail(th => th.WithUrl(rankimg)) + .WithThumbnailUrl(rankimg) .AddField(fb => fb.WithName("**Level**").WithValue($"{model.level}").WithIsInline(true)) .AddField(fb => fb.WithName("**Quick Wins**").WithValue($"{model.Games.Quick.wins}").WithIsInline(true)) .AddField(fb => fb.WithName("**Current Competitive Wins**").WithValue($"{model.Games.Competitive.wins}").WithIsInline(true)) @@ -71,32 +70,32 @@ namespace NadekoBot.Modules.Searches .AddField(fb => fb.WithName("**Competitive Playtime**").WithValue($"{model.Playtime.competitive}").WithIsInline(true)) .AddField(fb => fb.WithName("**Quick Playtime**").WithValue($"{model.Playtime.quick}").WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); return; } } catch { - await channel.SendErrorAsync("Found no user! Please check the **Region** and **BattleTag** before trying again."); + await Context.Channel.SendErrorAsync("Found no user! Please check the **Region** and **BattleTag** before trying again."); } } - public async Task GetProfile(string region, string battletag) - { - try - { - using (var http = new HttpClient()) - { - var Url = await http.GetStringAsync($"https://api.lootbox.eu/pc/{region.ToLower()}/{battletag}/profile"); - var model = JsonConvert.DeserializeObject(Url); - return model.data; - } - } - catch - { - return null; - } - } - - } + public async Task GetProfile(string region, string battletag) + { + try + { + using (var http = new HttpClient()) + { + var Url = await http.GetStringAsync($"https://api.lootbox.eu/pc/{region.ToLower()}/{battletag}/profile"); + var model = JsonConvert.DeserializeObject(Url); + return model.data; + } + } + catch + { + return null; + } + } + + } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs index 2be2d88a..513a4e80 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs @@ -11,7 +11,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class PlaceCommands + public class PlaceCommands : ModuleBase { string typesStr { get; } = ""; public PlaceCommands() @@ -33,11 +33,9 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Placelist(IUserMessage imsg) + public async Task Placelist() { - var channel = (ITextChannel)imsg.Channel; - - await channel.SendConfirmAsync(typesStr) + await Context.Channel.SendConfirmAsync(typesStr) .ConfigureAwait(false); } @@ -45,8 +43,6 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Place(IUserMessage imsg, PlaceType placeType, uint width = 0, uint height = 0) { - var channel = (ITextChannel)imsg.Channel; - string url = ""; switch (placeType) { @@ -84,7 +80,7 @@ namespace NadekoBot.Modules.Searches url += $"/{width}/{height}"; - await channel.SendMessageAsync(url).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(url).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index 60b9c27e..31269b00 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -15,7 +15,7 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class PokemonSearchCommands + public class PokemonSearchCommands : ModuleBase { private static Dictionary pokemons { get; } = new Dictionary(); private static Dictionary pokemonAbilities { get; } = new Dictionary(); @@ -42,10 +42,8 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Pokemon(IUserMessage umsg, [Remainder] string pokemon = null) + public async Task Pokemon([Remainder] string pokemon = null) { - var channel = (ITextChannel)umsg.Channel; - pokemon = pokemon?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(pokemon)) return; @@ -55,25 +53,23 @@ namespace NadekoBot.Modules.Searches if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant()) { var p = kvp.Value; - await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle(kvp.Key.ToTitleCase()) .WithDescription(p.BaseStats.ToString()) .AddField(efb => efb.WithName("Types").WithValue(string.Join(",\n", p.Types)).WithIsInline(true)) .AddField(efb => efb.WithName("Height/Weight").WithValue($"{p.HeightM}m/{p.WeightKg}kg").WithIsInline(true)) .AddField(efb => efb.WithName("Abilitities").WithValue(string.Join(",\n", p.Abilities.Select(a => a.Value))).WithIsInline(true)) - .Build()); + ); return; } } - await channel.SendErrorAsync("No pokemon found."); + await Context.Channel.SendErrorAsync("No pokemon found."); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task PokemonAbility(IUserMessage umsg, [Remainder] string ability = null) + public async Task PokemonAbility([Remainder] string ability = null) { - var channel = (ITextChannel)umsg.Channel; - ability = ability?.Trim().ToUpperInvariant().Replace(" ", ""); if (string.IsNullOrWhiteSpace(ability)) return; @@ -81,15 +77,15 @@ namespace NadekoBot.Modules.Searches { if (kvp.Key.ToUpperInvariant() == ability) { - await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle(kvp.Value.Name) .WithDescription(kvp.Value.Desc) .AddField(efb => efb.WithName("Rating").WithValue(kvp.Value.Rating.ToString()).WithIsInline(true)) - .Build()).ConfigureAwait(false); + ).ConfigureAwait(false); return; } } - await channel.SendErrorAsync("No ability found."); + await Context.Channel.SendErrorAsync("No ability found."); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index b81626f2..99d2fd03 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -1,4 +1,5 @@ ๏ปฟusing Discord.Commands; +using Discord; using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; @@ -67,7 +68,7 @@ namespace NadekoBot.Modules.Searches } [Group] - public class StreamNotificationCommands + public class StreamNotificationCommands : ModuleBase { private static Timer checkTimer { get; } private static ConcurrentDictionary oldCachedStatuses = new ConcurrentDictionary(); @@ -105,10 +106,10 @@ namespace NadekoBot.Modules.Searches oldStatus.IsLive != newStatus.IsLive) { var server = NadekoBot.Client.GetGuild(fs.GuildId); - var channel = server?.GetTextChannel(fs.ChannelId); + var channel = server?.GetTextChannelAsync(fs.ChannelId); if (channel == null) return; - try { await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); } catch { } + try { await (await channel).EmbedAsync(fs.GetEmbed(newStatus)).ConfigureAwait(false); } catch { } } } catch { } @@ -192,66 +193,62 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Hitbox(IUserMessage msg, [Remainder] string username) => - await TrackStream((ITextChannel)msg.Channel, username, FollowedStream.FollowedStreamType.Hitbox) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Hitbox([Remainder] string username) => + await TrackStream((ITextChannel)Context.Channel, username, FollowedStream.FollowedStreamType.Hitbox) .ConfigureAwait(false); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Twitch(IUserMessage msg, [Remainder] string username) => - await TrackStream((ITextChannel)msg.Channel, username, FollowedStream.FollowedStreamType.Twitch) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Twitch([Remainder] string username) => + await TrackStream((ITextChannel)Context.Channel, username, FollowedStream.FollowedStreamType.Twitch) .ConfigureAwait(false); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task Beam(IUserMessage msg, [Remainder] string username) => - await TrackStream((ITextChannel)msg.Channel, username, FollowedStream.FollowedStreamType.Beam) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task Beam([Remainder] string username) => + await TrackStream((ITextChannel)Context.Channel, username, FollowedStream.FollowedStreamType.Beam) .ConfigureAwait(false); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ListStreams(IUserMessage imsg) + public async Task ListStreams() { - var channel = (ITextChannel)imsg.Channel; - IEnumerable streams; using (var uow = DbHandler.UnitOfWork()) { streams = uow.GuildConfigs - .For(channel.Guild.Id, + .For(Context.Guild.Id, set => set.Include(gc => gc.FollowedStreams)) .FollowedStreams; } if (!streams.Any()) { - await channel.SendConfirmAsync("You are not following any streams on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("You are not following any streams on this server.").ConfigureAwait(false); return; } var text = string.Join("\n", streams.Select(snc => { - return $"`{snc.Username}`'s stream on **{channel.Guild.GetTextChannel(snc.ChannelId)?.Name}** channel. ใ€`{snc.Type.ToString()}`ใ€‘"; + return $"`{snc.Username}`'s stream on **{Context.Guild.GetTextChannel(snc.ChannelId)?.Name}** channel. ใ€`{snc.Type.ToString()}`ใ€‘"; })); - await channel.SendConfirmAsync($"You are following **{streams.Count()}** streams on this server.\n\n" + text).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"You are following **{streams.Count()}** streams on this server.\n\n" + text).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.ManageMessages)] - public async Task RemoveStream(IUserMessage msg, FollowedStream.FollowedStreamType type, [Remainder] string username) + [RequireUserPermission(GuildPermission.ManageMessages)] + public async Task RemoveStream(FollowedStream.FollowedStreamType type, [Remainder] string username) { - var channel = (ITextChannel)msg.Channel; - username = username.ToLowerInvariant().Trim(); var fs = new FollowedStream() { - ChannelId = channel.Id, + ChannelId = Context.Channel.Id, Username = username, Type = type }; @@ -259,25 +256,23 @@ namespace NadekoBot.Modules.Searches bool removed; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.FollowedStreams)); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(gc => gc.FollowedStreams)); removed = config.FollowedStreams.Remove(fs); if (removed) await uow.CompleteAsync().ConfigureAwait(false); } if (!removed) { - await channel.SendErrorAsync("No such stream.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No such stream.").ConfigureAwait(false); return; } - await channel.SendConfirmAsync($"Removed `{username}`'s stream ({type}) from notifications.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Removed `{username}`'s stream ({type}) from notifications.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task CheckStream(IUserMessage imsg, FollowedStream.FollowedStreamType platform, [Remainder] string username) { - var channel = (ITextChannel)imsg.Channel; - var stream = username?.Trim(); if (string.IsNullOrWhiteSpace(stream)) return; @@ -290,20 +285,20 @@ namespace NadekoBot.Modules.Searches })); if (streamStatus.IsLive) { - await channel.SendConfirmAsync($"Streamer {username} is online with {streamStatus.Views} viewers."); + await Context.Channel.SendConfirmAsync($"Streamer {username} is online with {streamStatus.Views} viewers."); } else { - await channel.SendConfirmAsync($"Streamer {username} is offline."); + await Context.Channel.SendConfirmAsync($"Streamer {username} is offline."); } } catch { - await channel.SendErrorAsync("No channel found."); + await Context.Channel.SendErrorAsync("No channel found."); } } - private async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type) + private static async Task TrackStream(ITextChannel channel, string username, FollowedStream.FollowedStreamType type) { username = username.ToLowerInvariant().Trim(); var fs = new FollowedStream @@ -332,7 +327,7 @@ namespace NadekoBot.Modules.Searches .Add(fs); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.EmbedAsync(fs.GetEmbed(status).Build(), $"๐Ÿ†— I will notify this channel when status changes.").ConfigureAwait(false); + await channel.EmbedAsync(fs.GetEmbed(status), $"๐Ÿ†— I will notify this channel when status changes.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index 31aaf147..113eca2f 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -6,6 +6,7 @@ using System; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Linq; +using Discord.WebSocket; namespace NadekoBot.Modules.Searches { @@ -18,7 +19,7 @@ namespace NadekoBot.Modules.Searches } [Group] - public class TranslateCommands + public class TranslateCommands : ModuleBase { private static ConcurrentDictionary TranslatedChannels { get; } private static ConcurrentDictionary UserLanguages { get; } @@ -30,7 +31,7 @@ namespace NadekoBot.Modules.Searches NadekoBot.Client.MessageReceived += (msg) => { - var umsg = msg as IUserMessage; + var umsg = msg as SocketUserMessage; if(umsg == null) return Task.CompletedTask; @@ -52,7 +53,7 @@ namespace NadekoBot.Modules.Searches try { - var text = await TranslateInternal(umsg, langs, umsg.Resolve(UserMentionHandling.Ignore), true) + var text = await TranslateInternal(umsg, langs, umsg.Resolve(userHandling: TagHandling.Ignore), true) .ConfigureAwait(false); if (autoDelete) try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { } @@ -69,11 +70,11 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Translate(IUserMessage umsg, string langs, [Remainder] string text = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); var translation = await TranslateInternal(umsg, langs, text); await channel.SendConfirmAsync("Translation " + langs, translation).ConfigureAwait(false); } @@ -104,11 +105,11 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task AutoTranslate(IUserMessage msg, AutoDeleteAutoTranslate autoDelete = AutoDeleteAutoTranslate.Nodel) + public async Task AutoTranslate(AutoDeleteAutoTranslate autoDelete = AutoDeleteAutoTranslate.Nodel) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; if (autoDelete == AutoDeleteAutoTranslate.Del) { @@ -131,20 +132,18 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AutoTransLang(IUserMessage msg, [Remainder] string langs = null) + public async Task AutoTransLang([Remainder] string langs = null) { - var channel = (ITextChannel)msg.Channel; - var ucp = new UserChannelPair { - UserId = msg.Author.Id, - ChannelId = msg.Channel.Id, + UserId = Context.User.Id, + ChannelId = Context.Channel.Id, }; if (string.IsNullOrWhiteSpace(langs)) { if (UserLanguages.TryRemove(ucp, out langs)) - await channel.SendConfirmAsync($"{msg.Author.Mention}'s auto-translate language has been removed.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention}'s auto-translate language has been removed.").ConfigureAwait(false); return; } @@ -156,22 +155,20 @@ namespace NadekoBot.Modules.Searches if (!GoogleTranslator.Instance.Languages.Contains(from) || !GoogleTranslator.Instance.Languages.Contains(to)) { - try { await channel.SendErrorAsync("Invalid source and/or target language.").ConfigureAwait(false); } catch { } + try { await Context.Channel.SendErrorAsync("Invalid source and/or target language.").ConfigureAwait(false); } catch { } return; } UserLanguages.AddOrUpdate(ucp, langs, (key, val) => langs); - await channel.SendConfirmAsync($"Your auto-translate language has been set to {from}>{to}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Your auto-translate language has been set to {from}>{to}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Translangs(IUserMessage umsg) + public async Task Translangs() { - var channel = (ITextChannel)umsg.Channel; - - await channel.SendTableAsync(GoogleTranslator.Instance.Languages, str => $"{str,-15}", columns: 3); + await Context.Channel.SendTableAsync(GoogleTranslator.Instance.Languages, str => $"{str,-15}", columns: 3); } } diff --git a/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs b/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs index f5700698..f6b0ad98 100644 --- a/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/XkcdCommands.cs @@ -12,24 +12,21 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [Group] - public class XkcdCommands + public class XkcdCommands : ModuleBase { private const string xkcdUrl = "https://xkcd.com"; [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Xkcd(IUserMessage msg, string arg = null) + public async Task Xkcd(string arg = null) { - var channel = (ITextChannel)msg.Channel; - if (arg?.ToLowerInvariant().Trim() == "latest") { using (var http = new HttpClient()) { var res = await http.GetStringAsync($"{xkcdUrl}/info.0.json").ConfigureAwait(false); var comic = JsonConvert.DeserializeObject(res); - var sent = await channel.SendMessageAsync($"{msg.Author.Mention} " + comic.ToString()) + var sent = await Context.Channel.SendMessageAsync($"{Context.User.Mention} " + comic.ToString()) .ConfigureAwait(false); await Task.Delay(10000).ConfigureAwait(false); @@ -38,16 +35,13 @@ namespace NadekoBot.Modules.Searches } return; } - await Xkcd(msg, new NadekoRandom().Next(1, 1750)).ConfigureAwait(false); + await Xkcd(new NadekoRandom().Next(1, 1750)).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Xkcd(IUserMessage msg, int num) + public async Task Xkcd(int num) { - var channel = (ITextChannel)msg.Channel; - if (num < 1) return; @@ -57,16 +51,16 @@ namespace NadekoBot.Modules.Searches var comic = JsonConvert.DeserializeObject(res); var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) - .WithImage(eib => eib.WithUrl(comic.ImageLink)) + .WithImageUrl(comic.ImageLink) .WithAuthor(eab => eab.WithName(comic.Title).WithUrl($"{xkcdUrl}/{num}").WithIconUrl("http://xkcd.com/s/919f27.ico")) .AddField(efb => efb.WithName("Comic#").WithValue(comic.Num.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName("Date").WithValue($"{comic.Month}/{comic.Year}").WithIsInline(true)); - var sent = await channel.EmbedAsync(embed.Build()) + var sent = await Context.Channel.EmbedAsync(embed) .ConfigureAwait(false); await Task.Delay(10000).ConfigureAwait(false); - await sent.ModifyAsync(m => m.Embed = embed.AddField(efb => efb.WithName("Alt").WithValue(comic.Alt.ToString()).WithIsInline(false)).Build()); + await sent.ModifyAsync(m => m.Embed = embed.AddField(efb => efb.WithName("Alt").WithValue(comic.Alt.ToString()).WithIsInline(false))); } } } diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index a3f5eb0e..98ce1f78 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -27,7 +27,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Weather(IUserMessage umsg, string city, string country) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; city = city.Replace(" ", ""); country = city.Replace(" ", ""); string response; @@ -47,14 +47,14 @@ namespace NadekoBot.Modules.Searches .AddField(fb => fb.WithName("๐ŸŒ„ **Sunrise**").WithValue($"{obj["sunrise"]}").WithIsInline(true)) .AddField(fb => fb.WithName("๐ŸŒ‡ **Sunset**").WithValue($"{obj["sunset"]}").WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Youtube(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (!(await ValidateQuery(channel, query).ConfigureAwait(false))) return; var result = (await NadekoBot.Google.GetVideosByKeywordsAsync(query, 1)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(result)) @@ -72,10 +72,10 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Imdb(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (!(await ValidateQuery(channel, query).ConfigureAwait(false))) return; - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); var movie = await OmdbProvider.FindMovie(query); if (movie == null) @@ -88,9 +88,9 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RandomCat(IUserMessage umsg) + public async Task RandomCat() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { var res = JObject.Parse(await http.GetStringAsync("http://www.random.cat/meow").ConfigureAwait(false)); @@ -100,9 +100,9 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RandomDog(IUserMessage umsg) + public async Task RandomDog() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { await channel.SendMessageAsync("http://random.dog/" + await http.GetStringAsync("http://random.dog/woof") @@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task I(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(query)) return; @@ -145,7 +145,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Ir(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(query)) return; @@ -178,7 +178,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Lmgtfy(IUserMessage umsg, [Remainder] string ffs = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(ffs)) @@ -190,7 +190,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Shorten(IUserMessage msg, [Remainder] string arg) + public async Task Shorten([Remainder] string arg) { if (string.IsNullOrWhiteSpace(arg)) return; @@ -199,15 +199,14 @@ namespace NadekoBot.Modules.Searches if (shortened == arg) { - await msg.Channel.SendErrorAsync("Failed to shorten that url.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed to shorten that url.").ConfigureAwait(false); } - await msg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .AddField(efb => efb.WithName("Original Url") .WithValue($"<{arg}>")) .AddField(efb => efb.WithName("Short Url") - .WithValue($"<{shortened}>")) - .Build()) + .WithValue($"<{shortened}>"))) .ConfigureAwait(false); } @@ -215,7 +214,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Google(IUserMessage umsg, [Remainder] string terms = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; terms = terms?.Trim(); if (string.IsNullOrWhiteSpace(terms)) @@ -229,7 +228,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task MagicTheGathering(IUserMessage umsg, [Remainder] string name = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = name; if (string.IsNullOrWhiteSpace(arg)) { @@ -237,7 +236,7 @@ namespace NadekoBot.Modules.Searches return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); string response = ""; using (var http = new HttpClient()) { @@ -258,13 +257,13 @@ namespace NadekoBot.Modules.Searches var embed = new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithTitle(item["name"].ToString()) .WithDescription(desc) - .WithImage(eib => eib.WithUrl(img)) + .WithImageUrl(img) .AddField(efb => efb.WithName("Store Url").WithValue(storeUrl).WithIsInline(true)) .AddField(efb => efb.WithName("Cost").WithValue(cost).WithIsInline(true)) .AddField(efb => efb.WithName("Types").WithValue(types).WithIsInline(true)); //.AddField(efb => efb.WithName("Store Url").WithValue(await NadekoBot.Google.ShortenUrl(items[0]["store_url"].ToString())).WithIsInline(true)); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } catch { @@ -277,7 +276,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Hearthstone(IUserMessage umsg, [Remainder] string name = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = name; if (string.IsNullOrWhiteSpace(arg)) { @@ -291,7 +290,7 @@ namespace NadekoBot.Modules.Searches return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); string response = ""; using (var http = new HttpClient()) { @@ -321,7 +320,7 @@ namespace NadekoBot.Modules.Searches msg = "โš  Found over 4 images. Showing random 4."; } var ms = new MemoryStream(); - images.Merge().SaveAsPng(ms); + images.AsEnumerable().Merge().SaveAsPng(ms); ms.Position = 0; await channel.SendFileAsync(ms, arg + ".png", msg).ConfigureAwait(false); } @@ -337,7 +336,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Yodify(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { @@ -351,7 +350,7 @@ namespace NadekoBot.Modules.Searches await channel.SendErrorAsync("Please enter a sentence.").ConfigureAwait(false); return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); @@ -365,7 +364,7 @@ namespace NadekoBot.Modules.Searches .WithAuthor(au => au.WithName("Yoda").WithIconUrl("http://www.yodaspeak.co.uk/yoda-small1.gif")) .WithDescription(res) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } catch { @@ -378,7 +377,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task UrbanDict(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { @@ -392,7 +391,7 @@ namespace NadekoBot.Modules.Searches await channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); @@ -409,7 +408,7 @@ namespace NadekoBot.Modules.Searches .WithUrl(link) .WithAuthor(eab => eab.WithIconUrl("http://i.imgur.com/nwERwQE.jpg").WithName(word)) .WithDescription(def); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } catch { @@ -422,7 +421,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Hashtag(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = query; if (string.IsNullOrWhiteSpace(arg)) @@ -436,7 +435,7 @@ namespace NadekoBot.Modules.Searches return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); string res = ""; using (var http = new HttpClient()) { @@ -456,8 +455,7 @@ namespace NadekoBot.Modules.Searches .WithAuthor(eab => eab.WithUrl(link) .WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg") .WithName(query)) - .WithDescription(desc) - .Build()); + .WithDescription(desc)); } catch { @@ -467,9 +465,9 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Catfact(IUserMessage umsg) + public async Task Catfact() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false); @@ -485,10 +483,10 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Revav(IUserMessage umsg, [Remainder] IUser usr = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (usr == null) - usr = umsg.Author; + usr = Context.User; await channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); } @@ -496,7 +494,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Revimg(IUserMessage umsg, [Remainder] string imageLink = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; imageLink = imageLink?.Trim() ?? ""; if (string.IsNullOrWhiteSpace(imageLink)) @@ -508,7 +506,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Safebooru(IUserMessage umsg, [Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var link = await GetSafebooruImageLink(tag).ConfigureAwait(false); @@ -522,7 +520,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Wiki(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; query = query?.Trim(); if (string.IsNullOrWhiteSpace(query)) @@ -542,7 +540,7 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Color(IUserMessage umsg, [Remainder] string color = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; color = color?.Trim().Replace("#", ""); if (string.IsNullOrWhiteSpace((string)color)) @@ -562,11 +560,11 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Videocall(IUserMessage umsg, [Remainder] string arg = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { - var allUsrs = umsg.MentionedUsers.Append(umsg.Author); + var allUsrs = umsg.MentionedUsers.Append(Context.User); var allUsrsArray = allUsrs.ToArray(); var str = allUsrsArray.Aggregate("http://appear.in/", (current, usr) => current + Uri.EscapeUriString(usr.Username[0].ToString())); str += new NadekoRandom().Next(); @@ -585,9 +583,9 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Avatar(IUserMessage umsg, [Remainder] string mention = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; - var usr = umsg.MentionedUsers.FirstOrDefault(); + var usr = umsg.MentionedUsers().FirstOrDefault(); if (usr == null) { await channel.SendErrorAsync("Invalid user specified.").ConfigureAwait(false); @@ -616,13 +614,13 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task Wikia(IUserMessage umsg, string target, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query)) { await channel.SendErrorAsync("Please enter a target wikia, followed by search query.").ConfigureAwait(false); return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); @@ -647,14 +645,14 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task MCPing(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = query; if (string.IsNullOrWhiteSpace(arg)) { await channel.SendErrorAsync("๐Ÿ’ข Please enter a `ip:port`.").ConfigureAwait(false); return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); @@ -684,14 +682,14 @@ namespace NadekoBot.Modules.Searches [RequireContext(ContextType.Guild)] public async Task MCQ(IUserMessage umsg, [Remainder] string query = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var arg = query; if (string.IsNullOrWhiteSpace(arg)) { await channel.SendErrorAsync("Please enter `ip:port`.").ConfigureAwait(false); return; } - await umsg.Channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); diff --git a/src/NadekoBot/Modules/Trello/Trello.cs b/src/NadekoBot/Modules/Trello/Trello.cs index fbda6fab..c3a7863f 100644 --- a/src/NadekoBot/Modules/Trello/Trello.cs +++ b/src/NadekoBot/Modules/Trello/Trello.cs @@ -75,7 +75,7 @@ // .Parameter("board_id", Discord.Commands.ParameterType.Required) // .Do(async e => // { -// if (!NadekoBot.IsOwner(umsg.Author.Id)) return; +// if (!NadekoBot.IsOwner(Context.User.Id)) return; // if (bound != null) return; // try // { @@ -95,7 +95,7 @@ // .Description($"Unbinds a bot from the channel and board. **Bot Owner Only!**| `{Prefix}unbind`") // .Do(async e => // { -// if (!NadekoBot.IsOwner(umsg.Author.Id)) return; +// if (!NadekoBot.IsOwner(Context.User.Id)) return; // if (bound == null || bound != e.Channel) return; // t.Stop(); // bound = null; @@ -109,7 +109,7 @@ // .Description($"Lists all lists, yo ;) **Bot Owner Only!**| `{Prefix}list`") // .Do(async e => // { -// if (!NadekoBot.IsOwner(umsg.Author.Id)) return; +// if (!NadekoBot.IsOwner(Context.User.Id)) return; // if (bound == null || board == null || bound != e.Channel) return; // await channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**โ€ข " + l.ToString() + "**"))) // .ConfigureAwait(false); @@ -120,7 +120,7 @@ // .Parameter("list_name", Discord.Commands.ParameterType.Unparsed) // .Do(async e => // { -// if (!NadekoBot.IsOwner(umsg.Author.Id)) return; +// if (!NadekoBot.IsOwner(Context.User.Id)) return; // if (bound == null || board == null || bound != e.Channel || list_name == null) return; // int num; diff --git a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs index 31a91f6f..0f90db17 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs @@ -16,15 +16,15 @@ namespace NadekoBot.Modules.Utility { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public static async Task Calculate(IUserMessage msg, [Remainder] string expression) + public async Task Calculate([Remainder] string expression) { var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); expr.EvaluateParameter += Expr_EvaluateParameter; var result = expr.Evaluate(); if (expr.Error == null) - await msg.Channel.SendConfirmAsync("Result", $"{result}"); + await Context.Channel.SendConfirmAsync("Result", $"{result}"); else - await msg.Channel.SendErrorAsync($"โš™ Error", expr.Error); + await Context.Channel.SendErrorAsync($"โš™ Error", expr.Error); } private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args) @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CalcOps(IUserMessage msg) + public async Task CalcOps() { var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x => { @@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Utility "Equals", "GetHashCode", "GetType"}); - await msg.Channel.SendConfirmAsync(string.Join(", ",selection)); + await Context.Channel.SendConfirmAsync(string.Join(", ",selection)); } } diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 740b18e0..9c01b77c 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -14,9 +14,9 @@ namespace NadekoBot.Modules.Utility { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ServerInfo(IUserMessage msg, string guildName = null) + public async Task ServerInfo(string guildName = null) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; guildName = guildName?.ToUpperInvariant(); IGuild guild; if (string.IsNullOrWhiteSpace(guildName)) @@ -43,24 +43,24 @@ namespace NadekoBot.Modules.Utility .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Roles**").WithValue(guild.Roles.Count().ToString()).WithIsInline(true)) - .WithImage(tn => tn.WithUrl(guild.IconUrl)) + .WithImageUrl(guild.IconUrl) .WithColor(NadekoBot.OkColor); if (guild.Emojis.Count() > 0) { embed.AddField(fb => fb.WithName("**Custom Emojis**").WithValue(Format.Italics(string.Join(", ", guild.Emojis))).WithIsInline(true)); } - await msg.Channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChannelInfo(IUserMessage msg, ITextChannel channel = null) + public async Task ChannelInfo(ITextChannel channel = null) { - var ch = channel ?? (ITextChannel)msg.Channel; + var ch = channel ?? (ITextChannel)Context.Channel; if (ch == null) return; var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); - var usercount = (await ch.GetUsersAsync()).Count(); + var usercount = (await ch.GetUsersAsync().Flatten()).Count(); var embed = new EmbedBuilder() .WithTitle(ch.Name) .WithDescription(ch.Topic?.SanitizeMentions()) @@ -68,15 +68,15 @@ namespace NadekoBot.Modules.Utility .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await msg.Channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UserInfo(IUserMessage msg, IGuildUser usr = null) + public async Task UserInfo(IGuildUser usr = null) { - var channel = (ITextChannel)msg.Channel; - var user = usr ?? msg.Author as IGuildUser; + var channel = (ITextChannel)Context.Channel; + var user = usr ?? Context.User as IGuildUser; if (user == null) return; @@ -89,11 +89,11 @@ namespace NadekoBot.Modules.Utility embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true)) .AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Name)}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.Roles.Count()})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) .WithThumbnail(tn => tn.WithUrl(user.AvatarUrl)) .WithColor(NadekoBot.OkColor); - await msg.Channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs index 41ce9aa8..1162f3d7 100644 --- a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs @@ -15,10 +15,8 @@ namespace NadekoBot.Modules.Utility { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ListQuotes(IUserMessage imsg, int page = 1) + public async Task ListQuotes(int page = 1) { - var channel = (ITextChannel)imsg.Channel; - page -= 1; if (page < 0) @@ -27,22 +25,20 @@ namespace NadekoBot.Modules.Utility IEnumerable quotes; using (var uow = DbHandler.UnitOfWork()) { - quotes = uow.Quotes.GetGroup(channel.Guild.Id, page * 16, 16); + quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16); } if (quotes.Any()) - await channel.SendConfirmAsync($"๐Ÿ’ฌ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") + await Context.Channel.SendConfirmAsync($"๐Ÿ’ฌ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") .ConfigureAwait(false); else - await channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ShowQuote(IUserMessage umsg, [Remainder] string keyword) + public async Task ShowQuote([Remainder] string keyword) { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(keyword)) return; @@ -51,21 +47,19 @@ namespace NadekoBot.Modules.Utility Quote quote; using (var uow = DbHandler.Instance.GetUnitOfWork()) { - quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(channel.Guild.Id, keyword).ConfigureAwait(false); + quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false); } if (quote == null) return; - await channel.SendMessageAsync("๐Ÿ“ฃ " + quote.Text.SanitizeMentions()); + await Context.Channel.SendMessageAsync("๐Ÿ“ฃ " + quote.Text.SanitizeMentions()); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AddQuote(IUserMessage umsg, string keyword, [Remainder] string text) + public async Task AddQuote(string keyword, [Remainder] string text) { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(keyword) || string.IsNullOrWhiteSpace(text)) return; @@ -75,56 +69,52 @@ namespace NadekoBot.Modules.Utility { uow.Quotes.Add(new Quote { - AuthorId = umsg.Author.Id, - AuthorName = umsg.Author.Username, - GuildId = channel.Guild.Id, + AuthorId = Context.Message.Author.Id, + AuthorName = Context.Message.Author.Username, + GuildId = Context.Guild.Id, Keyword = keyword, Text = text, }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync("โœ… Quote added.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Quote added.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task DeleteQuote(IUserMessage umsg, [Remainder] string keyword) + public async Task DeleteQuote([Remainder] string keyword) { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(keyword)) return; - var isAdmin = ((IGuildUser)umsg.Author).GuildPermissions.Administrator; + var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator; keyword = keyword.ToUpperInvariant(); string response; using (var uow = DbHandler.UnitOfWork()) { - var qs = uow.Quotes.GetAllQuotesByKeyword(channel.Guild.Id, keyword); + var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); if (qs==null || !qs.Any()) { - await channel.SendErrorAsync("No quotes found."); + await Context.Channel.SendErrorAsync("No quotes found.").ConfigureAwait(false); return; } - var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == umsg.Author.Id); + var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id); uow.Quotes.Remove(q); await uow.CompleteAsync().ConfigureAwait(false); response = "๐Ÿ—‘ **Deleted a random quote.**"; } - await channel.SendConfirmAsync(response); + await Context.Channel.SendConfirmAsync(response); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] - public async Task DelAllQuotes(IUserMessage umsg, [Remainder] string keyword) + [RequireUserPermission(GuildPermission.Administrator)] + public async Task DelAllQuotes([Remainder] string keyword) { - var channel = (ITextChannel)umsg.Channel; - if (string.IsNullOrWhiteSpace(keyword)) return; @@ -132,14 +122,14 @@ namespace NadekoBot.Modules.Utility using (var uow = DbHandler.UnitOfWork()) { - var quotes = uow.Quotes.GetAllQuotesByKeyword(channel.Guild.Id, keyword); + var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); uow.Quotes.RemoveRange(quotes.ToArray());//wtf?! await uow.CompleteAsync(); } - await channel.SendConfirmAsync($"๐Ÿ—‘ **Deleted all quotes** with **{keyword}** keyword."); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ **Deleted all quotes** with **{keyword}** keyword."); } } } diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index 60ba241a..2f0300a4 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -17,7 +17,7 @@ namespace NadekoBot.Modules.Utility public partial class Utility { [Group] - public class RemindCommands + public class RemindCommands : ModuleBase { Regex regex = new Regex(@"^(?:(?\d)mo)?(?:(?\d)w)?(?:(?\d{1,2})d)?(?:(?\d{1,2})h)?(?:(?\d{1,2})m)?$", @@ -62,14 +62,16 @@ namespace NadekoBot.Modules.Utility await Task.Delay(time); try { - IMessageChannel ch; + IMessageChannel ch = null; if (r.IsPrivate) { ch = await NadekoBot.Client.GetDMChannelAsync(r.ChannelId).ConfigureAwait(false); } else { - ch = NadekoBot.Client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); + var t = NadekoBot.Client.GetGuild(r.ServerId)?.GetTextChannelAsync(r.ChannelId).ConfigureAwait(false); + if (t != null) + ch = await t.Value; } if (ch == null) return; @@ -101,16 +103,14 @@ namespace NadekoBot.Modules.Utility [Priority(1)] public async Task Remind(IUserMessage umsg, MeOrHere meorhere, string timeStr, [Remainder] string message) { - var channel = (ITextChannel)umsg.Channel; - IMessageChannel target; if (meorhere == MeOrHere.Me) { - target = await ((IGuildUser)umsg.Author).CreateDMChannelAsync().ConfigureAwait(false); + target = await ((IGuildUser)Context.User).CreateDMChannelAsync().ConfigureAwait(false); } else { - target = channel; + target = Context.Channel; } await Remind(umsg, target, timeStr, message).ConfigureAwait(false); } @@ -120,11 +120,11 @@ namespace NadekoBot.Modules.Utility [Priority(0)] public async Task Remind(IUserMessage umsg, IMessageChannel ch, string timeStr, [Remainder] string message) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (ch == null) { - await channel.SendErrorAsync($"{umsg.Author.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); + await channel.SendErrorAsync($"{Context.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false); return; } @@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Utility IsPrivate = ch is IDMChannel, When = time, Message = message, - UserId = umsg.Author.Id, + UserId = Context.User.Id, ServerId = channel.Guild.Id }; @@ -187,7 +187,7 @@ namespace NadekoBot.Modules.Utility await uow.CompleteAsync(); } - try { await channel.SendConfirmAsync($"โฐ I will remind **\"{(ch is ITextChannel ? ((ITextChannel)ch).Name : umsg.Author.Username)}\"** to **\"{message.SanitizeMentions()}\"** in **{output}** `({time:d.M.yyyy.} at {time:HH:mm})`").ConfigureAwait(false); } catch { } + try { await channel.SendConfirmAsync($"โฐ I will remind **\"{(ch is ITextChannel ? ((ITextChannel)ch).Name : Context.User.Username)}\"** to **\"{message.SanitizeMentions()}\"** in **{output}** `({time:d.M.yyyy.} at {time:HH:mm})`").ConfigureAwait(false); } catch { } await StartReminder(rem); } @@ -196,7 +196,7 @@ namespace NadekoBot.Modules.Utility [OwnerOnly] public async Task RemindTemplate(IUserMessage umsg, [Remainder] string arg) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(arg)) return; diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index 3468a15f..4238bcad 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Utility public partial class Utility { [Group] - public class UnitConverterCommands + public class UnitConverterCommands : ModuleBase { public static List Units { get; set; } = new List(); @@ -102,7 +102,7 @@ namespace NadekoBot.Modules.Utility } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ConvertList(IUserMessage msg) + public async Task ConvertList() { var res = Units.GroupBy(x => x.UnitType) .Aggregate(new EmbedBuilder().WithTitle("__Units which can be used by the converter__") @@ -111,21 +111,21 @@ namespace NadekoBot.Modules.Utility efb.WithName(g.Key.ToTitleCase()) .WithValue(String.Join(", ", g.Select(x => x.Triggers.FirstOrDefault()) .OrderBy(x => x))))); - await msg.Channel.EmbedAsync(res.Build()); + await Context.Channel.EmbedAsync(res); } [NadekoCommand, Usage, Description, Aliases] - public async Task Convert(IUserMessage msg, string origin, string target, decimal value) + public async Task Convert(string origin, string target, decimal value) { var originUnit = Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(origin.ToLowerInvariant())); var targetUnit = Units.Find(x => x.Triggers.Select(y => y.ToLowerInvariant()).Contains(target.ToLowerInvariant())); if (originUnit == null || targetUnit == null) { - await msg.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: units not found", origin, target)); + await Context.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: units not found", origin, target)); return; } if (originUnit.UnitType != targetUnit.UnitType) { - await msg.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: types of unit are not equal", originUnit.Triggers.First(), targetUnit.Triggers.First())); + await Context.Channel.SendErrorAsync(string.Format("Cannot convert {0} to {1}: types of unit are not equal", originUnit.Triggers.First(), targetUnit.Triggers.First())); return; } decimal res; @@ -169,7 +169,7 @@ namespace NadekoBot.Modules.Utility } res = Math.Round(res, 4); - await msg.Channel.SendConfirmAsync(string.Format("{0} {1} is equal to {2} {3}", value, (originUnit.Triggers.First() + "s").SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2))); + await Context.Channel.SendConfirmAsync(string.Format("{0} {1} is equal to {2} {3}", value, (originUnit.Triggers.First() + "s").SnPl(value.IsInteger() ? (int)value : 2), res, (targetUnit.Triggers.First() + "s").SnPl(res.IsInteger() ? (int)res : 2))); } } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 1e6fce9c..f91d8a02 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -18,7 +18,6 @@ using EmbedField = Discord.API.EmbedField; namespace NadekoBot.Modules.Utility { - [NadekoModule("Utility", ".")] public partial class Utility : DiscordModule { @@ -29,103 +28,101 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task WhosPlaying(IUserMessage umsg, [Remainder] string game = null) + public async Task WhosPlaying([Remainder] string game = null) { - var channel = (ITextChannel)umsg.Channel; game = game.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(game)) return; - var arr = (await (umsg.Channel as IGuildChannel).Guild.GetUsersAsync()) + var arr = (await (Context.Channel as IGuildChannel).Guild.GetUsersAsync()) .Where(u => u.Game?.Name?.ToUpperInvariant() == game) .Select(u => u.Username) .ToList(); int i = 0; if (!arr.Any()) - await channel.SendErrorAsync("Nobody is playing that game.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Nobody is playing that game.").ConfigureAwait(false); else - await channel.SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 2) + await Context.Channel.SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 2) .Select(ig => string.Concat(ig.Select(el => $"โ€ข {el,-27}")))) + "\n```") .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task InRole(IUserMessage umsg, [Remainder] string roles) + public async Task InRole([Remainder] string roles) { if (string.IsNullOrWhiteSpace(roles)) return; - var channel = (ITextChannel)umsg.Channel; var arg = roles.Split(',').Select(r => r.Trim().ToUpperInvariant()); string send = "โ„น๏ธ **Here is a list of users in those roles:**"; foreach (var roleStr in arg.Where(str => !string.IsNullOrWhiteSpace(str) && str != "@EVERYONE" && str != "EVERYONE")) { - var role = channel.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault(); + var role = Context.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault(); if (role == null) continue; send += $"```css\n[{role.Name}]\n"; - send += string.Join(", ", channel.Guild.GetUsers().Where(u => u.Roles.Contains(role)).Select(u => u.ToString())); + send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Select(u => u.ToString())); send += $"\n```"; } - var usr = umsg.Author as IGuildUser; + var usr = Context.User as IGuildUser; while (send.Length > 2000) { - if (!usr.GetPermissions(channel).ManageMessages) + if (!usr.GetPermissions((ITextChannel)Context.Channel).ManageMessages) { - await channel.SendErrorAsync($"โš ๏ธ {usr.Mention} **you are not allowed to use this command on roles with a lot of users in them to prevent abuse.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"โš ๏ธ {usr.Mention} **you are not allowed to use this command on roles with a lot of users in them to prevent abuse.**").ConfigureAwait(false); return; } var curstr = send.Substring(0, 2000); - await channel.SendConfirmAsync(curstr.Substring(0, + await Context.Channel.SendConfirmAsync(curstr.Substring(0, curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1)).ConfigureAwait(false); send = curstr.Substring(curstr.LastIndexOf(", ", StringComparison.Ordinal) + 1) + send.Substring(2000); } - await channel.SendConfirmAsync(send).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(send).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CheckMyPerms(IUserMessage msg) + public async Task CheckMyPerms() { StringBuilder builder = new StringBuilder("```http\n"); - var user = msg.Author as IGuildUser; - var perms = user.GetPermissions((ITextChannel)msg.Channel); + var user = Context.User as IGuildUser; + var perms = user.GetPermissions((ITextChannel)Context.Channel); foreach (var p in perms.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any())) { builder.AppendLine($"{p.Name} : {p.GetValue(perms, null).ToString()}"); } builder.Append("```"); - await msg.Channel.SendConfirmAsync(builder.ToString()); + await Context.Channel.SendConfirmAsync(builder.ToString()); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UserId(IUserMessage msg, IGuildUser target = null) + public async Task UserId(IGuildUser target = null) { - var usr = target ?? msg.Author; - await msg.Channel.SendConfirmAsync($"๐Ÿ†” of the user **{ usr.Username }** is `{ usr.Id }`").ConfigureAwait(false); + var usr = target ?? Context.User; + await Context.Channel.SendConfirmAsync($"๐Ÿ†” of the user **{ usr.Username }** is `{ usr.Id }`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - public async Task ChannelId(IUserMessage msg) + public async Task ChannelId() { - await msg.Channel.SendConfirmAsync($"๐Ÿ†” of this channel is `{msg.Channel.Id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ†” of this channel is `{Context.Channel.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ServerId(IUserMessage msg) + public async Task ServerId() { - await msg.Channel.SendConfirmAsync($"๐Ÿ†” of this server is `{((ITextChannel)msg.Channel).Guild.Id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ†” of this server is `{((ITextChannel)Context.Channel).Guild.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Roles(IUserMessage msg, IGuildUser target, int page = 1) + public async Task Roles(IGuildUser target, int page = 1) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; var guild = channel.Guild; const int RolesPerPage = 20; @@ -144,14 +141,14 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Roles(IUserMessage msg, int page = 1) => - Roles(msg, null, page); + public Task Roles(int page = 1) => + Roles(null, page); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChannelTopic(IUserMessage umsg) + public async Task ChannelTopic() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var topic = channel.Topic; if (string.IsNullOrWhiteSpace(topic)) @@ -161,76 +158,31 @@ namespace NadekoBot.Modules.Utility } [NadekoCommand, Usage, Description, Aliases] - public async Task Stats(IUserMessage umsg) + public async Task Stats() { - var channel = umsg.Channel; + var channel = Context.Channel; var stats = NadekoBot.Stats; await channel.EmbedAsync( - new Embed() - { - Author = new EmbedAuthor() - { - Name = $"NadekoBot v{StatsService.BotVersion}", - Url = "http://nadekobot.readthedocs.io/en/latest/", - IconUrl = "https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg" - }, - Fields = new[] { - new EmbedField() { - Name = Format.Bold("Author"), - Value = stats.Author, - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Library"), - Value = stats.Library, - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Bot ID"), - Value = NadekoBot.Client.GetCurrentUser().Id.ToString(), - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Commands Ran"), - Value = stats.CommandsRan.ToString(), - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Messages"), - Value = $"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)", - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Memory"), - Value = $"{stats.Heap} MB", - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Owner ID(s)"), - Value = stats.OwnerIds, - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Uptime"), - Value = stats.GetUptimeString("\n"), - Inline = true - }, - new EmbedField() { - Name = Format.Bold("Presence"), - Value = $"{NadekoBot.Client.GetGuilds().Count} Servers\n{stats.TextChannels} Text Channels\n{stats.VoiceChannels} Voice Channels", - Inline = true - }, - - }, - Color = 0x00bbd6 - }); + new EmbedBuilder().WithColor(new Color(0x00bbd6)) + .WithAuthor(eab => eab.WithName($"NadekoBot v{StatsService.BotVersion}") + .WithUrl("http://nadekobot.readthedocs.io/en/latest/") + .WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg")) + .AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser().Id.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Owner ID(s)")).WithValue(stats.OwnerIds).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Uptime")).WithValue(stats.GetUptimeString("\n")).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Presence")).WithValue($"{NadekoBot.Client.GetGuilds().Count} Servers\n{stats.TextChannels} Text Channels\n{stats.VoiceChannels} Voice Channels").WithIsInline(true))); } private Regex emojiFinder { get; } = new Regex(@"<:(?.+?):(?\d*)>", RegexOptions.Compiled); [NadekoCommand, Usage, Description, Aliases] - public async Task Showemojis(IUserMessage msg, [Remainder] string emojis) + public async Task Showemojis([Remainder] string emojis) { var matches = emojiFinder.Matches(emojis); @@ -238,9 +190,9 @@ namespace NadekoBot.Modules.Utility .Select(m => $"**Name:** {m.Groups["name"]} **Link:** http://discordapp.com/api/emojis/{m.Groups["id"]}.png")); if (string.IsNullOrWhiteSpace(result)) - await msg.Channel.SendErrorAsync("No special emojis found."); + await Context.Channel.SendErrorAsync("No special emojis found."); else - await msg.Channel.SendMessageAsync(result).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(result).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -248,7 +200,7 @@ namespace NadekoBot.Modules.Utility [OwnerOnly] public async Task ListServers(IUserMessage imsg, int page = 1) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; page -= 1; @@ -265,9 +217,8 @@ namespace NadekoBot.Modules.Utility await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor), (embed, g) => embed.AddField(efb => efb.WithName(g.Name) - .WithValue($"```css\nID: {g.Id}\nMembers: {g.GetUsers().Count}\nOwnerID: {g.OwnerId} ```") - .WithIsInline(false))) - .Build()) + .WithValue($"```css\nID: {g.Id}\nMembers: {(g.GetUsersAsync().GetAwaiter().GetResult()).Count}\nOwnerID: {g.OwnerId} ```") + .WithIsInline(false)))) .ConfigureAwait(false); } } diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 56839613..6168b062 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -12,12 +12,10 @@ using System.Reflection; using System.Threading.Tasks; using System.Collections.Generic; using NadekoBot.Modules.Permissions; -using Module = Discord.Commands.Module; using NadekoBot.TypeReaders; using System.Collections.Concurrent; using NadekoBot.Modules.Music; using NadekoBot.Services.Database.Models; -using NadekoBot.Modules.Games.Commands.Hangman; namespace NadekoBot { @@ -25,8 +23,8 @@ namespace NadekoBot { private Logger _log; - public static uint OkColor { get; } = 0x71cd40; - public static uint ErrorColor { get; } = 0xee281f; + public static Color OkColor { get; } = new Color(0x71cd40); + public static Color ErrorColor { get; } = new Color(0xee281f); public static CommandService CommandService { get; private set; } public static CommandHandler CommandHandler { get; private set; } @@ -84,7 +82,7 @@ namespace NadekoBot //setup typereaders CommandService.AddTypeReader(new PermissionActionTypeReader()); - CommandService.AddTypeReader(new CommandTypeReader()); + CommandService.AddTypeReader(new CommandTypeReader()); CommandService.AddTypeReader(new ModuleTypeReader()); CommandService.AddTypeReader(new GuildTypeReader()); @@ -103,9 +101,9 @@ namespace NadekoBot // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); - await CommandService.LoadAssembly(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false); + await CommandService.AddModulesAsync(this.GetType().GetTypeInfo().Assembly).ConfigureAwait(false); #if !GLOBAL_NADEKO - await CommandService.Load(new Music()).ConfigureAwait(false); + await CommandService.AddModuleAsync().ConfigureAwait(false); #endif Ready = true; Console.WriteLine(await Stats.Print().ConfigureAwait(false)); diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 031a2dfe..10615415 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -39,7 +39,7 @@ namespace NadekoBot.Services private List ownerChannels { get; set; } - public event Func CommandExecuted = delegate { return Task.CompletedTask; }; + public event Func CommandExecuted = delegate { return Task.CompletedTask; }; public CommandHandler(ShardedDiscordClient client, CommandService commandService) { @@ -49,7 +49,7 @@ namespace NadekoBot.Services } public async Task StartHandling() { - ownerChannels = (await Task.WhenAll(_client.GetGuilds().SelectMany(g => g.GetUsers()) + ownerChannels = (await Task.WhenAll(_client.GetGuilds().SelectMany(g => g.GetUsersAsync().GetAwaiter().GetResult()) .Where(u => NadekoBot.Credentials.OwnerIds.Contains(u.Id)) .Distinct(new IGuildUserComparer()) .Select(async u => { try { return await u.CreateDMChannelAsync(); } catch { return null; } }))) @@ -64,20 +64,20 @@ namespace NadekoBot.Services _client.MessageReceived += MessageReceivedHandler; } - private async Task MessageReceivedHandler(IMessage msg) + private async Task MessageReceivedHandler(SocketMessage msg) { - var usrMsg = msg as IUserMessage; + var usrMsg = msg as SocketUserMessage; if (usrMsg == null) return; - if (usrMsg.Author.IsBot || !NadekoBot.Ready) //no bots + if (usrContext.User.IsBot || !NadekoBot.Ready) //no bots return; - var guild = (msg.Channel as ITextChannel)?.Guild; + var guild = (Context.Channel as SocketTextChannel)?.Guild; - if (guild != null && guild.OwnerId != usrMsg.Author.Id) + if (guild != null && guild.OwnerId != usrContext.User.Id) { - if (Permissions.FilterCommands.InviteFilteringChannels.Contains(usrMsg.Channel.Id) || + if (Permissions.FilterCommands.InviteFilteringChannels.Contains(usrContext.Channel.Id) || Permissions.FilterCommands.InviteFilteringServers.Contains(guild.Id)) { if (usrMsg.Content.IsDiscordInvite()) @@ -89,12 +89,12 @@ namespace NadekoBot.Services } catch (HttpException ex) { - _log.Warn("I do not have permission to filter invites in channel with id " + usrMsg.Channel.Id, ex); + _log.Warn("I do not have permission to filter invites in channel with id " + usrContext.Channel.Id, ex); } } } - var filteredWords = Permissions.FilterCommands.FilteredWordsForChannel(usrMsg.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id)); + var filteredWords = Permissions.FilterCommands.FilteredWordsForChannel(usrContext.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id)); var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' '); if (filteredWords.Any(w => wordsInMessage.Contains(w))) { @@ -105,7 +105,7 @@ namespace NadekoBot.Services } catch (HttpException ex) { - _log.Warn("I do not have permission to filter words in channel with id " + usrMsg.Channel.Id, ex); + _log.Warn("I do not have permission to filter words in channel with id " + usrContext.Channel.Id, ex); } } } @@ -113,8 +113,8 @@ namespace NadekoBot.Services BlacklistItem blacklistedItem; if ((blacklistedItem = Permissions.BlacklistCommands.BlacklistedItems.FirstOrDefault(bi => (bi.Type == BlacklistItem.BlacklistType.Server && bi.ItemId == guild?.Id) || - (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == msg.Channel.Id) || - (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == usrMsg.Author.Id))) != null) + (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == Context.Channel.Id) || + (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == usrContext.User.Id))) != null) { return; } @@ -146,12 +146,12 @@ namespace NadekoBot.Services try { - var t = await ExecuteCommand(usrMsg, usrMsg.Content, guild, usrMsg.Author, MultiMatchHandling.Best); + var t = await ExecuteCommand(usrMsg, usrMsg.Content, guild, usrContext.User, MultiMatchHandling.Best); var command = t.Item1; var permCache = t.Item2; var result = t.Item3; sw.Stop(); - var channel = (usrMsg.Channel as ITextChannel); + var channel = (usrContext.Channel as ITextChannel); if (result.IsSuccess) { await CommandExecuted(usrMsg, command); @@ -160,7 +160,7 @@ namespace NadekoBot.Services "Server: {1}\n\t" + "Channel: {2}\n\t" + "Message: {3}", - usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0} + usrContext.User + " [" + usrContext.User.Id + "]", // {0} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} usrMsg.Content, // {3} @@ -175,7 +175,7 @@ namespace NadekoBot.Services "Channel: {2}\n\t" + "Message: {3}\n\t" + "Error: {4}", - usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0} + usrContext.User + " [" + usrContext.User.Id + "]", // {0} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} usrMsg.Content,// {3} @@ -185,18 +185,18 @@ namespace NadekoBot.Services if (guild != null && command != null && result.Error == CommandError.Exception) { if (permCache != null && permCache.Verbose) - try { await msg.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } + try { await Context.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } } } else { - if (msg.Channel is IPrivateChannel) + if (Context.Channel is IPrivateChannel) { //rofl, gotta do this to prevent this message from occuring on polls int vote; if (int.TryParse(msg.Content, out vote)) return; - await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); await DMForwardCommands.HandleDMForwarding(msg, ownerChannels); } @@ -212,10 +212,10 @@ namespace NadekoBot.Services return; } - public async Task> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) { + public async Task> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) { var searchResult = _commandService.Search(message, input); if (!searchResult.IsSuccess) - return new Tuple(null, null, searchResult); + return new Tuple(null, null, searchResult); var commands = searchResult.Commands; for (int i = commands.Count - 1; i >= 0; i--) @@ -224,7 +224,7 @@ namespace NadekoBot.Services if (!preconditionResult.IsSuccess) { if (commands.Count == 1) - return new Tuple(null, null, searchResult); + return new Tuple(null, null, searchResult); else continue; } @@ -248,7 +248,7 @@ namespace NadekoBot.Services if (!parseResult.IsSuccess) { if (commands.Count == 1) - return new Tuple(null, null, parseResult); + return new Tuple(null, null, parseResult); else continue; } @@ -276,7 +276,7 @@ namespace NadekoBot.Services if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(message, cmd.Text, cmd.Module.Name, out index)) { var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand(guild)}** is preventing this action."; - return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); + return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); } @@ -284,28 +284,28 @@ namespace NadekoBot.Services { if (!((IGuildUser)user).Roles.Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) { - return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); + return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); } } } if (CmdCdsCommands.HasCooldown(cmd, guild, user)) - return new Tuple(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); + return new Tuple(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); - return new Tuple(commands[i], null, await commands[i].Execute(message, parseResult)); + return new Tuple(commands[i], null, await commands[i].Execute(message, parseResult)); } - return new Tuple(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); + return new Tuple(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); } } public class CommandExecutedEventArgs { - public Command Command { get; } + public CommandInfo Command { get; } public IUserMessage Message { get; } - public CommandExecutedEventArgs(IUserMessage msg, Command cmd) + public CommandExecutedEventArgs(CommandInfo cmd) { Message = msg; Command = cmd; diff --git a/src/NadekoBot/Services/Impl/BotCredentials.cs b/src/NadekoBot/Services/Impl/BotCredentials.cs index fdd0a1fa..2aa58a33 100644 --- a/src/NadekoBot/Services/Impl/BotCredentials.cs +++ b/src/NadekoBot/Services/Impl/BotCredentials.cs @@ -46,7 +46,7 @@ namespace NadekoBot.Services.Impl configBuilder.AddJsonFile(credsFileName, true) .AddEnvironmentVariables("NadekoBot_"); - var data = configBuilder.Build(); + var data = configBuilder; Token = data[nameof(Token)]; if (string.IsNullOrWhiteSpace(Token)) diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 8b71f3c4..95c04854 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -67,7 +67,7 @@ namespace NadekoBot.Services.Impl } public async Task Print() { - var curUser = await client.GetCurrentUserAsync(); + var curUser = await client.CurrentUser(); return $@" Author: [{Author}] | Library: [{Library}] Bot Version: [{BotVersion}] diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index 892bc6d8..747ba4fa 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -13,19 +13,19 @@ namespace NadekoBot private DiscordSocketConfig discordSocketConfig; private Logger _log { get; } - public event Func UserJoined = delegate { return Task.CompletedTask; }; - public event Func MessageReceived = delegate { return Task.CompletedTask; }; - public event Func UserLeft = delegate { return Task.CompletedTask; }; - public event Func UserUpdated = delegate { return Task.CompletedTask; }; - public event Func, IMessage, Task> MessageUpdated = delegate { return Task.CompletedTask; }; - public event Func, Task> MessageDeleted = delegate { return Task.CompletedTask; }; - public event Func UserBanned = delegate { return Task.CompletedTask; }; - public event Func UserUnbanned = delegate { return Task.CompletedTask; }; - public event Func UserPresenceUpdated = delegate { return Task.CompletedTask; }; - public event Func UserVoiceStateUpdated = delegate { return Task.CompletedTask; }; - public event Func ChannelCreated = delegate { return Task.CompletedTask; }; - public event Func ChannelDestroyed = delegate { return Task.CompletedTask; }; - public event Func ChannelUpdated = delegate { return Task.CompletedTask; }; + public event Func UserJoined = delegate { return Task.CompletedTask; }; + public event Func MessageReceived = delegate { return Task.CompletedTask; }; + public event Func UserLeft = delegate { return Task.CompletedTask; }; + public event Func UserUpdated = delegate { return Task.CompletedTask; }; + public event Func, SocketMessage, Task> MessageUpdated = delegate { return Task.CompletedTask; }; + public event Func, Task> MessageDeleted = delegate { return Task.CompletedTask; }; + public event Func UserBanned = delegate { return Task.CompletedTask; }; + public event Func UserUnbanned = delegate { return Task.CompletedTask; }; + public event Func, SocketUser, SocketPresence, SocketPresence, Task> UserPresenceUpdated = delegate { return Task.CompletedTask; }; + public event Func UserVoiceStateUpdated = delegate { return Task.CompletedTask; }; + public event Func ChannelCreated = delegate { return Task.CompletedTask; }; + public event Func ChannelDestroyed = delegate { return Task.CompletedTask; }; + public event Func ChannelUpdated = delegate { return Task.CompletedTask; }; public event Func Disconnected = delegate { return Task.CompletedTask; }; private IReadOnlyList Clients { get; } @@ -48,7 +48,7 @@ namespace NadekoBot client.MessageUpdated += async (arg1, m2) => await MessageUpdated(arg1, m2); client.MessageDeleted += async (arg1, arg2) => await MessageDeleted(arg1, arg2); client.UserBanned += async (arg1, arg2) => await UserBanned(arg1, arg2); - client.UserPresenceUpdated += async (arg1, arg2, arg3) => await UserPresenceUpdated(arg1, arg2, arg3); + client.UserPresenceUpdated += async (arg1, arg2, arg3, arg4) => await UserPresenceUpdated(arg1, arg2, arg3, arg4); client.UserVoiceStateUpdated += async (arg1, arg2, arg3) => await UserVoiceStateUpdated(arg1, arg2, arg3); client.ChannelCreated += async arg => await ChannelCreated(arg); client.ChannelDestroyed += async arg => await ChannelDestroyed(arg); @@ -60,17 +60,14 @@ namespace NadekoBot Clients = clientList.AsReadOnly(); } - public ISelfUser GetCurrentUser() => - Clients[0].GetCurrentUser(); + public ISelfUser CurrentUser() => + Clients[0].CurrentUser; - public Task GetCurrentUserAsync() => - Clients[0].GetCurrentUserAsync(); - - public Task GetAllCurrentUsersAsync() => - Task.WhenAll(Clients.Select(c => c.GetCurrentUserAsync())); + public ISelfUser[] GetAllCurrentUsers() => + Clients.Select(c => c.CurrentUser).ToArray(); public IReadOnlyCollection GetGuilds() => - Clients.SelectMany(c => c.GetGuilds()).ToArray(); + Clients.SelectMany(c => c.Guilds).ToList(); public IGuild GetGuild(ulong id) => Clients.Select(c => c.GetGuild(id)).FirstOrDefault(g => g != null); @@ -104,19 +101,11 @@ namespace NadekoBot } internal Task DownloadAllUsersAsync() => - Task.WhenAll(Clients.Select(async c => { await c.DownloadAllUsersAsync().ConfigureAwait(false); _log.Info($"Shard #{c.ShardId} downloaded {c.GetGuilds().Sum(g => g.GetUsers().Count)} users."); })); + Task.WhenAll(Clients.Select(async c => { await c.DownloadAllUsersAsync().ConfigureAwait(false); _log.Info($"Shard #{c.ShardId} downloaded {c.Guilds.Sum(g => g.Users.Count)} users."); })); - public async Task SetGame(string game) - { - await Task.WhenAll((await GetAllCurrentUsersAsync()) - .Select(u => u.ModifyStatusAsync(ms => ms.Game = new Discord.Game(game)))); - } + public Task SetGame(string game) => Task.WhenAll(Clients.Select(ms => ms.SetGame(game))); - public async Task SetStream(string name, string url) - { - await Task.WhenAll((await GetAllCurrentUsersAsync()) - .Select(u => u.ModifyStatusAsync(ms => ms.Game = new Discord.Game(name, url, StreamType.Twitch)))); - - } + + public Task SetStream(string name, string url) => Task.WhenAll(Clients.Select(ms => ms.SetGame(name, url, StreamType.NotStreaming))); } } diff --git a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs index 91763e8a..6128f6ff 100644 --- a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs +++ b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs @@ -7,12 +7,11 @@ namespace NadekoBot.TypeReaders { public class CommandTypeReader : TypeReader { - public override Task Read(IUserMessage context, string input) + public override Task Read(CommandContext context, string input) { input = input.ToUpperInvariant(); var cmd = NadekoBot.CommandService.Commands.FirstOrDefault(c => - c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input) || - c.Text.ToUpperInvariant() == input); + c.Aliases.Select(a => a.ToUpperInvariant()).Contains(input)); if (cmd == null) return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such command found.")); diff --git a/src/NadekoBot/TypeReaders/GuildTypeReader.cs b/src/NadekoBot/TypeReaders/GuildTypeReader.cs index ab9a5259..37576b95 100644 --- a/src/NadekoBot/TypeReaders/GuildTypeReader.cs +++ b/src/NadekoBot/TypeReaders/GuildTypeReader.cs @@ -7,7 +7,7 @@ namespace NadekoBot.TypeReaders { public class GuildTypeReader : TypeReader { - public override Task Read(IUserMessage context, string input) + public override Task Read(CommandContext context, string input) { input = input.Trim().ToLowerInvariant(); var guilds = NadekoBot.Client.GetGuilds(); diff --git a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs index 366429ec..fbc36ac8 100644 --- a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs @@ -7,7 +7,7 @@ namespace NadekoBot.TypeReaders { public class ModuleTypeReader : TypeReader { - public override Task Read(IUserMessage context, string input) + public override Task Read(CommandContext context, string input) { input = input.ToUpperInvariant(); var module = NadekoBot.CommandService.Modules.FirstOrDefault(m => m.Name.ToUpperInvariant() == input); diff --git a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs index 209f69b1..76071620 100644 --- a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs +++ b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs @@ -10,7 +10,7 @@ namespace NadekoBot.TypeReaders /// public class PermissionActionTypeReader : TypeReader { - public override Task Read(IUserMessage context, string input) + public override Task Read(CommandContext context, string input) { input = input.ToUpperInvariant(); switch (input) diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index a94681bb..ae947ee5 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -69,16 +69,18 @@ namespace NadekoBot.Extensions await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(message, isTTS).ConfigureAwait(false); public static async Task SendConfirmAsync(this IGuildUser user, string text) - => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new Embed() { Description = text, Color = NadekoBot.OkColor }); + => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text)); public static async Task SendConfirmAsync(this IGuildUser user, string title, string text, string url = null) - => await(await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new Embed() { Description = text, Title = title, Url = url, Color = NadekoBot.OkColor }); + => await(await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text) + .WithTitle(title).WithUrl(url)); public static async Task SendErrorAsync(this IGuildUser user, string title, string error, string url = null) - => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.ErrorColor }); + => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error) + .WithTitle(title).WithUrl(url)); public static async Task SendErrorAsync(this IGuildUser user, string error) - => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new Embed() { Description = error, Color = NadekoBot.ErrorColor }); + => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error)); public static async Task SendFileAsync(this IGuildUser user, string filePath, string caption = null, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(filePath, caption, isTTS).ConfigureAwait(false); @@ -87,25 +89,27 @@ namespace NadekoBot.Extensions await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); public static bool IsAuthor(this IUserMessage msg) => - NadekoBot.Client.GetCurrentUser().Id == msg.Author.Id; + NadekoBot.Client.CurrentUser().Id == msg.Author.Id; public static IEnumerable Members(this IRole role) => - NadekoBot.Client.GetGuild(role.GuildId)?.GetUsers().Where(u => u.Roles.Contains(role)) ?? Enumerable.Empty(); + role.Guild.GetUsersAsync().GetAwaiter().GetResult() ?? Enumerable.Empty(); - public static Task EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "") + public static Task EmbedAsync(this IMessageChannel ch, EmbedBuilder embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); public static Task SendErrorAsync(this IMessageChannel ch, string title, string error, string url = null) - => ch.SendMessageAsync("", embed: new Embed() { Description = error, Title = title, Url = url, Color = NadekoBot.ErrorColor }); + => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.ErrorColor).WithDescription(error) + .WithTitle(title).WithUrl(url)); public static Task SendErrorAsync(this IMessageChannel ch, string error) - => ch.SendMessageAsync("", embed: new Embed() { Description = error, Color = NadekoBot.ErrorColor }); + => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error)); public static Task SendConfirmAsync(this IMessageChannel ch, string title, string text, string url = null) - => ch.SendMessageAsync("", embed: new Embed() { Description = text, Title = title, Url = url, Color = NadekoBot.OkColor }); + => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text) + .WithTitle(title).WithUrl(url)); public static Task SendConfirmAsync(this IMessageChannel ch, string text) - => ch.SendMessageAsync("", embed: new Embed() { Description = text, Color = NadekoBot.OkColor }); + => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text)); public static Task SendTableAsync(this IMessageChannel ch, string seed, IEnumerable items, Func howToPrint, int columns = 3) { @@ -274,11 +278,11 @@ namespace NadekoBot.Extensions public static string Unmention(this string str) => str.Replace("@", "เถธ"); - public static Image Merge(this IEnumerable images) + public static ImageSharp.Image Merge(this IEnumerable images) { var imgList = images.ToList(); - var canvas = new Image(imgList.Sum(img => img.Width), imgList.Max(img => img.Height)); + var canvas = new ImageSharp.Image(imgList.Sum(img => img.Width), imgList.Max(img => img.Height)); var canvasPixels = canvas.Lock(); int offsetX = 0; @@ -297,7 +301,7 @@ namespace NadekoBot.Extensions return canvas; } - public static Stream ToStream(this Image img) + public static Stream ToStream(this ImageSharp.Image img) { var imageStream = new MemoryStream(); img.SaveAsPng(imageStream); diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index cbf49aa2..ac27a4f3 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -19,12 +19,6 @@ "dependencies": { "VideoLibrary": "1.3.4", "CoreCLR-NCalc": "2.1.2", - "Discord.Net.Commands": { - "target": "project" - }, - "Discord.Net": { - "target": "project" - }, "Google.Apis.Urlshortener.v1": "1.19.0.138", "Google.Apis.YouTube.v3": "1.19.0.655", "ImageSharp": "1.0.0-alpha-000079", @@ -44,7 +38,9 @@ "Newtonsoft.Json": "9.0.2-beta1", "NLog": "5.0.0-beta03", "System.Diagnostics.Contracts": "4.3.0", - "System.Xml.XPath": "4.3.0" + "System.Xml.XPath": "4.3.0", + "Discord.Net.Commands": "1.0.0-*", + "Discord.Net.WebSocket": "1.0.0-*" }, "tools": { "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final", From 91bcd82b511dbfd925b41a4879ca49a1abf89af4 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 19:44:46 +0100 Subject: [PATCH 02/30] woops --- NadekoBot.sln | 44 ++++++++++++++++++++++++++++++-------------- discord.net | 2 +- global.json | 2 +- 3 files changed, 32 insertions(+), 16 deletions(-) diff --git a/NadekoBot.sln b/NadekoBot.sln index 7b8981b8..147256fe 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -12,9 +12,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NadekoBot", "src\NadekoBot\NadekoBot.xproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net", "discord.net\src\Discord.Net\Discord.Net.xproj", "{91E9E7BD-75C9-4E98-84AA-2C271922E5C2}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{F29E2B91-6877-4EF1-8B54-523FE06F780C}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "discord.net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{526FAB2E-03EA-4231-B480-555F926B1750}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "discord.net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "discord.net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{E8B62DD4-5A6B-4C66-916B-A782247BC983}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -29,18 +33,30 @@ Global {45EC1473-C678-4857-A544-07DFE0D0B478}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.ActiveCfg = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.Build.0 = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.ActiveCfg = GlobalNadeko|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.Build.0 = Release|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.ActiveCfg = GlobalNadeko|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.Build.0 = Release|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Release|Any CPU.Build.0 = Release|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.Debug|Any CPU.Build.0 = Debug|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.Release|Any CPU.ActiveCfg = Release|Any CPU + {526FAB2E-03EA-4231-B480-555F926B1750}.Release|Any CPU.Build.0 = Release|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Release|Any CPU.Build.0 = Release|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/discord.net b/discord.net index 508026d5..803b6521 160000 --- a/discord.net +++ b/discord.net @@ -1 +1 @@ -Subproject commit 508026d5d4f4d8780d983c63ab25e4c15ad69e59 +Subproject commit 803b65212eaa153eb7f5d2aa6774ac8a44ea5a01 diff --git a/global.json b/global.json index 9c989b51..cb8b27b5 100644 --- a/global.json +++ b/global.json @@ -1,3 +1,3 @@ { - "projects": [ "discord.net/src", "src" ] + "projects": [ "discord.net/src", "src", "../../../Documents/Visual Studio 2015/Projects/NadekoWebsite/nadekobot/discord.net/src" ] } From 23cefb04b7696916ad7afa20c5de5713101454c9 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 19:46:48 +0100 Subject: [PATCH 03/30] Moved to RogueException/dev properly --- discord.net | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord.net b/discord.net index 803b6521..c102f52b 160000 --- a/discord.net +++ b/discord.net @@ -1 +1 @@ -Subproject commit 803b65212eaa153eb7f5d2aa6774ac8a44ea5a01 +Subproject commit c102f52bfa1a6fd6ffbbd7c7f65d07342e8b6851 From 3722ab240e3a49acb85c1342f8091e7b06958460 Mon Sep 17 00:00:00 2001 From: samvaio Date: Sat, 17 Dec 2016 00:42:23 +0530 Subject: [PATCH 04/30] Update ClashOfClans.cs --- src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 253e751e..7364c63b 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -294,7 +294,7 @@ namespace NadekoBot.Modules.ClashOfClans var channel = (ITextChannel)Context.Channel; //check if there are any wars List wars = null; - ClashWars.TryGetValue(channel.Guild.Id, out wars); + ClashWars.TryGetValue(Context.Guild.Id, out wars); if (wars == null || wars.Count == 0) { return null; From b7384285a6d46195df7c6c377e2a23398d1cdc70 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 20:45:46 +0100 Subject: [PATCH 05/30] a lot more converting stuff --- .../Games/Commands/CleverBotCommands.cs | 26 +- .../Modules/Games/Commands/HangmanCommands.cs | 5 +- .../Games/Commands/PlantAndPickCommands.cs | 18 +- .../Modules/Games/Commands/PollCommands.cs | 288 +++++++++--------- .../Games/Commands/SpeedTypingCommands.cs | 18 +- .../Modules/Games/Commands/TriviaCommands.cs | 16 +- src/NadekoBot/Modules/Games/Games.cs | 26 +- src/NadekoBot/Modules/Help/Help.cs | 41 +-- src/NadekoBot/Modules/Music/Music.cs | 124 ++++---- src/NadekoBot/Modules/NSFW/NSFW.cs | 90 ++---- .../Permissions/Commands/CmdCdsCommands.cs | 14 +- 11 files changed, 312 insertions(+), 354 deletions(-) diff --git a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs index 5062b251..d3f3a8b1 100644 --- a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs @@ -15,7 +15,7 @@ namespace NadekoBot.Modules.Games public partial class Games { [Group] - public class CleverBotCommands + public class CleverBotCommands : ModuleBase { private static Logger _log { get; } @@ -41,8 +41,8 @@ namespace NadekoBot.Modules.Games } } - public static async Task TryAsk() { - var channel = Context.Channel as ITextChannel; + public static async Task TryAsk(IUserMessage msg) { + var channel = msg.Channel as ITextChannel; if (channel == null) return false; @@ -68,16 +68,16 @@ namespace NadekoBot.Modules.Games return false; } - await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); + await msg.Channel.TriggerTypingAsync().ConfigureAwait(false); var response = await cleverbot.Think(message).ConfigureAwait(false); try { - await Context.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); + await msg.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); } catch { - await Context.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); // try twice :\ + await msg.Channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); // try twice :\ } return true; } @@ -87,32 +87,30 @@ namespace NadekoBot.Modules.Games [RequireUserPermission(ChannelPermission.ManageMessages)] public async Task Cleverbot() { - var channel = (ITextChannel)Context.Channel; - ChatterBotSession throwaway; - if (CleverbotGuilds.TryRemove(channel.Guild.Id, out throwaway)) + if (CleverbotGuilds.TryRemove(Context.Guild.Id, out throwaway)) { using (var uow = DbHandler.UnitOfWork()) { - uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, false); + uow.GuildConfigs.SetCleverbotEnabled(Context.Guild.Id, false); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{Context.User.Mention} Disabled cleverbot on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} Disabled cleverbot on this server.").ConfigureAwait(false); return; } var cleverbot = ChatterBotFactory.Create(ChatterBotType.CLEVERBOT); var session = cleverbot.CreateSession(); - CleverbotGuilds.TryAdd(channel.Guild.Id, session); + CleverbotGuilds.TryAdd(Context.Guild.Id, session); using (var uow = DbHandler.UnitOfWork()) { - uow.GuildConfigs.SetCleverbotEnabled(channel.Guild.Id, true); + uow.GuildConfigs.SetCleverbotEnabled(Context.Guild.Id, true); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{Context.User.Mention} Enabled cleverbot on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} Enabled cleverbot on this server.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs index 388e5a4d..38be0a13 100644 --- a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs @@ -15,9 +15,8 @@ namespace NadekoBot.Modules.Games { public partial class Games { - [Group] - public class HangmanCommands + public class HangmanCommands : ModuleBase { private static Logger _log { get; } @@ -42,7 +41,7 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - public async Task Hangman(IUserMessage imsg, HangmanTermPool.HangmanTermType type = HangmanTermPool.HangmanTermType.All) + public async Task Hangman(HangmanTermPool.HangmanTermType type = HangmanTermPool.HangmanTermType.All) { var hm = new HangmanGame(Context.Channel, type); diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 42b6055f..35519859 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -29,7 +29,7 @@ namespace NadekoBot.Modules.Games /// https://discord.gg/0TYNJfCU4De7YIk8 /// [Group] - public class PlantPickCommands + public class PlantPickCommands : ModuleBase { private static ConcurrentHashSet generationChannels { get; } = new ConcurrentHashSet(); //channelid/message @@ -60,10 +60,10 @@ namespace NadekoBot.Modules.Games private static Task PotentialFlowerGeneration(IMessage imsg) { var msg = imsg as IUserMessage; - if (msg == null || msg.IsAuthor() || Context.User.IsBot) + if (msg == null || msg.IsAuthor() || imsg.Author.IsBot) return Task.CompletedTask; - var channel = Context.Channel as ITextChannel; + var channel = imsg.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -111,7 +111,7 @@ namespace NadekoBot.Modules.Games List msgs; - try { await imsg.DeleteAsync().ConfigureAwait(false); } catch { } + try { await Context.Message.DeleteAsync().ConfigureAwait(false); } catch { } if (!plantedFlowers.TryRemove(channel.Id, out msgs)) return; @@ -130,12 +130,10 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Plant() { - var channel = (ITextChannel)Context.Channel; - var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, "Planted a flower.", 1, false).ConfigureAwait(false); if (!removed) { - await channel.SendErrorAsync($"You don't have any {Gambling.Gambling.CurrencyPluralName}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"You don't have any {Gambling.Gambling.CurrencyPluralName}.").ConfigureAwait(false); return; } @@ -146,13 +144,13 @@ namespace NadekoBot.Modules.Games var msgToSend = $"Oh how Nice! **{Context.User.Username}** planted {(vowelFirst ? "an" : "a")} {Gambling.Gambling.CurrencyName}. Pick it using {NadekoBot.ModulePrefixes[typeof(Games).Name]}pick"; if (file == null) { - msg = await channel.SendConfirmAsync(Gambling.Gambling.CurrencySign).ConfigureAwait(false); + msg = await Context.Channel.SendConfirmAsync(Gambling.Gambling.CurrencySign).ConfigureAwait(false); } else { - msg = await channel.SendFileAsync(file, msgToSend).ConfigureAwait(false); + msg = await Context.Channel.SendFileAsync(file, msgToSend).ConfigureAwait(false); } - plantedFlowers.AddOrUpdate(channel.Id, new List() { msg }, (id, old) => { old.Add(msg); return old; }); + plantedFlowers.AddOrUpdate(Context.Channel.Id, new List() { msg }, (id, old) => { old.Add(msg); return old; }); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index b5da738e..3b40898e 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -13,173 +13,177 @@ namespace NadekoBot.Modules.Games { public partial class Games { - public static ConcurrentDictionary ActivePolls = new ConcurrentDictionary(); - - [NadekoCommand, Usage, Description, Aliases] - [RequireUserPermission(GuildPermission.ManageMessages)] - [RequireContext(ContextType.Guild)] - public Task Poll(IUserMessage umsg, [Remainder] string arg = null) - => InternalStartPoll(umsg, arg, isPublic: false); - - [NadekoCommand, Usage, Description, Aliases] - [RequireUserPermission(GuildPermission.ManageMessages)] - [RequireContext(ContextType.Guild)] - public Task PublicPoll(IUserMessage umsg, [Remainder] string arg = null) - => InternalStartPoll(umsg, arg, isPublic: true); - - private async Task InternalStartPoll(IUserMessage umsg, string arg, bool isPublic = false) + [Group] + public class PollCommands : ModuleBase { - var channel = (ITextChannel)Context.Channel; + public static ConcurrentDictionary ActivePolls = new ConcurrentDictionary(); - if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) - return; - if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) - return; - var data = arg.Split(';'); - if (data.Length < 3) - return; + [NadekoCommand, Usage, Description, Aliases] + [RequireUserPermission(GuildPermission.ManageMessages)] + [RequireContext(ContextType.Guild)] + public Task Poll([Remainder] string arg = null) + => InternalStartPoll(arg, isPublic: false); - var poll = new Poll(umsg, data[0], data.Skip(1), isPublic: isPublic); - if (ActivePolls.TryAdd(channel.Guild, poll)) + [NadekoCommand, Usage, Description, Aliases] + [RequireUserPermission(GuildPermission.ManageMessages)] + [RequireContext(ContextType.Guild)] + public Task PublicPoll(IUserMessage umsg, [Remainder] string arg = null) + => InternalStartPoll(arg, isPublic: true); + + private async Task InternalStartPoll(string arg, bool isPublic = false) { - await poll.StartPoll().ConfigureAwait(false); - } - else - await channel.SendErrorAsync("Poll is already running on this server.").ConfigureAwait(false); - } + var channel = (ITextChannel)Context.Channel; - [NadekoCommand, Usage, Description, Aliases] - [RequireUserPermission(GuildPermission.ManageMessages)] - [RequireContext(ContextType.Guild)] - public async Task Pollend() - { - var channel = (ITextChannel)Context.Channel; - - Poll poll; - ActivePolls.TryRemove(channel.Guild, out poll); - await poll.StopPoll().ConfigureAwait(false); - } - } - - public class Poll - { - private readonly IUserMessage originalMessage; - private readonly IGuild guild; - private readonly string[] answers; - private ConcurrentDictionary participants = new ConcurrentDictionary(); - private readonly string question; - private DateTime started; - private CancellationTokenSource pollCancellationSource = new CancellationTokenSource(); - private readonly bool isPublic; - - public Poll(IUserMessage umsg, string question, IEnumerable enumerable, bool isPublic = false) - { - this.originalMessage = umsg; - this.guild = ((ITextChannel)Context.Channel).Guild; - this.question = question; - this.answers = enumerable as string[] ?? enumerable.ToArray(); - this.isPublic = isPublic; - } - - public async Task StartPoll() - { - started = DateTime.Now; - NadekoBot.Client.MessageReceived += Vote; - var msgToSend = $"๐Ÿ“ƒ**{originalMessage.Author.Username}** has created a poll which requires your attention:\n\n**{question}**\n"; - var num = 1; - msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); - if (!isPublic) - msgToSend += "\n**Private Message me with the corresponding number of the answer.**"; - else - msgToSend += "\n**Send a Message here with the corresponding number of the answer.**"; - await originalMessage.Channel.SendConfirmAsync(msgToSend).ConfigureAwait(false); - } - - public async Task StopPoll() - { - NadekoBot.Client.MessageReceived -= Vote; - try - { - var results = participants.GroupBy(kvp => kvp.Value) - .ToDictionary(x => x.Key, x => x.Sum(kvp => 1)) - .OrderByDescending(kvp => kvp.Value); - - var totalVotesCast = results.Sum(kvp => kvp.Value); - if (totalVotesCast == 0) - { - await originalMessage.Channel.SendMessageAsync("๐Ÿ“„ **No votes have been cast.**").ConfigureAwait(false); + if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) + return; + if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) + return; + var data = arg.Split(';'); + if (data.Length < 3) return; - } - var closeMessage = $"--------------**POLL CLOSED**--------------\n" + - $"๐Ÿ“„ , here are the results:\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 originalMessage.Channel.SendConfirmAsync($"๐Ÿ“„ **Total votes cast**: {totalVotesCast}\n{closeMessage}").ConfigureAwait(false); + var poll = new Poll(umsg, data[0], data.Skip(1), isPublic: isPublic); + if (ActivePolls.TryAdd(channel.Guild, poll)) + { + await poll.StartPoll().ConfigureAwait(false); + } + else + await channel.SendErrorAsync("Poll is already running on this server.").ConfigureAwait(false); } - catch (Exception ex) + + [NadekoCommand, Usage, Description, Aliases] + [RequireUserPermission(GuildPermission.ManageMessages)] + [RequireContext(ContextType.Guild)] + public async Task Pollend() { - Console.WriteLine($"Error in poll game {ex}"); + var channel = (ITextChannel)Context.Channel; + + Poll poll; + ActivePolls.TryRemove(channel.Guild, out poll); + await poll.StopPoll().ConfigureAwait(false); } } - private Task Vote(IMessage imsg) + public class Poll { - // has to be a user message - var msg = imsg as IUserMessage; - if (msg == null || Context.User.IsBot) - return Task.CompletedTask; + private readonly IUserMessage originalMessage; + private readonly IGuild guild; + private readonly string[] answers; + private ConcurrentDictionary participants = new ConcurrentDictionary(); + private readonly string question; + private DateTime started; + private CancellationTokenSource pollCancellationSource = new CancellationTokenSource(); + private readonly bool isPublic; - // has to be an integer - int vote; - if (!int.TryParse(imsg.Content, out vote)) - return Task.CompletedTask; - if (vote < 1 || vote > answers.Length) - return Task.CompletedTask; - - var t = Task.Run(async () => + public Poll(IUserMessage umsg, string question, IEnumerable enumerable, bool isPublic = false) { + this.originalMessage = umsg; + this.guild = ((ITextChannel)umsg.Channel).Guild; + this.question = question; + this.answers = enumerable as string[] ?? enumerable.ToArray(); + this.isPublic = isPublic; + } + + public async Task StartPoll() + { + started = DateTime.Now; + NadekoBot.Client.MessageReceived += Vote; + var msgToSend = $"๐Ÿ“ƒ**{originalMessage.Author.Username}** has created a poll which requires your attention:\n\n**{question}**\n"; + var num = 1; + msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); + if (!isPublic) + msgToSend += "\n**Private Message me with the corresponding number of the answer.**"; + else + msgToSend += "\n**Send a Message here with the corresponding number of the answer.**"; + await originalMessage.Channel.SendConfirmAsync(msgToSend).ConfigureAwait(false); + } + + public async Task StopPoll() + { + NadekoBot.Client.MessageReceived -= Vote; try { - IMessageChannel ch; - if (isPublic) - { - //if public, channel must be the same the poll started in - if (originalMessage.Channel.Id != Context.Channel.Id) - return; - ch = Context.Channel; - } - else - { - //if private, channel must be dm channel - if ((ch = Context.Channel as IDMChannel) == null) - return; + var results = participants.GroupBy(kvp => kvp.Value) + .ToDictionary(x => x.Key, x => x.Sum(kvp => 1)) + .OrderByDescending(kvp => kvp.Value); - // user must be a member of the guild this poll is in - var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); - if (!guildUsers.Any(u => u.Id == Context.User.Id)) - return; - } - - //user can vote only once - if (participants.TryAdd(Context.User.Id, vote)) + var totalVotesCast = results.Sum(kvp => kvp.Value); + if (totalVotesCast == 0) { - if (!isPublic) + await originalMessage.Channel.SendMessageAsync("๐Ÿ“„ **No votes have been cast.**").ConfigureAwait(false); + return; + } + var closeMessage = $"--------------**POLL CLOSED**--------------\n" + + $"๐Ÿ“„ , here are the results:\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 originalMessage.Channel.SendConfirmAsync($"๐Ÿ“„ **Total votes cast**: {totalVotesCast}\n{closeMessage}").ConfigureAwait(false); + } + catch (Exception ex) + { + Console.WriteLine($"Error in poll game {ex}"); + } + } + + private Task Vote(IMessage imsg) + { + // has to be a user message + var msg = imsg as IUserMessage; + if (msg == null || imsg.Author.IsBot) + return Task.CompletedTask; + + // has to be an integer + int vote; + if (!int.TryParse(imsg.Content, out vote)) + return Task.CompletedTask; + if (vote < 1 || vote > answers.Length) + return Task.CompletedTask; + + var t = Task.Run(async () => + { + try + { + IMessageChannel ch; + if (isPublic) { - await ch.SendConfirmAsync($"Thanks for voting **{Context.User.Username}**.").ConfigureAwait(false); + //if public, channel must be the same the poll started in + if (originalMessage.Channel.Id != imsg.Channel.Id) + return; + ch = imsg.Channel; } else { - var toDelete = await ch.SendConfirmAsync($"{Context.User.Mention} cast their vote.").ConfigureAwait(false); - await Task.Delay(5000); - await toDelete.DeleteAsync().ConfigureAwait(false); + //if private, channel must be dm channel + if ((ch = Context.Channel as IDMChannel) == null) + return; + + // user must be a member of the guild this poll is in + var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); + if (!guildUsers.Any(u => u.Id == Context.User.Id)) + return; + } + + //user can vote only once + if (participants.TryAdd(Context.User.Id, vote)) + { + if (!isPublic) + { + await ch.SendConfirmAsync($"Thanks for voting **{Context.User.Username}**.").ConfigureAwait(false); + } + else + { + var toDelete = await ch.SendConfirmAsync($"{Context.User.Mention} cast their vote.").ConfigureAwait(false); + await Task.Delay(5000); + await toDelete.DeleteAsync().ConfigureAwait(false); + } } } - } - catch { } - }); - return Task.CompletedTask; + catch { } + }); + return Task.CompletedTask; + } } } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index e2a33802..21b13112 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -107,7 +107,7 @@ namespace NadekoBot.Modules.Games private Task AnswerReceived(IMessage imsg) { - if (Context.User.IsBot) + if (imsg.Author.IsBot) return Task.CompletedTask; var msg = imsg as IUserMessage; if (msg == null) @@ -122,12 +122,12 @@ namespace NadekoBot.Modules.Games var distance = CurrentSentence.LevenshteinDistance(guess); var decision = Judge(distance, guess.Length); - if (decision && !finishedUserIds.Contains(Context.User.Id)) + if (decision && !finishedUserIds.Contains(imsg.Author.Id)) { var wpm = CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60; - finishedUserIds.Add(Context.User.Id); - await Extensions.Extensions.EmbedAsync(this.Channel, (Discord.API.Embed)new EmbedBuilder().WithColor((uint)NadekoBot.OkColor) - .WithTitle((string)$"{Context.User} finished the race!") + finishedUserIds.Add(imsg.Author.Id); + await Extensions.Extensions.EmbedAsync(this.Channel, new EmbedBuilder().WithColor(NadekoBot.OkColor) + .WithTitle((string)$"{imsg.Author} finished the race!") .AddField(efb => efb.WithName("Place").WithValue($"#{finishedUserIds.Count}").WithIsInline(true)) .AddField(efb => efb.WithName("WPM").WithValue($"{wpm:F2} *[{sw.Elapsed.Seconds.ToString()}sec]*").WithIsInline(true)) .AddField(efb => efb.WithName((string)"Errors").WithValue((string)distance.ToString()).WithIsInline((bool)true)) @@ -148,7 +148,7 @@ namespace NadekoBot.Modules.Games } [Group] - public class SpeedTypingCommands + public class SpeedTypingCommands : ModuleBase { public static List TypingArticles { get; } = new List(); @@ -205,7 +205,7 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Typeadd(IUserMessage imsg, [Remainder] string text) + public async Task Typeadd([Remainder] string text) { var channel = (ITextChannel)Context.Channel; @@ -222,7 +222,7 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Typelist(IUserMessage imsg, int page = 1) + public async Task Typelist(int page = 1) { var channel = (ITextChannel)Context.Channel; @@ -244,7 +244,7 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Typedel(IUserMessage imsg, int index) + public async Task Typedel(int index) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs index 27504087..ffa8e30d 100644 --- a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs @@ -14,18 +14,16 @@ namespace NadekoBot.Modules.Games public partial class Games { [Group] - public class TriviaCommands + public class TriviaCommands : ModuleBase { public static ConcurrentDictionary RunningTrivias = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Trivia(IUserMessage umsg, params string[] args) + public async Task Trivia(params string[] args) { - var channel = (ITextChannel)Context.Channel; - TriviaGame trivia; - if (!RunningTrivias.TryGetValue(channel.Guild.Id, out trivia)) + if (!RunningTrivias.TryGetValue(Context.Guild.Id, out trivia)) { var showHints = !args.Contains("nohint"); var number = args.Select(s => @@ -35,14 +33,14 @@ namespace NadekoBot.Modules.Games }).Where(t => t.Item1).Select(t => t.Item2).FirstOrDefault(); if (number < 0) return; - var triviaGame = new TriviaGame(channel.Guild, (ITextChannel)Context.Channel, showHints, number == 0 ? 10 : number); - if (RunningTrivias.TryAdd(channel.Guild.Id, triviaGame)) - await channel.SendConfirmAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); + var triviaGame = new TriviaGame(Context.Guild, (ITextChannel)Context.Channel, showHints, number == 0 ? 10 : number); + if (RunningTrivias.TryAdd(Context.Guild.Id, triviaGame)) + await Context.Channel.SendConfirmAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false); else await triviaGame.StopGame().ConfigureAwait(false); } else - await channel.SendErrorAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index bdf96a88..872ee207 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -27,40 +27,34 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Choose(IUserMessage umsg, [Remainder] string list = null) + public async Task Choose([Remainder] string list = null) { - var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(list)) return; var listArr = list.Split(';'); if (listArr.Count() < 2) return; var rng = new NadekoRandom(); - await channel.SendConfirmAsync("๐Ÿค”", listArr[rng.Next(0, listArr.Length)]).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿค”", listArr[rng.Next(0, listArr.Length)]).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task _8Ball(IUserMessage umsg, [Remainder] string question = null) + public async Task _8Ball([Remainder] string question = null) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(question)) return; var rng = new NadekoRandom(); - await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .AddField(efb => efb.WithName("โ“ Question").WithValue(question).WithIsInline(false)) - .AddField(efb => efb.WithName("๐ŸŽฑ 8Ball").WithValue(_8BallResponses.Shuffle().FirstOrDefault()).WithIsInline(false)) - ); + .AddField(efb => efb.WithName("๐ŸŽฑ 8Ball").WithValue(_8BallResponses.Shuffle().FirstOrDefault()).WithIsInline(false))); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Rps(IUserMessage umsg, string input) + public async Task Rps(string input) { - var channel = (ITextChannel)Context.Channel; - Func GetRPSPick = (p) => { if (p == 0) @@ -102,16 +96,14 @@ namespace NadekoBot.Modules.Games else msg = $"{Context.User.Mention} won! {GetRPSPick(pick)} beats {GetRPSPick(nadekoPick)}"; - await channel.SendConfirmAsync(msg).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(msg).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Linux(IUserMessage umsg, string guhnoo, string loonix) + public async Task Linux(string guhnoo, string loonix) { - var channel = (ITextChannel)Context.Channel; - - await channel.SendConfirmAsync( + await Context.Channel.SendConfirmAsync( $@"I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the {guhnoo} system every day, without realizing it. Through a peculiar turn of events, the version of {guhnoo} which is widely used today is often called {loonix}, and many of its users are not aware that it is basically the {guhnoo} system, developed by the {guhnoo} Project. diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index b2a8b9b0..b24685fd 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -51,11 +51,11 @@ namespace NadekoBot.Modules.Help if (string.IsNullOrWhiteSpace(module)) return; var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) - .OrderBy(c => c.Text) + .OrderBy(c => c.Aliases.First()) .Distinct(new CommandTextEqualityComparer()) .AsEnumerable(); - var cmdsArray = cmds as Command[] ?? cmds.ToArray(); + var cmdsArray = cmds as CommandInfo[] ?? cmds.ToArray(); if (!cmdsArray.Any()) { await channel.SendErrorAsync("That module does not exist.").ConfigureAwait(false); @@ -63,11 +63,11 @@ namespace NadekoBot.Modules.Help } if (module != "customreactions" && module != "conversations") { - await channel.SendTableAsync("๐Ÿ“ƒ **List Of Commands:**\n", cmdsArray, el => $"{el.Text,-15} {"["+el.Aliases.Skip(1).FirstOrDefault()+"]",-8}").ConfigureAwait(false); + await channel.SendTableAsync("๐Ÿ“ƒ **List Of Commands:**\n", cmdsArray, el => $"{el.Aliases.First(),-15} {"["+el.Aliases.Skip(1).FirstOrDefault()+"]",-8}").ConfigureAwait(false); } else { - await channel.SendMessageAsync("๐Ÿ“ƒ **List Of Commands:**\nโ€ข " + string.Join("\nโ€ข ", cmdsArray.Select(c => $"{c.Text}"))); + await channel.SendMessageAsync("๐Ÿ“ƒ **List Of Commands:**\nโ€ข " + string.Join("\nโ€ข ", cmdsArray.Select(c => $"{c.Aliases.First()}"))); } await channel.SendConfirmAsync($"โ„น๏ธ **Type** `\"{NadekoBot.ModulePrefixes[typeof(Help).Name]}h CommandName\"` **to see the help for that specified command.** ***e.g.*** `-h >8ball`").ConfigureAwait(false); } @@ -84,36 +84,37 @@ namespace NadekoBot.Modules.Help await ch.SendMessageAsync(HelpString).ConfigureAwait(false); return; } - var com = NadekoBot.CommandService.Commands.FirstOrDefault(c => c.Text.ToLowerInvariant() == comToFind || c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); + var com = NadekoBot.CommandService.Commands.FirstOrDefault(c => c.Aliases.Select(a=>a.ToLowerInvariant()).Contains(comToFind)); if (com == null) { await channel.SendErrorAsync("I can't find that command. Please check the **command** and **command prefix** before trying again."); return; } - var str = $"**`{com.Text}`**"; + var str = $"**`{com.Aliases.First()}`**"; var alias = com.Aliases.Skip(1).FirstOrDefault(); if (alias != null) str += $" **/ `{alias}`**"; var embed = new EmbedBuilder() - .AddField(fb => fb.WithIndex(1).WithName(str).WithValue($"{ string.Format(com.Summary, com.Module.Prefix)} { GetCommandRequirements(com)}").WithIsInline(true)) - .AddField(fb => fb.WithIndex(2).WithName("**Usage**").WithValue($"{string.Format(com.Remarks, com.Module.Prefix)}").WithIsInline(false)) + .AddField(fb => fb.WithName(str).WithValue($"{ string.Format(com.Summary, com.Module.Aliases.First())} { GetCommandRequirements(com)}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Usage**").WithValue($"{string.Format(com.Remarks, com.Module.Aliases.First())}").WithIsInline(false)) .WithColor(NadekoBot.OkColor); await channel.EmbedAsync(embed).ConfigureAwait(false); } - private string GetCommandRequirements(Command cmd) + private string GetCommandRequirements(CommandInfo cmd) { - return String.Join(" ", cmd.Source.CustomAttributes - .Where(ca => ca.AttributeType == typeof(OwnerOnlyAttribute) || ca.AttributeType == typeof(RequireUserPermissionAttribute)) + return String.Join(" ", cmd.Preconditions + .Where(ca => ca is OwnerOnlyAttribute || ca is RequireUserPermissionAttribute) .Select(ca => { - if (ca.AttributeType == typeof(OwnerOnlyAttribute)) + if (ca is OwnerOnlyAttribute) return "**Bot Owner only.**"; - else if (ca.AttributeType == typeof(RequireUserPermissionAttribute)) - return $"**Requires {(GuildPermission)ca.ConstructorArguments.FirstOrDefault().Value} server permission.**".Replace("Guild", "Server"); + var cau = (RequireUserPermissionAttribute)ca; + if (cau.GuildPermission != null) + return $"**Requires {cau.GuildPermission} server permission.**".Replace("Guild", "Server"); else - return $"**Requires {(GuildPermission)ca.ConstructorArguments.FirstOrDefault().Value} channel permission.**".Replace("Guild", "Server"); + return $"**Requires {cau.ChannelPermission} channel permission.**".Replace("Guild", "Server"); })); } @@ -128,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 NadekoBot.CommandService.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.Aliases.First()).Select(g => g.First())) { if (com.Module.Name != lastModule) { @@ -143,7 +144,7 @@ namespace NadekoBot.Modules.Help helpstr.AppendLine("----------------|--------------|-------"); lastModule = com.Module.Name; } - helpstr.AppendLine($"`{com.Text}` {string.Join(" ", com.Aliases.Skip(1).Select(a=>"`"+a+"`"))} | {string.Format(com.Summary, com.Module.Prefix)} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.Prefix)}"); + helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.Prefix)} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.Prefix)}"); } helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser().Username , "@BotName"); File.WriteAllText("../../docs/Commands List.md", helpstr.ToString()); @@ -176,11 +177,11 @@ Don't forget to leave your discord name or id in the message. } } - public class CommandTextEqualityComparer : IEqualityComparer + public class CommandTextEqualityComparer : IEqualityComparer { - public bool Equals(Command x, Command y) => x.Text == y.Text; + public bool Equals(CommandInfo x, CommandInfo y) => x.Aliases.First() == y.Aliases.First(); - public int GetHashCode(Command obj) => obj.Text.GetHashCode(); + public int GetHashCode(CommandInfo obj) => obj.Aliases.First().GetHashCode(); } } diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index d0a4dff5..3903c8a6 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -29,38 +29,38 @@ namespace NadekoBot.Modules.Music { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } - - NadekoBot.Client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated; + + NadekoBot.Client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated; Directory.CreateDirectory(MusicDataPath); } - - private Task Client_UserVoiceStateUpdated(IUser iusr, IVoiceState oldState, IVoiceState newState) + + private async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) { var usr = iusr as IGuildUser; if (usr == null || oldState.VoiceChannel == newState.VoiceChannel) - return Task.CompletedTask; + return; MusicPlayer player; if (!MusicPlayers.TryGetValue(usr.Guild.Id, out player)) - return Task.CompletedTask; + return; + var users = await player.PlaybackVoiceChannel.GetUsersAsync().Flatten().ConfigureAwait(false); if ((player.PlaybackVoiceChannel == newState.VoiceChannel && //if joined first, and player paused, unpause player.Paused && - player.PlaybackVoiceChannel.GetUsers().Count == 2) || // keep in mind bot is in the channel (+1) + users.Count() == 2) || // keep in mind bot is in the channel (+1) (player.PlaybackVoiceChannel == oldState.VoiceChannel && // if left last, and player unpaused, pause !player.Paused && - player.PlaybackVoiceChannel.GetUsers().Count == 1)) + users.Count() == 1)) { player.TogglePause(); } - return Task.CompletedTask; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Next(IUserMessage umsg, int skipCount = 1) + public Task Next(int skipCount = 1) { var channel = (ITextChannel)Context.Channel; @@ -126,7 +126,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Queue(IUserMessage umsg, [Remainder] string query) + public async Task Queue([Remainder] string query) { var channel = (ITextChannel)Context.Channel; @@ -134,13 +134,13 @@ namespace NadekoBot.Modules.Music if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); - await ((IUserMessage)umsg).DeleteAsync().ConfigureAwait(false); + await Context.Message.DeleteAsync().ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SoundCloudQueue(IUserMessage umsg, [Remainder] string query) + public async Task SoundCloudQueue([Remainder] string query) { var channel = (ITextChannel)Context.Channel; @@ -148,13 +148,13 @@ namespace NadekoBot.Modules.Music if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); - await ((IUserMessage)umsg).DeleteAsync().ConfigureAwait(false); + await Context.Message.DeleteAsync().ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ListQueue(IUserMessage umsg, int page = 1) + public async Task ListQueue(int page = 1) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -176,7 +176,7 @@ namespace NadekoBot.Modules.Music } //var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName} " + $"`{currentSong.PrettyCurrentTime()}`\n"; - var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName}\n"; + var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName}\n"; if (musicPlayer.RepeatSong) toSend += "๐Ÿ”‚"; else if (musicPlayer.RepeatPlaylist) @@ -197,40 +197,40 @@ namespace NadekoBot.Modules.Music public async Task NowPlaying() { var channel = (ITextChannel)Context.Channel; - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; var currentSong = musicPlayer.CurrentSong; if (currentSong == null) return; - var videoid = Regex.Match(currentSong.SongInfo.Query, "<=v=[a-zA-Z0-9-]+(?=&)|(?<=[0-9])[^&\n]+|(?<=v=)[^&\n]+"); + var videoid = Regex.Match(currentSong.SongInfo.Query, "<=v=[a-zA-Z0-9-]+(?=&)|(?<=[0-9])[^&\n]+|(?<=v=)[^&\n]+"); if (currentSong.TotalLength == TimeSpan.Zero) { await musicPlayer.UpdateSongDurationsAsync().ConfigureAwait(false); } - var embed = new EmbedBuilder() - .WithAuthor(eab => eab.WithName("Now Playing").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) - .WithTitle($"{currentSong.SongInfo.Title}") - .WithUrl($"{currentSong.SongInfo.Query}") - .WithDescription($"{currentSong.PrettyCurrentTime()}") - .WithFooter(ef => ef.WithText($"{currentSong.PrettyProvider} | {currentSong.PrettyUser}")) - .WithColor(NadekoBot.OkColor); - if (currentSong.SongInfo.Provider.Equals("YouTube", StringComparison.OrdinalIgnoreCase)) - { - embed.WithThumbnail(tn => tn.Url = $"https://img.youtube.com/vi/{videoid}/0.jpg"); - } - else if (currentSong.SongInfo.Provider.Equals("SoundCloud", StringComparison.OrdinalIgnoreCase)) - { - embed.WithThumbnail(tn => tn.Url = $"{currentSong.SongInfo.AlbumArt}"); - } - await channel.EmbedAsync(embed).ConfigureAwait(false); + var embed = new EmbedBuilder() + .WithAuthor(eab => eab.WithName("Now Playing").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) + .WithTitle($"{currentSong.SongInfo.Title}") + .WithUrl($"{currentSong.SongInfo.Query}") + .WithDescription($"{currentSong.PrettyCurrentTime()}") + .WithFooter(ef => ef.WithText($"{currentSong.PrettyProvider} | {currentSong.PrettyUser}")) + .WithColor(NadekoBot.OkColor); + if (currentSong.SongInfo.Provider.Equals("YouTube", StringComparison.OrdinalIgnoreCase)) + { + embed.WithThumbnailUrl($"https://img.youtube.com/vi/{videoid}/0.jpg"); + } + else if (currentSong.SongInfo.Provider.Equals("SoundCloud", StringComparison.OrdinalIgnoreCase)) + { + embed.WithThumbnailUrl($"{currentSong.SongInfo.AlbumArt}"); + } + await channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Volume(IUserMessage umsg, int val) + public async Task Volume(int val) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -246,7 +246,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Defvol(IUserMessage umsg, [Remainder] int val) + public async Task Defvol([Remainder] int val) { var channel = (ITextChannel)Context.Channel; @@ -285,7 +285,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Playlist(IUserMessage umsg, [Remainder] string playlist) + public async Task Playlist([Remainder] string playlist) { var channel = (ITextChannel)Context.Channel; var arg = playlist; @@ -326,7 +326,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SoundCloudPl(IUserMessage umsg, [Remainder] string pl) + public async Task SoundCloudPl([Remainder] string pl) { var channel = (ITextChannel)Context.Channel; pl = pl?.Trim(); @@ -364,7 +364,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task LocalPl(IUserMessage umsg, [Remainder] string directory) + public async Task LocalPl([Remainder] string directory) { var channel = (ITextChannel)Context.Channel; var arg = directory; @@ -394,7 +394,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Radio(IUserMessage umsg, string radio_link) + public async Task Radio(string radio_link) { var channel = (ITextChannel)Context.Channel; if (((IGuildUser)Context.User).VoiceChannel?.Guild != channel.Guild) @@ -406,14 +406,14 @@ namespace NadekoBot.Modules.Music if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); - await ((IUserMessage)umsg).DeleteAsync().ConfigureAwait(false); + await Context.Message.DeleteAsync().ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Local(IUserMessage umsg, [Remainder] string path) + public async Task Local([Remainder] string path) { var channel = (ITextChannel)Context.Channel; var arg = path; @@ -438,7 +438,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Remove(IUserMessage umsg, int num) + public async Task Remove(int num) { var channel = (ITextChannel)Context.Channel; @@ -459,7 +459,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Remove(IUserMessage umsg, string all) + public async Task Remove(string all) { var channel = (ITextChannel)Context.Channel; @@ -474,7 +474,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task MoveSong(IUserMessage umsg, [Remainder] string fromto) + public async Task MoveSong([Remainder] string fromto) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -502,14 +502,14 @@ namespace NadekoBot.Modules.Music playlist.Insert(n2 - 1, s); var nn1 = n2 < n1 ? n1 : n1 - 1; playlist.RemoveAt(nn1); - - var embed = new EmbedBuilder() - .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") - .WithUrl($"{s.SongInfo.Query}") - .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) - .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) - .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) - .WithColor(NadekoBot.OkColor); + + var embed = new EmbedBuilder() + .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") + .WithUrl($"{s.SongInfo.Query}") + .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) + .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) + .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) + .WithColor(NadekoBot.OkColor); await channel.EmbedAsync(embed).ConfigureAwait(false); //await channel.SendConfirmAsync($"๐ŸŽตMoved {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); @@ -519,7 +519,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SetMaxQueue(IUserMessage umsg, uint size) + public async Task SetMaxQueue(uint size) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -563,7 +563,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Save(IUserMessage umsg, [Remainder] string name) + public async Task Save([Remainder] string name) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -599,7 +599,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Load(IUserMessage umsg, [Remainder] int id) + public async Task Load([Remainder] int id) { var channel = (ITextChannel)Context.Channel; @@ -632,7 +632,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Playlists(IUserMessage umsg, [Remainder] int num = 1) + public async Task Playlists([Remainder] int num = 1) { var channel = (ITextChannel)Context.Channel; @@ -654,7 +654,7 @@ namespace NadekoBot.Modules.Music //todo only author or owner [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task DeletePlaylist(IUserMessage umsg, [Remainder] int id) + public async Task DeletePlaylist([Remainder] int id) { var channel = (ITextChannel)Context.Channel; @@ -692,7 +692,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Goto(IUserMessage umsg, int time) + public async Task Goto(int time) { var channel = (ITextChannel)Context.Channel; @@ -729,7 +729,7 @@ namespace NadekoBot.Modules.Music [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task GetLink(IUserMessage umsg, int index = 0) + public async Task GetLink(int index = 0) { var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; @@ -797,7 +797,7 @@ namespace NadekoBot.Modules.Music } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; - IUserMessage lastFinishedMessage = null; + IUserMessage lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) @@ -829,7 +829,7 @@ namespace NadekoBot.Modules.Music try { playingMessage = await textCh.SendConfirmAsync(msgTxt).ConfigureAwait(false); } catch { } } }; - mp.OnPauseChanged += async (paused) => + mp.OnPauseChanged += async (paused) => { try { diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 8b856b1b..c6913a56 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -21,11 +21,8 @@ namespace NadekoBot.Modules.NSFW } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Hentai(IUserMessage umsg, [Remainder] string tag = null) + public async Task Hentai([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; tag = "rating%3Aexplicit+" + tag; @@ -51,17 +48,14 @@ namespace NadekoBot.Modules.NSFW } var link = await provider.ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task HentaiBomb(IUserMessage umsg, [Remainder] string tag = null) + public async Task HentaiBomb([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; tag = "rating%3Aexplicit+" + tag; @@ -72,11 +66,11 @@ namespace NadekoBot.Modules.NSFW if (links.All(l => l == null)) { - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(String.Join("\n\n", links)).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(String.Join("\n\n", links)).ConfigureAwait(false); } public static async Task GetYandereImageLink(string tag) @@ -99,103 +93,80 @@ namespace NadekoBot.Modules.NSFW } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Yandere(IUserMessage umsg, [Remainder] string tag = null) + public async Task Yandere([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetYandereImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Danbooru(IUserMessage umsg, [Remainder] string tag = null) + public async Task Danbooru([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetDanbooruImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Konachan(IUserMessage umsg, [Remainder] string tag = null) + public async Task Konachan([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetKonachanImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Gelbooru(IUserMessage umsg, [Remainder] string tag = null) + public async Task Gelbooru([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetGelbooruImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Rule34(IUserMessage umsg, [Remainder] string tag = null) + public async Task Rule34([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetRule34ImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task E621(IUserMessage umsg, [Remainder] string tag = null) + public async Task E621([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetE621ImageLink(tag).ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) - await channel.SendErrorAsync("No results found.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found.").ConfigureAwait(false); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Cp() { - var channel = (ITextChannel)Context.Channel; - - await channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Boobs() { - var channel = (ITextChannel)Context.Channel; try { JToken obj; @@ -203,20 +174,17 @@ namespace NadekoBot.Modules.NSFW { obj = JArray.Parse(await http.GetStringAsync($"http://api.oboobs.ru/boobs/{ new NadekoRandom().Next(0, 10229) }").ConfigureAwait(false))[0]; } - await channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync(ex.Message).ConfigureAwait(false); + await Context.Channel.SendErrorAsync(ex.Message).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Butts() { - var channel = (ITextChannel)Context.Channel; - try { JToken obj; @@ -224,11 +192,11 @@ namespace NadekoBot.Modules.NSFW { obj = JArray.Parse(await http.GetStringAsync($"http://api.obutts.ru/butts/{ new NadekoRandom().Next(0, 4222) }").ConfigureAwait(false))[0]; } - await channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync(ex.Message).ConfigureAwait(false); + await Context.Channel.SendErrorAsync(ex.Message).ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index b9b32b56..4097783d 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -56,7 +56,7 @@ namespace NadekoBot.Modules.Permissions { var cc = new CommandCooldown() { - CommandName = command.Text.ToLowerInvariant(), + CommandName = command.Aliases.First().ToLowerInvariant(), Seconds = secs, }; config.CommandCooldowns.Add(cc); @@ -67,7 +67,7 @@ namespace NadekoBot.Modules.Permissions if (secs == 0) { var activeCds = activeCooldowns.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); - activeCds.RemoveWhere(ac => ac.Command == command.Text.ToLowerInvariant()); + activeCds.RemoveWhere(ac => ac.Command == command.Aliases.First().ToLowerInvariant()); await channel.SendConfirmAsync($"๐Ÿšฎ Command **{command}** has no coooldown now and all existing cooldowns have been cleared.") .ConfigureAwait(false); } @@ -91,16 +91,16 @@ namespace NadekoBot.Modules.Permissions await channel.SendTableAsync("", localSet.Select(c => c.CommandName + ": " + c.Seconds + " secs"), s => $"{s,-30}", 2).ConfigureAwait(false); } - public static bool HasCooldown(Command cmd, IGuild guild, IUser user) + public static bool HasCooldown(CommandInfo cmd, IGuild guild, IUser user) { if (guild == null) return false; var cmdcds = CmdCdsCommands.commandCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); CommandCooldown cdRule; - if ((cdRule = cmdcds.FirstOrDefault(cc => cc.CommandName == cmd.Text.ToLowerInvariant())) != null) + if ((cdRule = cmdcds.FirstOrDefault(cc => cc.CommandName == cmd.Aliases.First().ToLowerInvariant())) != null) { var activeCdsForGuild = activeCooldowns.GetOrAdd(guild.Id, new ConcurrentHashSet()); - if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == cmd.Text.ToLowerInvariant()) != null) + if (activeCdsForGuild.FirstOrDefault(ac => ac.UserId == user.Id && ac.Command == cmd.Aliases.First().ToLowerInvariant()) != null) { return true; } @@ -109,14 +109,14 @@ namespace NadekoBot.Modules.Permissions activeCdsForGuild.Add(new ActiveCooldown() { UserId = user.Id, - Command = cmd.Text.ToLowerInvariant(), + Command = cmd.Aliases.First().ToLowerInvariant(), }); var t = Task.Run(async () => { try { await Task.Delay(cdRule.Seconds * 1000); - activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Text.ToLowerInvariant() && ac.UserId == user.Id); + activeCdsForGuild.RemoveWhere(ac => ac.Command == cmd.Aliases.First().ToLowerInvariant() && ac.UserId == user.Id); } catch { } }); From 3d196e3b1f90a66845cf29326860a88a158ef1a0 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 20:53:47 +0100 Subject: [PATCH 06/30] module stuff --- .gitmodules | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitmodules b/.gitmodules index 0f1296be..1996477a 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "discord.net"] path = discord.net url = https://github.com/kwoth/discord.net - branch = dev + branch = rogue-dev From 0b2ea8254208ef0d14cfe2012d83049ff71485f5 Mon Sep 17 00:00:00 2001 From: samvaio Date: Sat, 17 Dec 2016 03:14:26 +0530 Subject: [PATCH 07/30] beta ups --- .../Modules/Administration/Administration.cs | 2 +- .../Commands/AntiRaidCommands.cs | 32 +++---- .../Commands/AutoAssignRoleCommands.cs | 8 +- .../Commands/CrossServerTextChannel.cs | 14 +-- .../Commands/DMForwardCommands.cs | 12 +-- .../Administration/Commands/LogCommand.cs | 84 +++++++++--------- .../Commands/MessageRepeater.cs | 20 ++--- .../Administration/Commands/Migration.cs | 2 +- .../Administration/Commands/MuteCommands.cs | 48 +++++----- .../Commands/RatelimitCommand.cs | 12 +-- .../Commands/SelfAssignedRolesCommand.cs | 64 +++++++------- .../Administration/Commands/SelfCommands.cs | 8 +- .../Commands/ServerGreetCommands.cs | 88 +++++++++---------- .../Commands/VoicePlusTextCommands.cs | 22 ++--- .../Modules/ClashOfClans/ClashOfClans.cs | 74 ++++++++-------- .../CustomReactions/CustomReactions.cs | 39 ++++---- .../Modules/Gambling/Commands/AnimalRacing.cs | 12 +-- .../Gambling/Commands/DiceRollCommand.cs | 30 +++---- .../Modules/Gambling/Commands/DrawCommand.cs | 14 +-- .../Gambling/Commands/FlipCoinCommand.cs | 18 ++-- src/NadekoBot/Modules/Gambling/Gambling.cs | 55 ++++++------ 21 files changed, 336 insertions(+), 322 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index bacb683d..7b4ad467 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -53,7 +53,7 @@ namespace NadekoBot.Modules.Administration bool shouldDelete; using (var uow = DbHandler.UnitOfWork()) { - shouldDelete = uow.GuildConfigs.For(channel.Guild.Id, set => set).DeleteMessageOnCommand; + shouldDelete = uow.GuildConfigs.For(Context.Guild.Id, set => set).DeleteMessageOnCommand; } if (shouldDelete) diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 14fd957a..53cfdce1 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -87,7 +87,7 @@ namespace NadekoBot.Modules.Administration if (msg == null || Context.User.IsBot) return Task.CompletedTask; - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -96,7 +96,7 @@ namespace NadekoBot.Modules.Administration try { AntiSpamSetting spamSettings; - if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings)) + if (!antiSpamGuilds.TryGetValue(Context.Guild.Id, out spamSettings)) return; var stats = spamSettings.UserStats.AddOrUpdate(Context.User.Id, new UserSpamStats(msg.Content), @@ -199,27 +199,27 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiRaid(IUserMessage imsg, int userThreshold, int seconds, PunishmentAction action) { - var channel = (ITextChannel)Context.Channel; + ////var channel = (ITextChannel)Context.Channel; if (userThreshold < 2 || userThreshold > 30) { - await channel.SendErrorAsync("โ—๏ธUser threshold must be between **2** and **30**.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โ—๏ธUser threshold must be between **2** and **30**.").ConfigureAwait(false); return; } if (seconds < 2 || seconds > 300) { - await channel.SendErrorAsync("โ—๏ธTime must be between **2** and **300** seconds.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โ—๏ธTime must be between **2** and **300** seconds.").ConfigureAwait(false); return; } try { - await MuteCommands.GetMuteRole(channel.Guild).ConfigureAwait(false); + await MuteCommands.GetMuteRole(Context.Guild).ConfigureAwait(false); } catch (Exception ex) { - await channel.SendConfirmAsync("โš ๏ธ Failed creating a mute role. Give me ManageRoles permission" + + await Context.Channel.SendConfirmAsync("โš ๏ธ Failed creating a mute role. Give me ManageRoles permission" + "or create 'nadeko-mute' role with disabled SendMessages and try again.") .ConfigureAwait(false); _log.Warn(ex); @@ -232,9 +232,9 @@ namespace NadekoBot.Modules.Administration Seconds = seconds, UserThreshold = userThreshold, }; - antiRaidGuilds.AddOrUpdate(channel.Guild.Id, setting, (id, old) => setting); + antiRaidGuilds.AddOrUpdate(Context.Guild.Id, setting, (id, old) => setting); - await channel.SendConfirmAsync($"โ„น๏ธ {Context.User.Mention} If **{userThreshold}** or more users join within **{seconds}** seconds, I will **{action}** them.") + await Context.Channel.SendConfirmAsync($"โ„น๏ธ {Context.User.Mention} If **{userThreshold}** or more users join within **{seconds}** seconds, I will **{action}** them.") .ConfigureAwait(false); } @@ -243,37 +243,37 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiSpam(IUserMessage imsg, int messageCount=3, PunishmentAction action = PunishmentAction.Mute) { - var channel = (ITextChannel)Context.Channel; + ////var channel = (ITextChannel)Context.Channel; if (messageCount < 2 || messageCount > 10) return; AntiSpamSetting throwaway; - if (antiSpamGuilds.TryRemove(channel.Guild.Id, out throwaway)) + if (antiSpamGuilds.TryRemove(Context.Guild.Id, out throwaway)) { - await channel.SendConfirmAsync("๐Ÿ†— **Anti-Spam feature** has been **disabled** on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **Anti-Spam feature** has been **disabled** on this server.").ConfigureAwait(false); } else { try { - await MuteCommands.GetMuteRole(channel.Guild).ConfigureAwait(false); + await MuteCommands.GetMuteRole(Context.Guild).ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync("โš ๏ธ Failed creating a mute role. Give me ManageRoles permission" + + await Context.Channel.SendErrorAsync("โš ๏ธ Failed creating a mute role. Give me ManageRoles permission" + "or create 'nadeko-mute' role with disabled SendMessages and try again.") .ConfigureAwait(false); _log.Warn(ex); return; } - if (antiSpamGuilds.TryAdd(channel.Guild.Id, new AntiSpamSetting() + if (antiSpamGuilds.TryAdd(Context.Guild.Id, new AntiSpamSetting() { Action = action, MessageThreshold = messageCount, })) - await channel.SendConfirmAsync("โœ… **Anti-Spam feature** has been **enabled** on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **Anti-Spam feature** has been **enabled** on this server.").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 1009936c..3342e6c2 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -48,12 +48,12 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task AutoAssignRole(IUserMessage umsg, [Remainder] IRole role = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; GuildConfig conf; using (var uow = DbHandler.UnitOfWork()) { - conf = uow.GuildConfigs.For(channel.Guild.Id, set => set); + conf = uow.GuildConfigs.For(Context.Guild.Id, set => set); if (role == null) conf.AutoAssignRoleId = 0; else @@ -64,11 +64,11 @@ namespace NadekoBot.Modules.Administration if (role == null) { - await channel.SendConfirmAsync("๐Ÿ†— **Auto assign role** on user join is now **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **Auto assign role** on user join is now **disabled**.").ConfigureAwait(false); return; } - await channel.SendConfirmAsync("โœ… **Auto assign role** on user join is now **enabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **Auto assign role** on user join is now **enabled**.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index d7f517b5..81a10732 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Administration if (msg == null) return Task.CompletedTask; - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Administration continue; foreach (var chan in set.Except(new[] { channel })) { - try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)Context.User, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await chan.SendMessageAsync(GetText(Context.Guild, channel, (IGuildUser)Context.User, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } } }); @@ -61,7 +61,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task Scsc() { - var channel = (ITextChannel)Context.Channel; + ////var channel = (ITextChannel)Context.Channel; var token = new NadekoRandom().Next(); var set = new ConcurrentHashSet(); if (Subscribers.TryAdd(token, set)) @@ -76,13 +76,13 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Jcsc(IUserMessage imsg, int token) { - var channel = (ITextChannel)Context.Channel; + ////var channel = (ITextChannel)Context.Channel; ConcurrentHashSet set; if (!Subscribers.TryGetValue(token, out set)) return; set.Add(channel); - await channel.SendConfirmAsync("Joined cross server channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Joined cross server channel.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -90,13 +90,13 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Lcsc() { - var channel = (ITextChannel)Context.Channel; + ////var channel = (ITextChannel)Context.Channel; foreach (var subscriber in Subscribers) { subscriber.Value.TryRemove(channel); } - await channel.SendMessageAsync("Left cross server channel.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("Left cross server channel.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs index cc304cf8..a808510e 100644 --- a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs @@ -31,7 +31,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task ForwardMessages() { - var channel = Context.Channel; + //var channel = Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -40,16 +40,16 @@ namespace NadekoBot.Modules.Administration uow.Complete(); } if (ForwardDMs) - await channel.SendConfirmAsync("โœ… **I will forward DMs from now on.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **I will forward DMs from now on.**").ConfigureAwait(false); else - await channel.SendConfirmAsync("๐Ÿ†— **I will stop forwarding DMs from now on.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— **I will stop forwarding DMs from now on.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] public async Task ForwardToAll() { - var channel = Context.Channel; + //var channel = Context.Channel; using (var uow = DbHandler.UnitOfWork()) { @@ -58,9 +58,9 @@ namespace NadekoBot.Modules.Administration uow.Complete(); } if (ForwardDMsToAllOwners) - await channel.SendConfirmAsync("โ„น๏ธ **I will forward DMs to all owners.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ **I will forward DMs to all owners.**").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ **I will forward DMs only to the first owner.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ **I will forward DMs only to the first owner.**").ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 2113d064..938ff9d8 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -469,19 +469,19 @@ namespace NadekoBot.Modules.Administration if (msg == null || msg.IsAuthor()) return Task.CompletedTask; - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(Context.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.MessageDeleted || logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == channel.Id)) return Task.CompletedTask; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(channel.Guild, logSetting)) == null || logChannel.Id == msg.Id) + if ((logChannel = TryGetLogChannel(Context.Guild, logSetting)) == null || logChannel.Id == msg.Id) return Task.CompletedTask; var task = Task.Run(async () => @@ -510,19 +510,19 @@ namespace NadekoBot.Modules.Administration if (before == null) return Task.CompletedTask; - var channel = after.Channel as ITextChannel; + //var channel = after.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(Context.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.MessageUpdated || logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == channel.Id)) return Task.CompletedTask; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(channel.Guild, logSetting)) == null || logChannel.Id == after.Channel.Id) + if ((logChannel = TryGetLogChannel(Context.Guild, logSetting)) == null || logChannel.Id == after.Channel.Id) return Task.CompletedTask; var task = Task.Run(async () => @@ -553,7 +553,7 @@ namespace NadekoBot.Modules.Administration id = logSetting.UserPresenceChannelId; break; } - var channel = guild.GetTextChannel(id); + //var channel = guild.GetTextChannel(id); if (channel == null) using (var uow = DbHandler.UnitOfWork()) @@ -585,12 +585,12 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogServer() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; LogSetting logSetting; using (var uow = DbHandler.UnitOfWork()) { - logSetting = uow.GuildConfigs.For(channel.Guild.Id).LogSetting; - GuildLogSettings.AddOrUpdate(channel.Guild.Id, (id) => logSetting, (id, old) => logSetting); + logSetting = uow.GuildConfigs.For(Context.Guild.Id).LogSetting; + GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); logSetting.IsLogging = !logSetting.IsLogging; if (logSetting.IsLogging) logSetting.ChannelId = channel.Id; @@ -598,9 +598,9 @@ namespace NadekoBot.Modules.Administration } if (logSetting.IsLogging) - await channel.SendMessageAsync("โœ… **Logging enabled.**").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("โœ… **Logging enabled.**").ConfigureAwait(false); else - await channel.SendMessageAsync("โ„น๏ธ **Logging disabled.**").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("โ„น๏ธ **Logging disabled.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -609,12 +609,12 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogIgnore() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id); - LogSetting logSetting = GuildLogSettings.GetOrAdd(channel.Guild.Id, (id) => config.LogSetting); + var config = uow.GuildConfigs.For(Context.Guild.Id); + LogSetting logSetting = GuildLogSettings.GetOrAdd(Context.Guild.Id, (id) => config.LogSetting); removed = logSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == channel.Id); config.LogSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == channel.Id); if (removed == 0) @@ -627,9 +627,9 @@ namespace NadekoBot.Modules.Administration } if (removed == 0) - await channel.SendMessageAsync($"๐Ÿ†— Logging will **now ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"๐Ÿ†— Logging will **now ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); else - await channel.SendMessageAsync($"โ„น๏ธ Logging will **no longer ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โ„น๏ธ Logging will **no longer ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); } //[LocalizedCommand, LocalizedRemarks, LocalizedSummary, LocalizedAlias] @@ -637,7 +637,7 @@ namespace NadekoBot.Modules.Administration //[OwnerOnly] //public async Task LogAdd([Remainder] string eventName) //{ - // var channel = (ITextChannel)Context.Channel; + // //var channel = (ITextChannel)Context.Channel; // //eventName = eventName?.Replace(" ","").ToLowerInvariant(); // switch (eventName.ToLowerInvariant()) @@ -653,16 +653,16 @@ namespace NadekoBot.Modules.Administration // case "channelupdated": // using (var uow = DbHandler.UnitOfWork()) // { - // var logSetting = uow.GuildConfigs.For(channel.Guild.Id).LogSetting; - // GuildLogSettings.AddOrUpdate(channel.Guild.Id, (id) => logSetting, (id, old) => logSetting); + // var logSetting = uow.GuildConfigs.For(Context.Guild.Id).LogSetting; + // GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); // var prop = logSetting.GetType().GetProperty(eventName); // prop.SetValue(logSetting, true); // await uow.CompleteAsync().ConfigureAwait(false); // } - // await channel.SendMessageAsync($"`Now logging {eventName} event.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`Now logging {eventName} event.`").ConfigureAwait(false); // break; // default: - // await channel.SendMessageAsync($"`Event \"{eventName}\" not found.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`Event \"{eventName}\" not found.`").ConfigureAwait(false); // break; // } //} @@ -671,7 +671,7 @@ namespace NadekoBot.Modules.Administration //[RequireContext(ContextType.Guild)] //public async Task LogRemove(string eventName) //{ - // var channel = (ITextChannel)Context.Channel; + // //var channel = (ITextChannel)Context.Channel; // eventName = eventName.ToLowerInvariant(); // switch (eventName) @@ -688,16 +688,16 @@ namespace NadekoBot.Modules.Administration // case "channelupdated": // using (var uow = DbHandler.UnitOfWork()) // { - // var config = uow.GuildConfigs.For(channel.Guild.Id); - // LogSetting logSetting = GuildLogSettings.GetOrAdd(channel.Guild.Id, (id) => config.LogSetting); + // var config = uow.GuildConfigs.For(Context.Guild.Id); + // LogSetting logSetting = GuildLogSettings.GetOrAdd(Context.Guild.Id, (id) => config.LogSetting); // logSetting.GetType().GetProperty(eventName).SetValue(logSetting, false); // config.LogSetting = logSetting; // await uow.CompleteAsync().ConfigureAwait(false); // } - // await channel.SendMessageAsync($"`No longer logging {eventName} event.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`No longer logging {eventName} event.`").ConfigureAwait(false); // break; // default: - // await channel.SendMessageAsync($"`Event \"{eventName}\" not found.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`Event \"{eventName}\" not found.`").ConfigureAwait(false); // break; // } //} @@ -707,12 +707,12 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task UserPresence() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { - var logSetting = uow.GuildConfigs.For(channel.Guild.Id).LogSetting; - GuildLogSettings.AddOrUpdate(channel.Guild.Id, (id) => logSetting, (id, old) => logSetting); + var logSetting = uow.GuildConfigs.For(Context.Guild.Id).LogSetting; + GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); enabled = logSetting.LogUserPresence = !logSetting.LogUserPresence; if(enabled) logSetting.UserPresenceChannelId = channel.Id; @@ -720,9 +720,9 @@ namespace NadekoBot.Modules.Administration } if (enabled) - await channel.SendMessageAsync($"โœ… Logging **user presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โœ… Logging **user presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); else - await channel.SendMessageAsync($"โ„น๏ธ Stopped logging **user presence** updates.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โ„น๏ธ Stopped logging **user presence** updates.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -730,14 +730,14 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task VoicePresence() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { - var logSetting = uow.GuildConfigs.For(channel.Guild.Id, set => set.Include(gc => gc.LogSetting) + var logSetting = uow.GuildConfigs.For(Context.Guild.Id, set => set.Include(gc => gc.LogSetting) .ThenInclude(ls => ls.IgnoredVoicePresenceChannelIds)) .LogSetting; - GuildLogSettings.AddOrUpdate(channel.Guild.Id, (id) => logSetting, (id, old) => logSetting); + GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); enabled = logSetting.LogVoicePresence = !logSetting.LogVoicePresence; if (enabled) logSetting.VoicePresenceChannelId = channel.Id; @@ -745,21 +745,21 @@ namespace NadekoBot.Modules.Administration } if (enabled) - await channel.SendMessageAsync($"โœ… Logging **voice presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โœ… Logging **voice presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); else - await channel.SendMessageAsync($"โ„น๏ธ Stopped logging **voice presence** updates.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โ„น๏ธ Stopped logging **voice presence** updates.").ConfigureAwait(false); } //[LocalizedCommand, LocalizedDescription, LocalizedSummary, LocalizedAlias] //[RequireContext(ContextType.Guild)] //public async Task VoiPresIgnore(IUserMessage imsg, IVoiceChannel voiceChannel) //{ - // var channel = (ITextChannel)Context.Channel; + // //var channel = (ITextChannel)Context.Channel; // int removed; // using (var uow = DbHandler.UnitOfWork()) // { - // var config = uow.GuildConfigs.For(channel.Guild.Id); - // LogSetting logSetting = GuildLogSettings.GetOrAdd(channel.Guild.Id, (id) => config.LogSetting); + // var config = uow.GuildConfigs.For(Context.Guild.Id); + // LogSetting logSetting = GuildLogSettings.GetOrAdd(Context.Guild.Id, (id) => config.LogSetting); // removed = logSetting.IgnoredVoicePresenceChannelIds.RemoveWhere(ivpc => ivpc.ChannelId == voiceChannel.Id); // if (removed == 0) // logSetting.IgnoredVoicePresenceChannelIds.Add(new IgnoredVoicePresenceChannel { ChannelId = voiceChannel.Id }); @@ -768,9 +768,9 @@ namespace NadekoBot.Modules.Administration // } // if (removed == 0) - // await channel.SendMessageAsync($"`Enabled logging voice presence updates for {voiceChannel.Name} ({voiceChannel.Id}) channel.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`Enabled logging voice presence updates for {voiceChannel.Name} ({voiceChannel.Id}) channel.`").ConfigureAwait(false); // else - // await channel.SendMessageAsync($"`Disabled logging voice presence updates for {voiceChannel.Name} ({voiceChannel.Id}) channel.`").ConfigureAwait(false); + // await Context.Channel.SendMessageAsync($"`Disabled logging voice presence updates for {voiceChannel.Name} ({voiceChannel.Id}) channel.`").ConfigureAwait(false); //} } } diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 9e0975af..54e480fe 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -53,7 +53,7 @@ namespace NadekoBot.Modules.Administration await Task.Delay(Repeater.Interval, token).ConfigureAwait(false); if (oldMsg != null) try { await oldMsg.DeleteAsync(); } catch { } - try { oldMsg = await Channel.SendMessageAsync("๐Ÿ”„ " + Repeater.Message).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); try { source.Cancel(); } catch { } } + try { oldMsg = await Context.Channel.SendMessageAsync("๐Ÿ”„ " + Repeater.Message).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); try { source.Cancel(); } catch { } } } } catch (OperationCanceledException) { } @@ -84,16 +84,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task RepeatInvoke() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; RepeatRunner rep; if (!repeaters.TryGetValue(channel.Id, out rep)) { - await channel.SendErrorAsync("โ„น๏ธ **No repeating message found on this server.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โ„น๏ธ **No repeating message found on this server.**").ConfigureAwait(false); return; } rep.Reset(); - await channel.SendMessageAsync("๐Ÿ”„ " + rep.Repeater.Message).ConfigureAwait(false); + await Context.Channel.SendMessageAsync("๐Ÿ”„ " + rep.Repeater.Message).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Repeat() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; RepeatRunner rep; if (repeaters.TryRemove(channel.Id, out rep)) { @@ -111,10 +111,10 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } rep.Stop(); - await channel.SendConfirmAsync("โœ… **Stopped repeating a message.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… **Stopped repeating a message.**").ConfigureAwait(false); } else - await channel.SendConfirmAsync("โ„น๏ธ **No message is repeating.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ **No message is repeating.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -122,7 +122,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (minutes < 1 || minutes > 10080) return; @@ -139,7 +139,7 @@ namespace NadekoBot.Modules.Administration var localRep = new Repeater { ChannelId = channel.Id, - GuildId = channel.Guild.Id, + GuildId = Context.Guild.Id, Interval = TimeSpan.FromMinutes(minutes), Message = message, }; @@ -160,7 +160,7 @@ namespace NadekoBot.Modules.Administration return old; }); - await channel.SendConfirmAsync($"๐Ÿ” Repeating **\"{rep.Repeater.Message}\"** every `{rep.Repeater.Interval.Days} day(s), {rep.Repeater.Interval.Hours} hour(s) and {rep.Repeater.Interval.Minutes} minute(s)`.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ” Repeating **\"{rep.Repeater.Message}\"** every `{rep.Repeater.Interval.Days} day(s), {rep.Repeater.Interval.Hours} hour(s) and {rep.Repeater.Interval.Minutes} minute(s)`.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/Migration.cs b/src/NadekoBot/Modules/Administration/Commands/Migration.cs index a16dad79..59509501 100644 --- a/src/NadekoBot/Modules/Administration/Commands/Migration.cs +++ b/src/NadekoBot/Modules/Administration/Commands/Migration.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task MigrateData() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var version = 0; using (var uow = DbHandler.UnitOfWork()) diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index 1efe2e90..481e8d5c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -141,19 +141,19 @@ namespace NadekoBot.Modules.Administration [Priority(1)] public async Task SetMuteRole(IUserMessage imsg, [Remainder] string name) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; name = name.Trim(); if (string.IsNullOrWhiteSpace(name)) return; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); config.MuteRoleName = name; - GuildMuteRoles.AddOrUpdate(channel.Guild.Id, name, (id, old) => name); + GuildMuteRoles.AddOrUpdate(Context.Guild.Id, name, (id, old) => name); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync("โ˜‘๏ธ **New mute role set.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ˜‘๏ธ **New mute role set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -169,16 +169,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.MuteMembers)] public async Task Mute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { await Mute(user).ConfigureAwait(false); - await channel.SendConfirmAsync($"๐Ÿ”‡ **{user}** has been **muted** from text and voice chat.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ”‡ **{user}** has been **muted** from text and voice chat.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } @@ -188,16 +188,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.MuteMembers)] public async Task Unmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { await Unmute(user).ConfigureAwait(false); - await channel.SendConfirmAsync($"๐Ÿ”‰ **{user}** has been **unmuted** from text and voice chat.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ”‰ **{user}** has been **unmuted** from text and voice chat.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } @@ -206,17 +206,17 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task ChatMute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { - await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); + await user.AddRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); await UserMuted(user, MuteType.Chat).ConfigureAwait(false); - await channel.SendConfirmAsync($"โœ๏ธ๐Ÿšซ **{user}** has been **muted** from chatting.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ๏ธ๐Ÿšซ **{user}** has been **muted** from chatting.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } @@ -225,17 +225,17 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task ChatUnmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { - await user.RemoveRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); + await user.RemoveRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); await UserUnmuted(user, MuteType.Chat).ConfigureAwait(false); - await channel.SendConfirmAsync($"โœ๏ธโœ… **{user}** has been **unmuted** from chatting.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ๏ธโœ… **{user}** has been **unmuted** from chatting.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } @@ -244,17 +244,17 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceMute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false); await UserMuted(user, MuteType.Voice).ConfigureAwait(false); - await channel.SendConfirmAsync($"๐ŸŽ™๐Ÿšซ **{user}** has been **voice muted**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽ™๐Ÿšซ **{user}** has been **voice muted**.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } @@ -263,16 +263,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.MuteMembers)] public async Task VoiceUnmute(IUserMessage umsg, IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { await user.ModifyAsync(usr => usr.Mute = false).ConfigureAwait(false); await UserUnmuted(user, MuteType.Voice).ConfigureAwait(false); - await channel.SendConfirmAsync($"๐ŸŽ™โœ… **{user}** has been **voice unmuted**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽ™โœ… **{user}** has been **voice unmuted**.").ConfigureAwait(false); } catch { - await channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ I most likely don't have the permission necessary for that.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 610b3bb7..1fecbd91 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Administration var t = Task.Run(async () => { var usrMsg = umsg as IUserMessage; - var channel = usrContext.Channel as ITextChannel; + //var channel = usrContext.Channel as ITextChannel; if (channel == null || usrMsg.IsAuthor()) return; @@ -88,13 +88,13 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Slowmode() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; Ratelimiter throwaway; if (RatelimitingChannels.TryRemove(channel.Id, out throwaway)) { throwaway.cancelSource.Cancel(); - await channel.SendConfirmAsync("โ„น๏ธ Slow mode disabled.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Slow mode disabled.").ConfigureAwait(false); return; } } @@ -105,11 +105,11 @@ namespace NadekoBot.Modules.Administration public async Task Slowmode(IUserMessage umsg, int msg, int perSec) { await Slowmode(umsg).ConfigureAwait(false); // disable if exists - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (msg < 1 || perSec < 1 || msg > 100 || perSec > 3600) { - await channel.SendErrorAsync("โš ๏ธ Invalid parameters."); + await Context.Channel.SendErrorAsync("โš ๏ธ Invalid parameters."); return; } var toAdd = new Ratelimiter() @@ -120,7 +120,7 @@ namespace NadekoBot.Modules.Administration }; if(RatelimitingChannels.TryAdd(channel.Id, toAdd)) { - await channel.SendConfirmAsync("Slow mode initiated", + await Context.Channel.SendConfirmAsync("Slow mode initiated", $"Users can't send more than `{toAdd.MaxMessages} message(s)` every `{toAdd.PerSeconds} second(s)`.") .ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs index e05a7a09..55319653 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -24,16 +24,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task AdSarm() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; bool newval; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); newval = config.AutoDeleteSelfAssignedRoleMessages = !config.AutoDeleteSelfAssignedRoleMessages; await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"โ„น๏ธ Automatic deleting of `iam` and `iamn` confirmations has been {(newval ? "**enabled**" : "**disabled**")}.") + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Automatic deleting of `iam` and `iamn` confirmations has been {(newval ? "**enabled**" : "**disabled**")}.") .ConfigureAwait(false); } @@ -42,17 +42,17 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task Asar(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; IEnumerable roles; string msg; using (var uow = DbHandler.UnitOfWork()) { - roles = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id); + roles = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id); if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.GuildId)) { - await channel.SendMessageAsync($"๐Ÿ’ข Role **{role.Name}** is already in the list.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"๐Ÿ’ข Role **{role.Name}** is already in the list.").ConfigureAwait(false); return; } else @@ -65,7 +65,7 @@ namespace NadekoBot.Modules.Administration msg = $"๐Ÿ†— Role **{role.Name}** added to the list."; } } - await channel.SendConfirmAsync(msg.ToString()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(msg.ToString()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task Rsar(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; bool success; using (var uow = DbHandler.UnitOfWork()) @@ -83,17 +83,17 @@ namespace NadekoBot.Modules.Administration } if (!success) { - await channel.SendErrorAsync("โŽ That role is not self-assignable.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โŽ That role is not self-assignable.").ConfigureAwait(false); return; } - await channel.SendConfirmAsync($"๐Ÿ—‘ **{role.Name}** has been removed from the list of self-assignable roles.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ **{role.Name}** has been removed from the list of self-assignable roles.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Lsar() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var toRemove = new ConcurrentHashSet(); var removeMsg = new StringBuilder(); @@ -101,13 +101,13 @@ namespace NadekoBot.Modules.Administration var roleCnt = 0; using (var uow = DbHandler.UnitOfWork()) { - var roleModels = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id).ToList(); + var roleModels = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id).ToList(); roleCnt = roleModels.Count; msg.AppendLine(); foreach (var roleModel in roleModels) { - var role = channel.Guild.Roles.FirstOrDefault(r => r.Id == roleModel.RoleId); + var role = Context.Guild.Roles.FirstOrDefault(r => r.Id == roleModel.RoleId); if (role == null) { uow.SelfAssignedRoles.Remove(roleModel); @@ -123,7 +123,7 @@ namespace NadekoBot.Modules.Administration } await uow.CompleteAsync(); } - await channel.SendConfirmAsync($"โ„น๏ธ There are `{roleCnt}` self assignable roles:", msg.ToString() + "\n\n" + removeMsg.ToString()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ There are `{roleCnt}` self assignable roles:", msg.ToString() + "\n\n" + removeMsg.ToString()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -131,25 +131,25 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task Tesar() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; bool areExclusive; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); areExclusive = config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles; await uow.CompleteAsync(); } string exl = areExclusive ? "**exclusive**." : "**not exclusive**."; - await channel.SendConfirmAsync("โ„น๏ธ Self assigned roles are now " + exl); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Self assigned roles are now " + exl); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Iam(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; var usrMsg = (IUserMessage)umsg; @@ -157,18 +157,18 @@ namespace NadekoBot.Modules.Administration IEnumerable roles; using (var uow = DbHandler.UnitOfWork()) { - conf = uow.GuildConfigs.For(channel.Guild.Id, set => set); - roles = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id); + conf = uow.GuildConfigs.For(Context.Guild.Id, set => set); + roles = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id); } SelfAssignedRole roleModel; if ((roleModel = roles.FirstOrDefault(r=>r.RoleId == role.Id)) == null) { - await channel.SendErrorAsync("That role is not self-assignable.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("That role is not self-assignable.").ConfigureAwait(false); return; } if (guildUser.Roles.Contains(role)) { - await channel.SendErrorAsync($"You already have **{role.Name}** role.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"You already have **{role.Name}** role.").ConfigureAwait(false); return; } @@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Administration var sameRoles = guildUser.Roles.Where(r => roles.Any(rm => rm.RoleId == r.Id)); if (sameRoles.Any()) { - await channel.SendErrorAsync($"You already have **{sameRoles.FirstOrDefault().Name}** `exclusive self-assigned` role.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"You already have **{sameRoles.FirstOrDefault().Name}** `exclusive self-assigned` role.").ConfigureAwait(false); return; } } @@ -187,11 +187,11 @@ namespace NadekoBot.Modules.Administration } catch (Exception ex) { - await channel.SendErrorAsync($"โš ๏ธ I am unable to add that role to you. `I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"โš ๏ธ I am unable to add that role to you. `I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); Console.WriteLine(ex); return; } - var msg = await channel.SendConfirmAsync($"๐Ÿ†— You now have **{role.Name}** role.").ConfigureAwait(false); + var msg = await Context.Channel.SendConfirmAsync($"๐Ÿ†— You now have **{role.Name}** role.").ConfigureAwait(false); if (conf.AutoDeleteSelfAssignedRoleMessages) { @@ -208,25 +208,25 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] public async Task Iamnot(IUserMessage umsg, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; bool autoDeleteSelfAssignedRoleMessages; IEnumerable roles; using (var uow = DbHandler.UnitOfWork()) { - autoDeleteSelfAssignedRoleMessages = uow.GuildConfigs.For(channel.Guild.Id, set => set).AutoDeleteSelfAssignedRoleMessages; - roles = uow.SelfAssignedRoles.GetFromGuild(channel.Guild.Id); + autoDeleteSelfAssignedRoleMessages = uow.GuildConfigs.For(Context.Guild.Id, set => set).AutoDeleteSelfAssignedRoleMessages; + roles = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id); } SelfAssignedRole roleModel; if ((roleModel = roles.FirstOrDefault(r => r.RoleId == role.Id)) == null) { - await channel.SendErrorAsync("๐Ÿ’ข That role is not self-assignable.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ’ข That role is not self-assignable.").ConfigureAwait(false); return; } if (!guildUser.Roles.Contains(role)) { - await channel.SendErrorAsync($"โŽ You don't have **{role.Name}** role.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"โŽ You don't have **{role.Name}** role.").ConfigureAwait(false); return; } try @@ -235,10 +235,10 @@ namespace NadekoBot.Modules.Administration } catch (Exception) { - await channel.SendErrorAsync($"โš ๏ธ I am unable to add that role to you. `I can't remove roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"โš ๏ธ I am unable to add that role to you. `I can't remove roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false); return; } - var msg = await channel.SendConfirmAsync($"๐Ÿ†— You no longer have **{role.Name}** role.").ConfigureAwait(false); + var msg = await Context.Channel.SendConfirmAsync($"๐Ÿ†— You no longer have **{role.Name}** role.").ConfigureAwait(false); if (autoDeleteSelfAssignedRoleMessages) { diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index 9b888321..a671d73e 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task Leave(IUserMessage umsg, [Remainder] string guildStr) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; guildStr = guildStr.Trim().ToUpperInvariant(); var server = _client.GetGuilds().FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == guildStr) ?? @@ -32,18 +32,18 @@ namespace NadekoBot.Modules.Administration if (server == null) { - await channel.SendErrorAsync("โš ๏ธ Cannot find that server").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โš ๏ธ Cannot find that server").ConfigureAwait(false); return; } if (server.OwnerId != _client.CurrentUser().Id) { await server.LeaveAsync().ConfigureAwait(false); - await channel.SendConfirmAsync("โœ… Left server " + server.Name).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Left server " + server.Name).ConfigureAwait(false); } else { await server.DeleteAsync().ConfigureAwait(false); - await channel.SendConfirmAsync("Deleted server " + server.Name).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Deleted server " + server.Name).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index 96dcf125..5309f750 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Administration } if (!conf.SendChannelByeMessage) return; - var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId); + //var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId); if (channel == null) //maybe warn the server owner that the channel is missing return; @@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Administration return; try { - var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); + var toDelete = await Context.Channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); if (conf.AutoDeleteByeMessagesTimer > 0) { var t = Task.Run(async () => @@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Administration if (conf.SendChannelGreetMessage) { - var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.GreetMessageChannelId); + //var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.GreetMessageChannelId); if (channel != null) //maybe warn the server owner that the channel is missing { var msg = conf.ChannelGreetMessageText.Replace("%user%", user.Mention).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name); @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Administration { try { - var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); + var toDelete = await Context.Channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); if (conf.AutoDeleteGreetMessagesTimer > 0) { var t = Task.Run(async () => @@ -105,14 +105,14 @@ namespace NadekoBot.Modules.Administration if (conf.SendDmGreetMessage) { - var channel = await user.CreateDMChannelAsync(); + //var channel = await user.CreateDMChannelAsync(); if (channel != null) { var msg = conf.DmGreetMessageText.Replace("%user%", user.Username).Replace("%server%", user.Guild.Name); if (!string.IsNullOrWhiteSpace(msg)) { - await channel.SendConfirmAsync(msg).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(msg).ConfigureAwait(false); } } } @@ -127,16 +127,16 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDel(IUserMessage umsg, int timer = 30) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (timer < 0 || timer > 600) return; - await ServerGreetCommands.SetGreetDel(channel.Guild.Id, timer).ConfigureAwait(false); + await ServerGreetCommands.SetGreetDel(Context.Guild.Id, timer).ConfigureAwait(false); if (timer > 0) - await channel.SendConfirmAsync($"๐Ÿ†— Greet messages **will be deleted** after `{timer} seconds`.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ†— Greet messages **will be deleted** after `{timer} seconds`.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ Automatic deletion of greet messages has been **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Automatic deletion of greet messages has been **disabled**.").ConfigureAwait(false); } private static async Task SetGreetDel(ulong id, int timer) @@ -158,14 +158,14 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Greet() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - var enabled = await ServerGreetCommands.SetGreet(channel.Guild.Id, channel.Id).ConfigureAwait(false); + var enabled = await ServerGreetCommands.SetGreet(Context.Guild.Id, channel.Id).ConfigureAwait(false); if (enabled) - await channel.SendConfirmAsync("โœ… Greeting messages **enabled** on this channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Greeting messages **enabled** on this channel.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ Greeting messages **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Greeting messages **disabled**.").ConfigureAwait(false); } private static async Task SetGreet(ulong guildId, ulong channelId, bool? value = null) @@ -187,24 +187,24 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { string channelGreetMessageText; using (var uow = DbHandler.UnitOfWork()) { - channelGreetMessageText = uow.GuildConfigs.For(channel.Guild.Id, set => set).ChannelGreetMessageText; + channelGreetMessageText = uow.GuildConfigs.For(Context.Guild.Id, set => set).ChannelGreetMessageText; } - await channel.SendConfirmAsync("Current greet message: ", channelGreetMessageText?.SanitizeMentions()); + await Context.Channel.SendConfirmAsync("Current greet message: ", channelGreetMessageText?.SanitizeMentions()); return; } - var sendGreetEnabled = ServerGreetCommands.SetGreetMessage(channel.Guild.Id, ref text); + var sendGreetEnabled = ServerGreetCommands.SetGreetMessage(Context.Guild.Id, ref text); - await channel.SendConfirmAsync("๐Ÿ†— New greet message **set**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— New greet message **set**.").ConfigureAwait(false); if (!sendGreetEnabled) - await channel.SendConfirmAsync("โ„น๏ธ Enable greet messsages by typing `.greet`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Enable greet messsages by typing `.greet`").ConfigureAwait(false); } public static bool SetGreetMessage(ulong guildId, ref string message) @@ -231,14 +231,14 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDm() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - var enabled = await ServerGreetCommands.SetGreetDm(channel.Guild.Id).ConfigureAwait(false); + var enabled = await ServerGreetCommands.SetGreetDm(Context.Guild.Id).ConfigureAwait(false); if (enabled) - await channel.SendConfirmAsync("๐Ÿ†— DM Greet announcements **enabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— DM Greet announcements **enabled**.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ Greet announcements **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Greet announcements **disabled**.").ConfigureAwait(false); } private static async Task SetGreetDm(ulong guildId, bool? value = null) @@ -259,24 +259,24 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDmMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { GuildConfig config; using (var uow = DbHandler.UnitOfWork()) { - config = uow.GuildConfigs.For(channel.Guild.Id); + config = uow.GuildConfigs.For(Context.Guild.Id); } - await channel.SendConfirmAsync("โ„น๏ธ Current **DM greet** message: `" + config.DmGreetMessageText?.SanitizeMentions() + "`"); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Current **DM greet** message: `" + config.DmGreetMessageText?.SanitizeMentions() + "`"); return; } - var sendGreetEnabled = ServerGreetCommands.SetGreetDmMessage(channel.Guild.Id, ref text); + var sendGreetEnabled = ServerGreetCommands.SetGreetDmMessage(Context.Guild.Id, ref text); - await channel.SendConfirmAsync("๐Ÿ†— New DM greet message **set**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— New DM greet message **set**.").ConfigureAwait(false); if (!sendGreetEnabled) - await channel.SendConfirmAsync($"โ„น๏ธ Enable DM greet messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}greetdm`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Enable DM greet messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}greetdm`").ConfigureAwait(false); } public static bool SetGreetDmMessage(ulong guildId, ref string message) @@ -303,14 +303,14 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Bye() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - var enabled = await ServerGreetCommands.SetBye(channel.Guild.Id, channel.Id).ConfigureAwait(false); + var enabled = await ServerGreetCommands.SetBye(Context.Guild.Id, channel.Id).ConfigureAwait(false); if (enabled) - await channel.SendConfirmAsync("โœ… Bye announcements **enabled** on this channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Bye announcements **enabled** on this channel.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ Bye announcements **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Bye announcements **disabled**.").ConfigureAwait(false); } private static async Task SetBye(ulong guildId, ulong channelId, bool? value = null) @@ -332,24 +332,24 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task ByeMsg(IUserMessage umsg, [Remainder] string text = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(text)) { string byeMessageText; using (var uow = DbHandler.UnitOfWork()) { - byeMessageText = uow.GuildConfigs.For(channel.Guild.Id, set => set).ChannelByeMessageText; + byeMessageText = uow.GuildConfigs.For(Context.Guild.Id, set => set).ChannelByeMessageText; } - await channel.SendConfirmAsync("โ„น๏ธ Current **bye** message: `" + byeMessageText?.SanitizeMentions() + "`"); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Current **bye** message: `" + byeMessageText?.SanitizeMentions() + "`"); return; } - var sendByeEnabled = ServerGreetCommands.SetByeMessage(channel.Guild.Id, ref text); + var sendByeEnabled = ServerGreetCommands.SetByeMessage(Context.Guild.Id, ref text); - await channel.SendConfirmAsync("๐Ÿ†— New bye message **set**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— New bye message **set**.").ConfigureAwait(false); if (!sendByeEnabled) - await channel.SendConfirmAsync($"โ„น๏ธ Enable bye messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}bye`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Enable bye messsages by typing `{NadekoBot.ModulePrefixes[typeof(Administration).Name]}bye`").ConfigureAwait(false); } public static bool SetByeMessage(ulong guildId, ref string message) @@ -376,14 +376,14 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task ByeDel(IUserMessage umsg, int timer = 30) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - await ServerGreetCommands.SetByeDel(channel.Guild.Id, timer).ConfigureAwait(false); + await ServerGreetCommands.SetByeDel(Context.Guild.Id, timer).ConfigureAwait(false); if (timer > 0) - await channel.SendConfirmAsync($"๐Ÿ†— Bye messages **will be deleted** after `{timer} seconds`.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ†— Bye messages **will be deleted** after `{timer} seconds`.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โ„น๏ธ Automatic deletion of bye messages has been **disabled**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Automatic deletion of bye messages has been **disabled**.").ConfigureAwait(false); } private static async Task SetByeDel(ulong id, int timer) diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 0abb0527..70172381 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -110,13 +110,13 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageChannels)] public async Task VoicePlusText() { - var channel = (ITextChannel)Context.Channel; - var guild = channel.Guild; + //var channel = (ITextChannel)Context.Channel; + var guild = Context.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); if (!botUser.GuildPermissions.ManageRoles || !botUser.GuildPermissions.ManageChannels) { - await channel.SendErrorAsync("I require atleast **manage roles** and **manage channels permissions** to enable this feature. `(preffered Administration permission)`"); + await Context.Channel.SendErrorAsync("I require atleast **manage roles** and **manage channels permissions** to enable this feature. `(preffered Administration permission)`"); return; } @@ -124,7 +124,7 @@ namespace NadekoBot.Modules.Administration { try { - await channel.SendErrorAsync("โš ๏ธ You are enabling this feature and **I do not have ADMINISTRATOR permissions**. " + + await Context.Channel.SendErrorAsync("โš ๏ธ You are enabling this feature and **I do not have ADMINISTRATOR permissions**. " + "`This may cause some issues, and you will have to clean up text channels yourself afterwards.`"); } catch { } @@ -145,16 +145,16 @@ namespace NadekoBot.Modules.Administration { try { await textChannel.DeleteAsync().ConfigureAwait(false); } catch { } } - await channel.SendConfirmAsync("โ„น๏ธ Successfuly **removed** voice + text feature.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ Successfuly **removed** voice + text feature.").ConfigureAwait(false); return; } voicePlusTextCache.Add(guild.Id); - await channel.SendConfirmAsync("๐Ÿ†— Successfuly **enabled** voice + text feature.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ†— Successfuly **enabled** voice + text feature.").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync(ex.ToString()).ConfigureAwait(false); + await Context.Channel.SendErrorAsync(ex.ToString()).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] @@ -163,12 +163,12 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task CleanVPlusT() { - var channel = (ITextChannel)Context.Channel; - var guild = channel.Guild; + //var channel = (ITextChannel)Context.Channel; + var guild = Context.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); if (!botUser.GuildPermissions.Administrator) { - await channel.SendErrorAsync("I need **Administrator permission** to do that.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("I need **Administrator permission** to do that.").ConfigureAwait(false); return; } @@ -183,7 +183,7 @@ namespace NadekoBot.Modules.Administration await Task.Delay(500); } - await channel.SendConfirmAsync("Cleaned v+t.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Cleaned v+t.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 7364c63b..357d2cd7 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task CreateWar(IUserMessage umsg, int size, [Remainder] string enemyClan = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) return; @@ -69,29 +69,32 @@ namespace NadekoBot.Modules.ClashOfClans if (size < 10 || size > 50 || size % 5 != 0) { - await channel.SendErrorAsync("๐Ÿ”ฐ Not a Valid war size").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ Not a Valid war size").ConfigureAwait(false); return; } List wars; - if (!ClashWars.TryGetValue(channel.Guild.Id, out wars)) + //if (!ClashWars.TryGetValue(channel.Guild.Id, out wars)) + if (!ClashWars.TryGetValue(Context.Guild.Id, out wars)) { wars = new List(); - if (!ClashWars.TryAdd(channel.Guild.Id, wars)) + if (!ClashWars.TryAdd(Context.Guild.Id, wars)) + //if (!ClashWars.TryAdd(channel.Guild.Id, wars)) return; } - var cw = await CreateWar(enemyClan, size, channel.Guild.Id, Context.Channel.Id); + var cw = await CreateWar(enemyClan, size, Context.Guild.Id, Context.Channel.Id); + //var cw = await CreateWar(enemyClan, size, channel.Guild.Id, Context.Channel.Id); wars.Add(cw); - await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task StartWar(IUserMessage umsg, [Remainder] string number = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; int num = 0; int.TryParse(number, out num); @@ -99,18 +102,18 @@ namespace NadekoBot.Modules.ClashOfClans var warsInfo = GetWarInfo(umsg, num); if (warsInfo == null) { - await channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); return; } var war = warsInfo.Item1[warsInfo.Item2]; try { war.Start(); - await channel.SendConfirmAsync($"๐Ÿ”ฐ**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ”ฐ**STARTED WAR AGAINST {war.ShortPrint()}**").ConfigureAwait(false); } catch { - await channel.SendErrorAsync($"๐Ÿ”ฐ**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"๐Ÿ”ฐ**WAR AGAINST {war.ShortPrint()} HAS ALREADY STARTED**").ConfigureAwait(false); } SaveWar(war); } @@ -119,17 +122,18 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ListWar(IUserMessage umsg, [Remainder] string number = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; // if number is null, print all wars in a short way if (string.IsNullOrWhiteSpace(number)) { //check if there are any wars List wars = null; - ClashWars.TryGetValue(channel.Guild.Id, out wars); + ClashWars.TryGetValue(Context.Guild.Id, out wars); + //ClashWars.TryGetValue(channel.Guild.Id, out wars); if (wars == null || wars.Count == 0) { - await channel.SendErrorAsync("๐Ÿ”ฐ **No active wars.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **No active wars.**").ConfigureAwait(false); return; } @@ -142,7 +146,7 @@ namespace NadekoBot.Modules.ClashOfClans sb.AppendLine($"\t\t`Size:` **{wars[i].Size} v {wars[i].Size}**"); sb.AppendLine("**-------------------------**"); } - await channel.SendConfirmAsync(sb.ToString()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(sb.ToString()).ConfigureAwait(false); return; } @@ -152,21 +156,21 @@ namespace NadekoBot.Modules.ClashOfClans var warsInfo = GetWarInfo(umsg, num); if (warsInfo == null) { - await channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); return; } - await channel.SendConfirmAsync(warsInfo.Item1[warsInfo.Item2].ToPrettyString()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(warsInfo.Item1[warsInfo.Item2].ToPrettyString()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Claim(IUserMessage umsg, int number, int baseNumber, [Remainder] string other_name = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { - await channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); return; } var usr = @@ -178,11 +182,11 @@ namespace NadekoBot.Modules.ClashOfClans var war = warsInfo.Item1[warsInfo.Item2]; war.Call(usr, baseNumber - 1); SaveWar(war); - await channel.SendConfirmAsync($"๐Ÿ”ฐ**{usr}** claimed a base #{baseNumber} for a war against {war.ShortPrint()}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ”ฐ**{usr}** claimed a base #{baseNumber} for a war against {war.ShortPrint()}").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); } } @@ -190,7 +194,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish1(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1, 1); } @@ -198,7 +202,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish2(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1, 2); } @@ -206,7 +210,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ClaimFinish(IUserMessage umsg, int number, int baseNumber = 0) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; await FinishClaim(umsg, number, baseNumber - 1); } @@ -214,18 +218,18 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task EndWar(IUserMessage umsg, int number) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg,number); if (warsInfo == null) { - await channel.SendErrorAsync("๐Ÿ”ฐ That war does not exist.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ That war does not exist.").ConfigureAwait(false); return; } var war = warsInfo.Item1[warsInfo.Item2]; war.End(); SaveWar(war); - await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**War against {warsInfo.Item1[warsInfo.Item2].ShortPrint()} ended.**").ConfigureAwait(false); var size = warsInfo.Item1[warsInfo.Item2].Size; warsInfo.Item1.RemoveAt(warsInfo.Item2); @@ -235,12 +239,12 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task Unclaim(IUserMessage umsg, int number, [Remainder] string otherName = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var warsInfo = GetWarInfo(umsg, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { - await channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); return; } var usr = @@ -252,21 +256,21 @@ namespace NadekoBot.Modules.ClashOfClans var war = warsInfo.Item1[warsInfo.Item2]; var baseNumber = war.Uncall(usr); SaveWar(war); - await channel.SendConfirmAsync($"๐Ÿ”ฐ @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ”ฐ @{usr} has **UNCLAIMED** a base #{baseNumber + 1} from a war against {war.ShortPrint()}").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); } } private async Task FinishClaim(IUserMessage umsg, int number, int baseNumber, int stars = 3) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var warInfo = GetWarInfo(umsg, number); if (warInfo == null || warInfo.Item1.Count == 0) { - await channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); return; } var war = warInfo.Item1[warInfo.Item2]; @@ -281,17 +285,17 @@ namespace NadekoBot.Modules.ClashOfClans { war.FinishClaim(baseNumber, stars); } - await channel.SendConfirmAsync($"โ—๐Ÿ”ฐ{Context.User.Mention} **DESTROYED** a base #{baseNumber + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ—๐Ÿ”ฐ{Context.User.Mention} **DESTROYED** a base #{baseNumber + 1} in a war against {war.ShortPrint()}").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"๐Ÿ”ฐ {ex.Message}").ConfigureAwait(false); } } private static Tuple, int> GetWarInfo(IUserMessage umsg, int num) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; //check if there are any wars List wars = null; ClashWars.TryGetValue(Context.Guild.Id, out wars); diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 71bb62bc..81aa2a43 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -35,13 +35,14 @@ namespace NadekoBot.Modules.CustomReactions public static async Task TryExecuteCustomReaction() { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (channel == null) return false; var content = umsg.Content.Trim().ToLowerInvariant(); ConcurrentHashSet reactions; - GuildReactions.TryGetValue(channel.Guild.Id, out reactions); + //GuildReactions.TryGetValue(channel.Guild.Id, out reactions); + GuildReactions.TryGetValue(Context.Guild.Id, out reactions); if (reactions != null && reactions.Any()) { var reaction = reactions.Where(cr => @@ -53,7 +54,7 @@ namespace NadekoBot.Modules.CustomReactions if (reaction != null) { if (reaction.Response != "-") - try { await channel.SendMessageAsync(reaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } + try { await Context.Channel.SendMessageAsync(reaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } ReactionStats.AddOrUpdate(reaction.Trigger, 1, (k, old) => ++old); return true; @@ -68,7 +69,7 @@ namespace NadekoBot.Modules.CustomReactions if (greaction != null) { - try { await channel.SendMessageAsync(greaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } + try { await Context.Channel.SendMessageAsync(greaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } ReactionStats.AddOrUpdate(greaction.Trigger, 1, (k, old) => ++old); return true; } @@ -78,7 +79,7 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task AddCustReact(IUserMessage imsg, string key, [Remainder] string message) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(key)) return; @@ -111,7 +112,8 @@ namespace NadekoBot.Modules.CustomReactions } else { - var reactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + var reactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); + //var reactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); reactions.Add(cr); } @@ -127,7 +129,7 @@ namespace NadekoBot.Modules.CustomReactions [Priority(0)] public async Task ListCustReact(IUserMessage imsg, int page = 1) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (page < 1 || page > 1000) return; @@ -135,7 +137,8 @@ namespace NadekoBot.Modules.CustomReactions if (channel == null) customReactions = GlobalReactions; else - customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); + //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -158,13 +161,14 @@ namespace NadekoBot.Modules.CustomReactions [Priority(1)] public async Task ListCustReact(IUserMessage imsg, All x) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; ConcurrentHashSet customReactions; if (channel == null) customReactions = GlobalReactions; else - customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); + //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -186,14 +190,15 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task ListCustReactG(IUserMessage imsg, int page = 1) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if (page < 1 || page > 10000) return; ConcurrentHashSet customReactions; if (channel == null) customReactions = GlobalReactions; else - customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); + //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -211,13 +216,14 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task ShowCustReact(IUserMessage imsg, int id) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; ConcurrentHashSet customReactions; if (channel == null) customReactions = GlobalReactions; else - customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); + customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); + //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); var found = customReactions.FirstOrDefault(cr => cr.Id == id); @@ -236,7 +242,7 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task DelCustReact(IUserMessage imsg, int id) { - var channel = Context.Channel as ITextChannel; + //var channel = Context.Channel as ITextChannel; if ((channel == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { @@ -261,7 +267,8 @@ namespace NadekoBot.Modules.CustomReactions else if ((toDelete.GuildId != null && toDelete.GuildId != 0) && channel?.Guild.Id == toDelete.GuildId) { uow.CustomReactions.Remove(toDelete); - GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()).RemoveWhere(cr => cr.Id == toDelete.Id); + GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()).RemoveWhere(cr => cr.Id == toDelete.Id); + //GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()).RemoveWhere(cr => cr.Id == toDelete.Id); success = true; } if (success) diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index 926903f8..f45ab74b 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -24,28 +24,28 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Race() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - var ar = new AnimalRace(channel.Guild.Id, channel); + var ar = new AnimalRace(Context.Guild.Id, channel); if (ar.Fail) - await channel.SendErrorAsync("๐Ÿ `Failed starting a race. Another race is probably running.`"); + await Context.Channel.SendErrorAsync("๐Ÿ `Failed starting a race. Another race is probably running.`"); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task JoinRace(IUserMessage umsg, int amount = 0) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount < 0) amount = 0; AnimalRace ar; - if (!AnimalRaces.TryGetValue(channel.Guild.Id, out ar)) + if (!AnimalRaces.TryGetValue(Context.Guild.Id, out ar)) { - await channel.SendErrorAsync("No race exists on this server"); + await Context.Channel.SendErrorAsync("No race exists on this server"); return; } await ar.JoinRace(Context.User as IGuildUser, amount); diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index 06571677..a83b08fb 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Roll() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (channel == null) return; var rng = new NadekoRandom(); @@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Gambling catch { return new MemoryStream(); } }); - await channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); + await Context.Channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } //todo merge into internallDndRoll and internalRoll [NadekoCommand, Usage, Description, Aliases] @@ -52,7 +52,7 @@ namespace NadekoBot.Modules.Gambling [Priority(1)] public async Task Roll(IUserMessage umsg, string arg) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; - await channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Gambling [Priority(0)] public async Task Roll(IUserMessage umsg, int num) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -96,7 +96,7 @@ namespace NadekoBot.Modules.Gambling if (num < 1 || num > 30) { - await channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } @@ -134,14 +134,14 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, string arg) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -167,7 +167,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = rng.Next(1, n2 + 1) + add - sub; } var elemCnt = 0; - await channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); } } } @@ -176,7 +176,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Rolluo(IUserMessage umsg, int num) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -184,7 +184,7 @@ namespace NadekoBot.Modules.Gambling if (num < 1 || num > 30) { - await channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } @@ -222,14 +222,14 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task NRoll(IUserMessage umsg, [Remainder] string range) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; try { @@ -249,11 +249,11 @@ namespace NadekoBot.Modules.Gambling rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } - await channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index 53571526..19acfc47 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -33,8 +33,8 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Draw(int num = 1) { - var channel = (ITextChannel)Context.Channel; - var cards = AllDecks.GetOrAdd(channel.Guild, (s) => new Cards()); + //var channel = (ITextChannel)Context.Channel; + var cards = AllDecks.GetOrAdd(Context.Guild, (s) => new Cards()); var images = new List(); var cardObjects = new List(); if (num > 5) num = 5; @@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Gambling { if (cards.CardPool.Count == 0 && i != 0) { - try { await channel.SendErrorAsync("No more cards in a deck.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await Context.Channel.SendErrorAsync("No more cards in a deck.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } break; } var currentCard = cards.DrawACard(); @@ -58,16 +58,16 @@ namespace NadekoBot.Modules.Gambling if (cardObjects.Count == 5) toSend += $" drew `{Cards.GetHandValue(cardObjects)}`"; - await channel.SendFileAsync(bitmapStream, images.Count + " cards.jpg", toSend).ConfigureAwait(false); + await Context.Channel.SendFileAsync(bitmapStream, images.Count + " cards.jpg", toSend).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ShuffleDeck() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - AllDecks.AddOrUpdate(channel.Guild, + AllDecks.AddOrUpdate(Context.Guild, (g) => new Cards(), (g, c) => { @@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Gambling return c; }); - await channel.SendConfirmAsync("Deck reshuffled.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Deck reshuffled.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 66fb228e..554bcfef 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -23,18 +23,18 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Flip(IUserMessage imsg, int count = 1) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (count == 1) { if (rng.Next(0, 2) == 1) - await channel.SendFileAsync(headsPath, $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false); + await Context.Channel.SendFileAsync(headsPath, $"{Context.User.Mention} flipped " + Format.Code("Heads") + ".").ConfigureAwait(false); else - await channel.SendFileAsync(tailsPath, $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false); + await Context.Channel.SendFileAsync(tailsPath, $"{Context.User.Mention} flipped " + Format.Code("Tails") + ".").ConfigureAwait(false); return; } if (count > 10 || count < 1) { - await channel.SendErrorAsync("`Invalid number specified. You can flip 1 to 10 coins.`"); + await Context.Channel.SendErrorAsync("`Invalid number specified. You can flip 1 to 10 coins.`"); return; } var imgs = new Image[count]; @@ -44,14 +44,14 @@ namespace NadekoBot.Modules.Gambling new Image(File.OpenRead(headsPath)) : new Image(File.OpenRead(tailsPath)); } - await channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false); + await Context.Channel.SendFileAsync(imgs.Merge().ToStream(), $"{count} coins.png").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Betflip(IUserMessage umsg, int amount, string guess) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; var guessStr = guess.Trim().ToUpperInvariant(); if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS") @@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Gambling if (amount < 3) { - await channel.SendErrorAsync($"You can't bet less than 3{Gambling.CurrencySign}.") + await Context.Channel.SendErrorAsync($"You can't bet less than 3{Gambling.CurrencySign}.") .ConfigureAwait(false); return; } @@ -72,7 +72,7 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); return; } @@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Gambling str = $"{Context.User.Mention}`Better luck next time.`"; } - await channel.SendFileAsync(imgPathToSend, str).ConfigureAwait(false); + await Context.Channel.SendFileAsync(imgPathToSend, str).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 066d4fd1..d60a45d9 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -44,51 +44,52 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Raffle(IUserMessage umsg, [Remainder] IRole role = null) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; - role = role ?? channel.Guild.EveryoneRole; + //role = role ?? channel.Guild.EveryoneRole; + role = role ?? Context.Guild.EveryoneRole; var members = role.Members().Where(u => u.Status != UserStatus.Offline && u.Status != UserStatus.Unknown); var membersArray = members as IUser[] ?? members.ToArray(); var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)]; - await channel.SendConfirmAsync("๐ŸŽŸ Raffled user", $"**{usr.Username}#{usr.Discriminator}** ID: `{usr.Id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐ŸŽŸ Raffled user", $"**{usr.Username}#{usr.Discriminator}** ID: `{usr.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] public async Task Cash(IUserMessage umsg, [Remainder] IUser user = null) { - var channel = Context.Channel; + //var channel = Context.Channel; user = user ?? Context.User; - await channel.SendConfirmAsync($"{user.Username} has {GetCurrency(user.Id)} {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{user.Username} has {GetCurrency(user.Id)} {CurrencySign}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Cash(IUserMessage umsg, ulong userId) { - var channel = Context.Channel; + //var channel = Context.Channel; - await channel.SendConfirmAsync($"`{userId}` has {GetCurrency(userId)} {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"`{userId}` has {GetCurrency(userId)} {CurrencySign}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Give(IUserMessage umsg, long amount, [Remainder] IGuildUser receiver) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount <= 0 || Context.User.Id == receiver.Id) return; var success = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, $"Gift to {receiver.Username} ({receiver.Id}).", amount, true).ConfigureAwait(false); if (!success) { - await channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); return; } await CurrencyHandler.AddCurrencyAsync(receiver, $"Gift from {Context.User.Username} ({Context.User.Id}).", amount, true).ConfigureAwait(false); - await channel.SendConfirmAsync($"{Context.User.Mention} successfully sent {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to {receiver.Mention}!").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully sent {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to {receiver.Mention}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -104,14 +105,14 @@ namespace NadekoBot.Modules.Gambling [Priority(1)] public async Task Award(IUserMessage umsg, int amount, ulong usrId) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; await CurrencyHandler.AddCurrencyAsync(usrId, $"Awarded by bot owner. ({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false); - await channel.SendConfirmAsync($"{Context.User.Mention} successfully awarded {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to <@{usrId}>!").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully awarded {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} to <@{usrId}>!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -121,7 +122,8 @@ namespace NadekoBot.Modules.Gambling public async Task Award(IUserMessage umsg, int amount, [Remainder] IRole role) { var channel = (ITextChannel)Context.Channel; - var users = channel.Guild.GetUsers() + var users = Context.Guild.GetUsers() + //var users = channel.Guild.GetUsers() .Where(u => u.Roles.Contains(role)) .ToList(); await Task.WhenAll(users.Select(u => CurrencyHandler.AddCurrencyAsync(u.Id, @@ -129,7 +131,8 @@ namespace NadekoBot.Modules.Gambling amount))) .ConfigureAwait(false); - await channel.SendConfirmAsync($"Awarded `{amount}` {Gambling.CurrencyPluralName} to `{users.Count}` users from `{role.Name}` role.") + await Context.Channel.SendConfirmAsync($"Awarded `{amount}` {Gambling.CurrencyPluralName} to `{users.Count}` users from `{role.Name}` role.") + //await channel.SendConfirmAsync($"Awarded `{amount}` {Gambling.CurrencyPluralName} to `{users.Count}` users from `{role.Name}` role.") .ConfigureAwait(false); } @@ -139,14 +142,14 @@ namespace NadekoBot.Modules.Gambling [OwnerOnly] public async Task Take(IUserMessage umsg, long amount, [Remainder] IGuildUser user) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; if(await CurrencyHandler.RemoveCurrencyAsync(user, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount, true).ConfigureAwait(false)) - await channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); else - await channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user} because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user} because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } @@ -155,21 +158,21 @@ namespace NadekoBot.Modules.Gambling [OwnerOnly] public async Task Take(IUserMessage umsg, long amount, [Remainder] ulong usrId) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; if(await CurrencyHandler.RemoveCurrencyAsync(usrId, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false)) - await channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from <@{usrId}>!").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from <@{usrId}>!").ConfigureAwait(false); else - await channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from `{usrId}` because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from `{usrId}` because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task BetRoll(IUserMessage umsg, long amount) { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; if (amount < 1) return; @@ -184,7 +187,7 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await channel.SendErrorAsync($"{guildUser.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{guildUser.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); return; } @@ -212,14 +215,14 @@ namespace NadekoBot.Modules.Gambling await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 10, false).ConfigureAwait(false); } - await channel.SendConfirmAsync(str).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(str).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Leaderboard() { - var channel = (ITextChannel)Context.Channel; + //var channel = (ITextChannel)Context.Channel; IEnumerable richest = new List(); using (var uow = DbHandler.UnitOfWork()) @@ -228,14 +231,14 @@ namespace NadekoBot.Modules.Gambling } if (!richest.Any()) return; - await channel.SendMessageAsync( + await Context.Channel.SendMessageAsync( richest.Aggregate(new StringBuilder( $@"```xl โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ณโ”โ”โ”โ”โ”โ”โ”โ”โ”“ โ”ƒ Id โ”ƒ $$$ โ”ƒ "), (cur, cs) => cur.AppendLine($@"โ”ฃโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‹โ”โ”โ”โ”โ”โ”โ”โ”โ”ซ -โ”ƒ{(channel.Guild.GetUser(cs.UserId)?.Username?.TrimTo(18, true) ?? cs.UserId.ToString()),-20} โ”ƒ {cs.Amount,6} โ”ƒ") +โ”ƒ{(Context.Guild.GetUser(cs.UserId)?.Username?.TrimTo(18, true) ?? cs.UserId.ToString()),-20} โ”ƒ {cs.Amount,6} โ”ƒ") ).ToString() + "โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ปโ”โ”โ”โ”โ”โ”โ”โ”โ”›```").ConfigureAwait(false); } } From 778070d9b3dde34f44bd0f08cc70e41eb1d0ee95 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Fri, 16 Dec 2016 23:01:56 +0100 Subject: [PATCH 08/30] Removed discord.net submodule for now --- .gitmodules | 4 ---- NadekoBot.sln | 32 -------------------------------- discord.net | 1 - src/NadekoBot/project.json | 4 +--- 4 files changed, 1 insertion(+), 40 deletions(-) delete mode 100644 .gitmodules delete mode 160000 discord.net diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 1996477a..00000000 --- a/.gitmodules +++ /dev/null @@ -1,4 +0,0 @@ -[submodule "discord.net"] - path = discord.net - url = https://github.com/kwoth/discord.net - branch = rogue-dev diff --git a/NadekoBot.sln b/NadekoBot.sln index 147256fe..6a872243 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -12,14 +12,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NadekoBot", "src\NadekoBot\NadekoBot.xproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{F29E2B91-6877-4EF1-8B54-523FE06F780C}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "discord.net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{526FAB2E-03EA-4231-B480-555F926B1750}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "discord.net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}" -EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "discord.net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{E8B62DD4-5A6B-4C66-916B-A782247BC983}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -33,30 +25,6 @@ Global {45EC1473-C678-4857-A544-07DFE0D0B478}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.ActiveCfg = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.Build.0 = Release|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F29E2B91-6877-4EF1-8B54-523FE06F780C}.Release|Any CPU.Build.0 = Release|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.Debug|Any CPU.Build.0 = Debug|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.Release|Any CPU.ActiveCfg = Release|Any CPU - {526FAB2E-03EA-4231-B480-555F926B1750}.Release|Any CPU.Build.0 = Release|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2BA94A35-7DE0-4E19-9DAC-D6378845B8D0}.Release|Any CPU.Build.0 = Release|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E8B62DD4-5A6B-4C66-916B-A782247BC983}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/discord.net b/discord.net deleted file mode 160000 index c102f52b..00000000 --- a/discord.net +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c102f52bfa1a6fd6ffbbd7c7f65d07342e8b6851 diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index ac27a4f3..90ff822c 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -38,9 +38,7 @@ "Newtonsoft.Json": "9.0.2-beta1", "NLog": "5.0.0-beta03", "System.Diagnostics.Contracts": "4.3.0", - "System.Xml.XPath": "4.3.0", - "Discord.Net.Commands": "1.0.0-*", - "Discord.Net.WebSocket": "1.0.0-*" + "System.Xml.XPath": "4.3.0" }, "tools": { "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final", From 14876012f5bd1a7f95510aab2cc618ae4ff5cccb Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 17 Dec 2016 01:16:14 +0100 Subject: [PATCH 09/30] Only utility left for basic changes --- .../Attributes/OwnerOnlyAttribute.cs | 2 - .../20161122100602_Greet and bye improved.cs | 4 +- .../Migrations/20161127233843_PokeGame.cs | 4 +- .../Migrations/20161213025624_mutedusers.cs | 4 +- .../NadekoSqliteContextModelSnapshot.cs | 3 - .../Modules/Administration/Administration.cs | 25 +- .../Commands/AntiRaidCommands.cs | 18 +- .../Commands/AutoAssignRoleCommands.cs | 4 +- .../Commands/CrossServerTextChannel.cs | 23 +- .../Commands/DMForwardCommands.cs | 15 +- .../Administration/Commands/LogCommand.cs | 2 - .../Commands/MessageRepeater.cs | 20 +- .../Administration/Commands/Migration.cs | 5 +- .../Administration/Commands/MuteCommands.cs | 42 ++-- .../Commands/PlayingRotateCommands.cs | 5 +- .../Commands/RatelimitCommand.cs | 21 +- .../Commands/SelfAssignedRolesCommand.cs | 32 +-- .../Administration/Commands/SelfCommands.cs | 9 +- .../Commands/ServerGreetCommands.cs | 46 ++-- .../Commands/VoicePlusTextCommands.cs | 20 +- .../Modules/ClashOfClans/ClashOfClans.cs | 55 ++--- .../CustomReactions/CustomReactions.cs | 54 ++-- src/NadekoBot/Modules/DiscordModule.cs | 1 - .../Modules/Gambling/Commands/AnimalRacing.cs | 15 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 44 +--- .../Games/Commands/CleverBotCommands.cs | 7 +- .../Games/Commands/Hangman/HangmanGame.cs | 1 - .../Games/Commands/Hangman/IHangmanObject.cs | 8 +- .../Modules/Games/Commands/HangmanCommands.cs | 6 +- .../Modules/Games/Commands/LeetCommands.cs | 2 +- .../Games/Commands/PlantAndPickCommands.cs | 3 +- .../Modules/Games/Commands/PollCommands.cs | 17 +- .../Modules/Games/Commands/TriviaCommands.cs | 2 +- src/NadekoBot/Modules/Music/Music.cs | 216 ++++++++-------- src/NadekoBot/Modules/NSFW/NSFW.cs | 3 +- .../Permissions/PermissionExtensions.cs | 1 - .../Modules/Permissions/Permissions.cs | 172 ++++++------- src/NadekoBot/Modules/Pokemon/Pokemon.cs | 59 +++-- src/NadekoBot/Modules/Pokemon/PokemonType.cs | 6 +- .../Searches/Commands/AnimeSearchCommands.cs | 1 - .../Modules/Searches/Commands/JokeCommands.cs | 8 +- .../Modules/Searches/Commands/LoLCommands.cs | 3 - .../Searches/Commands/MemegenCommands.cs | 6 +- .../Searches/Commands/Models/AnimeResult.cs | 1 - .../Commands/Models/OverwatchApiModel.cs | 1 - .../Searches/Commands/OMDB/OmdbProvider.cs | 1 - .../Modules/Searches/Commands/OsuCommands.cs | 13 +- .../Searches/Commands/OverwatchCommands.cs | 15 +- .../Searches/Commands/PlaceCommands.cs | 7 +- .../Commands/PokemonSearchCommands.cs | 2 - .../Commands/StreamNotificationCommands.cs | 4 - .../Modules/Searches/Commands/Translator.cs | 13 +- src/NadekoBot/Modules/Searches/Searches.cs | 231 +++++++----------- .../Modules/Utility/Commands/CalcCommand.cs | 5 +- .../Modules/Utility/Commands/InfoCommands.cs | 1 - .../Modules/Utility/Commands/Remind.cs | 1 - .../Utility/Commands/UnitConversion.cs | 1 - src/NadekoBot/Modules/Utility/Utility.cs | 6 - .../Services/Database/Models/PokeType.cs | 9 +- .../Repositories/IPokeGameRepository.cs | 1 - .../Repositories/Impl/PokeGameRepository.cs | 3 - src/NadekoBot/Services/Impl/StatsService.cs | 1 - src/NadekoBot/ShardedDiscordClient.cs | 2 +- .../TypeReaders/BotCommandTypeReader.cs | 1 - src/NadekoBot/TypeReaders/GuildTypeReader.cs | 1 - src/NadekoBot/TypeReaders/ModuleTypeReader.cs | 1 - .../TypeReaders/PermissionActionTypeReader.cs | 1 - src/NadekoBot/_Extensions/Extensions.cs | 3 - src/NadekoBot/project.json | 6 +- 69 files changed, 494 insertions(+), 831 deletions(-) diff --git a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs index ecb5c552..70432527 100644 --- a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs +++ b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs @@ -1,7 +1,5 @@ ๏ปฟusing System.Threading.Tasks; using Discord.Commands; -using Discord; -using System; namespace NadekoBot.Attributes { diff --git a/src/NadekoBot/Migrations/20161122100602_Greet and bye improved.cs b/src/NadekoBot/Migrations/20161122100602_Greet and bye improved.cs index 8dabc472..8d3d5644 100644 --- a/src/NadekoBot/Migrations/20161122100602_Greet and bye improved.cs +++ b/src/NadekoBot/Migrations/20161122100602_Greet and bye improved.cs @@ -1,6 +1,4 @@ -๏ปฟusing System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +๏ปฟusing Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20161127233843_PokeGame.cs b/src/NadekoBot/Migrations/20161127233843_PokeGame.cs index 1b1a2ab0..81f6f789 100644 --- a/src/NadekoBot/Migrations/20161127233843_PokeGame.cs +++ b/src/NadekoBot/Migrations/20161127233843_PokeGame.cs @@ -1,6 +1,4 @@ -๏ปฟusing System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +๏ปฟusing Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/20161213025624_mutedusers.cs b/src/NadekoBot/Migrations/20161213025624_mutedusers.cs index ec97cac5..8ac7dfa9 100644 --- a/src/NadekoBot/Migrations/20161213025624_mutedusers.cs +++ b/src/NadekoBot/Migrations/20161213025624_mutedusers.cs @@ -1,6 +1,4 @@ -๏ปฟusing System; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Migrations; +๏ปฟusing Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Migrations/NadekoSqliteContextModelSnapshot.cs b/src/NadekoBot/Migrations/NadekoSqliteContextModelSnapshot.cs index 6b7ef481..c0ea456d 100644 --- a/src/NadekoBot/Migrations/NadekoSqliteContextModelSnapshot.cs +++ b/src/NadekoBot/Migrations/NadekoSqliteContextModelSnapshot.cs @@ -2,10 +2,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.EntityFrameworkCore.Migrations; using NadekoBot.Services.Database; -using NadekoBot.Services.Database.Models; -using NadekoBot.Modules.Music.Classes; namespace NadekoBot.Migrations { diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 7b4ad467..02bfb1dc 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -16,8 +16,6 @@ using System.IO; using static NadekoBot.Modules.Permissions.Permissions; using System.Collections.Concurrent; using NLog; -using NadekoBot.Services.Database; -using Microsoft.EntityFrameworkCore; namespace NadekoBot.Modules.Administration { @@ -45,7 +43,7 @@ namespace NadekoBot.Modules.Administration { try { - var channel = Context.Channel as SocketTextChannel; + var channel = msg.Channel as SocketTextChannel; if (channel == null) return; @@ -53,7 +51,7 @@ namespace NadekoBot.Modules.Administration bool shouldDelete; using (var uow = DbHandler.UnitOfWork()) { - shouldDelete = uow.GuildConfigs.For(Context.Guild.Id, set => set).DeleteMessageOnCommand; + shouldDelete = uow.GuildConfigs.For(channel.Guild.Id, set => set).DeleteMessageOnCommand; } if (shouldDelete) @@ -221,7 +219,7 @@ namespace NadekoBot.Modules.Administration var green = Convert.ToByte(rgb ? int.Parse(args[2]) : Convert.ToInt32(arg1.Substring(2, 2), 16)); var blue = Convert.ToByte(rgb ? int.Parse(args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16)); - await role.ModifyAsync(r => r.Color = new Discord.Color(red, green, blue).RawValue).ConfigureAwait(false); + await role.ModifyAsync(r => r.Color = new Color(red, green, blue)).ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"โ˜‘๏ธ Role **{role.Name}'s** color has been changed.").ConfigureAwait(false); } catch (Exception) @@ -419,9 +417,10 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageChannels)] public async Task SetTopic([Remainder] string topic = null) { + var channel = (ITextChannel)Context.Channel; topic = topic ?? ""; - await Context.Channel.ModifyAsync(c => c.Topic = topic); - await Context.Channel.SendConfirmAsync("๐Ÿ†— **New channel topic set.**").ConfigureAwait(false); + await channel.ModifyAsync(c => c.Topic = topic); + await channel.SendConfirmAsync("๐Ÿ†— **New channel topic set.**").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -429,8 +428,9 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageChannels)] public async Task SetChanlName([Remainder] string name) { - await Context.Channel.ModifyAsync(c => c.Name = name).ConfigureAwait(false); - await Context.Channel.SendConfirmAsync("๐Ÿ†— **New channel name set.**").ConfigureAwait(false); + var channel = (ITextChannel)Context.Channel; + await channel.ModifyAsync(c => c.Name = name).ConfigureAwait(false); + await channel.SendConfirmAsync("๐Ÿ†— **New channel name set.**").ConfigureAwait(false); } @@ -438,7 +438,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Prune() - { + { var user = await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false); var enumerable = (await Context.Channel.GetMessagesAsync().Flatten()).AsEnumerable(); @@ -452,8 +452,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(ChannelPermission.ManageMessages)] public async Task Prune(int count) { - - await (Context.Message as IUserMessage).DeleteAsync(); + await Context.Message.DeleteAsync().ConfigureAwait(false); int limit = (count < 100) ? count : 100; var enumerable = (await Context.Channel.GetMessagesAsync(limit: limit).Flatten().ConfigureAwait(false)); await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); @@ -507,7 +506,7 @@ namespace NadekoBot.Modules.Administration await sr.CopyToAsync(imgStream); imgStream.Position = 0; - await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = imgStream).ConfigureAwait(false); + await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 53cfdce1..6126c994 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -67,7 +67,7 @@ namespace NadekoBot.Modules.Administration } [Group] - public class AntiRaidCommands + public class AntiRaidCommands : ModuleBase { private static ConcurrentDictionary antiRaidGuilds = new ConcurrentDictionary(); @@ -84,10 +84,10 @@ namespace NadekoBot.Modules.Administration NadekoBot.Client.MessageReceived += (imsg) => { var msg = imsg as IUserMessage; - if (msg == null || Context.User.IsBot) + if (msg == null || imsg.Author.IsBot) return Task.CompletedTask; - //var channel = Context.Channel as ITextChannel; + var channel = imsg.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; @@ -96,17 +96,17 @@ namespace NadekoBot.Modules.Administration try { AntiSpamSetting spamSettings; - if (!antiSpamGuilds.TryGetValue(Context.Guild.Id, out spamSettings)) + if (!antiSpamGuilds.TryGetValue(channel.Guild.Id, out spamSettings)) return; - var stats = spamSettings.UserStats.AddOrUpdate(Context.User.Id, new UserSpamStats(msg.Content), + var stats = spamSettings.UserStats.AddOrUpdate(imsg.Author.Id, new UserSpamStats(msg.Content), (id, old) => { old.ApplyNextMessage(msg.Content); return old; }); if (stats.Count >= spamSettings.MessageThreshold) { - if (spamSettings.UserStats.TryRemove(Context.User.Id, out stats)) + if (spamSettings.UserStats.TryRemove(imsg.Author.Id, out stats)) { - await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)Context.User) + await PunishUsers(spamSettings.Action, ProtectionType.Spamming, (IGuildUser)imsg.Author) .ConfigureAwait(false); } } @@ -199,8 +199,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiRaid(IUserMessage imsg, int userThreshold, int seconds, PunishmentAction action) { - ////var channel = (ITextChannel)Context.Channel; - if (userThreshold < 2 || userThreshold > 30) { await Context.Channel.SendErrorAsync("โ—๏ธUser threshold must be between **2** and **30**.").ConfigureAwait(false); @@ -243,8 +241,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task AntiSpam(IUserMessage imsg, int messageCount=3, PunishmentAction action = PunishmentAction.Mute) { - ////var channel = (ITextChannel)Context.Channel; - if (messageCount < 2 || messageCount > 10) return; diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 3342e6c2..902f4348 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -14,7 +14,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class AutoAssignRoleCommands + public class AutoAssignRoleCommands : ModuleBase { private static Logger _log { get; } @@ -48,8 +48,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task AutoAssignRole(IUserMessage umsg, [Remainder] IRole role = null) { - //var channel = (ITextChannel)Context.Channel; - GuildConfig conf; using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 81a10732..09335700 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -14,35 +14,35 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class CrossServerTextChannel + public class CrossServerTextChannel : ModuleBase { static CrossServerTextChannel() { _log = LogManager.GetCurrentClassLogger(); NadekoBot.Client.MessageReceived += (imsg) => { - if (Context.User.IsBot) + if (imsg.Author.IsBot) return Task.CompletedTask; var msg = imsg as IUserMessage; if (msg == null) return Task.CompletedTask; - //var channel = Context.Channel as ITextChannel; + var channel = imsg.Channel as ITextChannel; if (channel == null) return Task.CompletedTask; Task.Run(async () => { - if (Context.User.Id == NadekoBot.Client.CurrentUser().Id) return; + if (imsg.Author.Id == NadekoBot.Client.CurrentUser().Id) return; foreach (var subscriber in Subscribers) { var set = subscriber.Value; - if (!set.Contains(Context.Channel)) + if (!set.Contains(channel)) continue; foreach (var chan in set.Except(new[] { channel })) { - try { await chan.SendMessageAsync(GetText(Context.Guild, channel, (IGuildUser)Context.User, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await chan.SendMessageAsync(GetText(channel.Guild, channel, (IGuildUser)msg.Author, msg)).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } } }); @@ -61,12 +61,11 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task Scsc() { - ////var channel = (ITextChannel)Context.Channel; var token = new NadekoRandom().Next(); var set = new ConcurrentHashSet(); if (Subscribers.TryAdd(token, set)) { - set.Add(channel); + set.Add((ITextChannel)Context.Channel); await ((IGuildUser)Context.User).SendConfirmAsync("This is your CSC token", token.ToString()).ConfigureAwait(false); } } @@ -76,12 +75,10 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Jcsc(IUserMessage imsg, int token) { - ////var channel = (ITextChannel)Context.Channel; - ConcurrentHashSet set; if (!Subscribers.TryGetValue(token, out set)) return; - set.Add(channel); + set.Add((ITextChannel)Context.Channel); await Context.Channel.SendConfirmAsync("Joined cross server channel.").ConfigureAwait(false); } @@ -90,11 +87,9 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Lcsc() { - ////var channel = (ITextChannel)Context.Channel; - foreach (var subscriber in Subscribers) { - subscriber.Value.TryRemove(channel); + subscriber.Value.TryRemove((ITextChannel)Context.Channel); } await Context.Channel.SendMessageAsync("Left cross server channel.").ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs index a808510e..066ce804 100644 --- a/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/DMForwardCommands.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -12,7 +13,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class DMForwardCommands + public class DMForwardCommands : ModuleBase { private static bool ForwardDMs { get; set; } private static bool ForwardDMsToAllOwners { get; set; } @@ -31,8 +32,6 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task ForwardMessages() { - //var channel = Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var config = uow.BotConfig.GetOrCreate(); @@ -49,8 +48,6 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task ForwardToAll() { - //var channel = Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var config = uow.BotConfig.GetOrCreate(); @@ -64,20 +61,20 @@ namespace NadekoBot.Modules.Administration } - public static async Task HandleDMForwarding(IMessage msg, List ownerChannels) + public static async Task HandleDMForwarding(SocketMessage msg, List ownerChannels) { if (ForwardDMs && ownerChannels.Any()) { - var title = $"DM from [{Context.User}]({Context.User.Id})"; + var title = $"DM from [{msg.Author}]({msg.Author.Id})"; if (ForwardDMsToAllOwners) { - var msgs = await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != Context.User.Id) + var msgs = await Task.WhenAll(ownerChannels.Where(ch => ch.Recipient.Id != msg.Author.Id) .Select(ch => ch.SendConfirmAsync(title, msg.Content))).ConfigureAwait(false); } else { var firstOwnerChannel = ownerChannels.First(); - if (firstOwnerChannel.Recipient.Id != Context.User.Id) + if (firstOwnerChannel.Recipient.Id != msg.Author.Id) try { await firstOwnerChannel.SendConfirmAsync(title, msg.Content).ConfigureAwait(false); } catch { } } } diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 938ff9d8..9e63efda 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; @@ -65,7 +64,6 @@ namespace NadekoBot.Modules.Administration public LogCommands() { - //_client.MessageReceived += _client_MessageReceived; _client.MessageUpdated += _client_MessageUpdated; _client.MessageDeleted += _client_MessageDeleted; _client.UserBanned += _client_UserBanned; diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 54e480fe..1984bdf6 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -17,7 +16,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class RepeatCommands + public class RepeatCommands : ModuleBase { public static ConcurrentDictionary repeaters { get; } @@ -53,7 +52,7 @@ namespace NadekoBot.Modules.Administration await Task.Delay(Repeater.Interval, token).ConfigureAwait(false); if (oldMsg != null) try { await oldMsg.DeleteAsync(); } catch { } - try { oldMsg = await Context.Channel.SendMessageAsync("๐Ÿ”„ " + Repeater.Message).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); try { source.Cancel(); } catch { } } + try { oldMsg = await Channel.SendMessageAsync("๐Ÿ”„ " + Repeater.Message).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); try { source.Cancel(); } catch { } } } } catch (OperationCanceledException) { } @@ -84,10 +83,8 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task RepeatInvoke() { - //var channel = (ITextChannel)Context.Channel; - RepeatRunner rep; - if (!repeaters.TryGetValue(channel.Id, out rep)) + if (!repeaters.TryGetValue(Context.Channel.Id, out rep)) { await Context.Channel.SendErrorAsync("โ„น๏ธ **No repeating message found on this server.**").ConfigureAwait(false); return; @@ -101,9 +98,8 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Repeat() { - //var channel = (ITextChannel)Context.Channel; RepeatRunner rep; - if (repeaters.TryRemove(channel.Id, out rep)) + if (repeaters.TryRemove(Context.Channel.Id, out rep)) { using (var uow = DbHandler.UnitOfWork()) { @@ -122,8 +118,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message) { - //var channel = (ITextChannel)Context.Channel; - if (minutes < 1 || minutes > 10080) return; @@ -132,20 +126,20 @@ namespace NadekoBot.Modules.Administration RepeatRunner rep; - rep = repeaters.AddOrUpdate(channel.Id, (cid) => + rep = repeaters.AddOrUpdate(Context.Channel.Id, (cid) => { using (var uow = DbHandler.UnitOfWork()) { var localRep = new Repeater { - ChannelId = channel.Id, + ChannelId = Context.Channel.Id, GuildId = Context.Guild.Id, Interval = TimeSpan.FromMinutes(minutes), Message = message, }; uow.Repeaters.Add(localRep); uow.Complete(); - return new RepeatRunner(localRep, channel); + return new RepeatRunner(localRep, (ITextChannel)Context.Channel); } }, (cid, old) => { diff --git a/src/NadekoBot/Modules/Administration/Commands/Migration.cs b/src/NadekoBot/Modules/Administration/Commands/Migration.cs index 59509501..ea7eb8ba 100644 --- a/src/NadekoBot/Modules/Administration/Commands/Migration.cs +++ b/src/NadekoBot/Modules/Administration/Commands/Migration.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; -using Discord; using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Services; @@ -21,7 +20,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class Migration + public class Migration : ModuleBase { private const int CURRENT_VERSION = 1; @@ -36,8 +35,6 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task MigrateData() { - //var channel = (ITextChannel)Context.Channel; - var version = 0; using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index 481e8d5c..6780c6b4 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; @@ -8,9 +7,7 @@ using NadekoBot.Services; using NadekoBot.Services.Database.Models; using System; using System.Collections.Concurrent; -using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Modules.Administration @@ -18,7 +15,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class MuteCommands + public class MuteCommands : ModuleBase { private static ConcurrentDictionary GuildMuteRoles { get; } = new ConcurrentDictionary(); @@ -59,11 +56,11 @@ namespace NadekoBot.Modules.Administration if (muted == null || !muted.Contains(usr.Id)) return; else - await Mute(usr).ConfigureAwait(false); + await MuteCommands.MuteUser(usr).ConfigureAwait(false); } - public static async Task Mute(IGuildUser usr) + public static async Task MuteUser(IGuildUser usr) { await usr.ModifyAsync(x => x.Mute = true).ConfigureAwait(false); await usr.AddRolesAsync(await GetMuteRole(usr.Guild)).ConfigureAwait(false); @@ -83,7 +80,7 @@ namespace NadekoBot.Modules.Administration await UserMuted(usr, MuteType.All).ConfigureAwait(false); } - public static async Task Unmute(IGuildUser usr) + public static async Task UnmuteUser(IGuildUser usr) { await usr.ModifyAsync(x => x.Mute = false).ConfigureAwait(false); await usr.RemoveRolesAsync(await GetMuteRole(usr.Guild)).ConfigureAwait(false); @@ -160,20 +157,18 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(0)] - public Task SetMuteRole(IUserMessage imsg, [Remainder] IRole role) - => SetMuteRole(imsg, role.Name); + public Task SetMuteRole([Remainder] IRole role) + => SetMuteRole(Context.Message, role.Name); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [RequireUserPermission(GuildPermission.MuteMembers)] - public async Task Mute(IUserMessage umsg, IGuildUser user) + public async Task Mute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; - try { - await Mute(user).ConfigureAwait(false); + await MuteUser(user).ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"๐Ÿ”‡ **{user}** has been **muted** from text and voice chat.").ConfigureAwait(false); } catch @@ -186,13 +181,11 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [RequireUserPermission(GuildPermission.MuteMembers)] - public async Task Unmute(IUserMessage umsg, IGuildUser user) + public async Task Unmute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; - try { - await Unmute(user).ConfigureAwait(false); + await UnmuteUser(user).ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"๐Ÿ”‰ **{user}** has been **unmuted** from text and voice chat.").ConfigureAwait(false); } catch @@ -204,10 +197,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] - public async Task ChatMute(IUserMessage umsg, IGuildUser user) + public async Task ChatMute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; - try { await user.AddRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); @@ -223,10 +214,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] - public async Task ChatUnmute(IUserMessage umsg, IGuildUser user) + public async Task ChatUnmute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; - try { await user.RemoveRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); @@ -242,10 +231,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.MuteMembers)] - public async Task VoiceMute(IUserMessage umsg, IGuildUser user) + public async Task VoiceMute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; - try { await user.ModifyAsync(usr => usr.Mute = true).ConfigureAwait(false); @@ -261,9 +248,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.MuteMembers)] - public async Task VoiceUnmute(IUserMessage umsg, IGuildUser user) + public async Task VoiceUnmute(IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; try { await user.ModifyAsync(usr => usr.Mute = false).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index 15d11e3f..0101e1c0 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -16,7 +15,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class PlayingRotateCommands + public class PlayingRotateCommands : ModuleBase { private static Logger _log { get; } public static List RotatingStatusMessages { get; } @@ -70,7 +69,7 @@ namespace NadekoBot.Modules.Administration public static Dictionary> PlayingPlaceholders { get; } = new Dictionary> { {"%servers%", () => NadekoBot.Client.GetGuilds().Count().ToString()}, - {"%users%", () => NadekoBot.Client.GetGuilds().Select(s => s.GetUsers().Count).Sum().ToString()}, + {"%users%", () => NadekoBot.Client.GetGuilds().Select(s => s.Users.Count).Sum().ToString()}, {"%playing%", () => { var cnt = Music.Music.MusicPlayers.Count(kvp => kvp.Value.CurrentSong != null); if (cnt != 1) return cnt.ToString(); diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 1fecbd91..f0ce418e 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -13,7 +13,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class RatelimitCommand + public class RatelimitCommand : ModuleBase { public static ConcurrentDictionary RatelimitingChannels = new ConcurrentDictionary(); private static Logger _log { get; } @@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Administration var t = Task.Run(async () => { var usrMsg = umsg as IUserMessage; - //var channel = usrContext.Channel as ITextChannel; + var channel = umsg.Channel as ITextChannel; if (channel == null || usrMsg.IsAuthor()) return; @@ -76,7 +76,7 @@ namespace NadekoBot.Modules.Administration if (!RatelimitingChannels.TryGetValue(channel.Id, out limiter)) return; - if (limiter.CheckUserRatelimit(usrContext.User.Id)) + if (limiter.CheckUserRatelimit(umsg.Author.Id)) try { await usrMsg.DeleteAsync(); } catch (Exception ex) { _log.Warn(ex); } }); return Task.CompletedTask; @@ -88,10 +88,8 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task Slowmode() { - //var channel = (ITextChannel)Context.Channel; - Ratelimiter throwaway; - if (RatelimitingChannels.TryRemove(channel.Id, out throwaway)) + if (RatelimitingChannels.TryRemove(Context.Channel.Id, out throwaway)) { throwaway.cancelSource.Cancel(); await Context.Channel.SendConfirmAsync("โ„น๏ธ Slow mode disabled.").ConfigureAwait(false); @@ -102,11 +100,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageMessages)] - public async Task Slowmode(IUserMessage umsg, int msg, int perSec) + public async Task Slowmode(int msg, int perSec) { - await Slowmode(umsg).ConfigureAwait(false); // disable if exists - //var channel = (ITextChannel)Context.Channel; - + await Slowmode().ConfigureAwait(false); // disable if exists + if (msg < 1 || perSec < 1 || msg > 100 || perSec > 3600) { await Context.Channel.SendErrorAsync("โš ๏ธ Invalid parameters."); @@ -114,11 +111,11 @@ namespace NadekoBot.Modules.Administration } var toAdd = new Ratelimiter() { - ChannelId = channel.Id, + ChannelId = Context.Channel.Id, MaxMessages = msg, PerSeconds = perSec, }; - if(RatelimitingChannels.TryAdd(channel.Id, toAdd)) + if(RatelimitingChannels.TryAdd(Context.Channel.Id, toAdd)) { await Context.Channel.SendConfirmAsync("Slow mode initiated", $"Users can't send more than `{toAdd.MaxMessages} message(s)` every `{toAdd.PerSeconds} second(s)`.") diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs index 55319653..c78c88f7 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class SelfAssignedRolesCommands + public class SelfAssignedRolesCommands : ModuleBase { [NadekoCommand, Usage, Description, Aliases] @@ -24,7 +24,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageMessages)] public async Task AdSarm() { - //var channel = (ITextChannel)Context.Channel; bool newval; using (var uow = DbHandler.UnitOfWork()) { @@ -40,17 +39,15 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] - public async Task Asar(IUserMessage umsg, [Remainder] IRole role) + public async Task Asar([Remainder] IRole role) { - //var channel = (ITextChannel)Context.Channel; - IEnumerable roles; string msg; using (var uow = DbHandler.UnitOfWork()) { roles = uow.SelfAssignedRoles.GetFromGuild(Context.Guild.Id); - if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.GuildId)) + if (roles.Any(s => s.RoleId == role.Id && s.GuildId == role.Guild.Id)) { await Context.Channel.SendMessageAsync($"๐Ÿ’ข Role **{role.Name}** is already in the list.").ConfigureAwait(false); return; @@ -59,7 +56,7 @@ namespace NadekoBot.Modules.Administration { uow.SelfAssignedRoles.Add(new SelfAssignedRole { RoleId = role.Id, - GuildId = role.GuildId + GuildId = role.Guild.Id }); await uow.CompleteAsync(); msg = $"๐Ÿ†— Role **{role.Name}** added to the list."; @@ -71,14 +68,14 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] - public async Task Rsar(IUserMessage umsg, [Remainder] IRole role) + public async Task Rsar([Remainder] IRole role) { //var channel = (ITextChannel)Context.Channel; bool success; using (var uow = DbHandler.UnitOfWork()) { - success = uow.SelfAssignedRoles.DeleteByGuildAndRoleId(role.GuildId, role.Id); + success = uow.SelfAssignedRoles.DeleteByGuildAndRoleId(role.Guild.Id, role.Id); await uow.CompleteAsync(); } if (!success) @@ -147,11 +144,10 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Iam(IUserMessage umsg, [Remainder] IRole role) + public async Task Iam([Remainder] IRole role) { //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; - var usrMsg = (IUserMessage)umsg; GuildConfig conf; IEnumerable roles; @@ -166,7 +162,7 @@ namespace NadekoBot.Modules.Administration await Context.Channel.SendErrorAsync("That role is not self-assignable.").ConfigureAwait(false); return; } - if (guildUser.Roles.Contains(role)) + if (guildUser.RoleIds.Contains(role.Id)) { await Context.Channel.SendErrorAsync($"You already have **{role.Name}** role.").ConfigureAwait(false); return; @@ -174,8 +170,7 @@ namespace NadekoBot.Modules.Administration if (conf.ExclusiveSelfAssignedRoles) { - var sameRoles = guildUser.Roles.Where(r => roles.Any(rm => rm.RoleId == r.Id)); - if (sameRoles.Any()) + if (guildUser.RoleIds.Contains(role.Id)) { await Context.Channel.SendErrorAsync($"You already have **{sameRoles.FirstOrDefault().Name}** `exclusive self-assigned` role.").ConfigureAwait(false); return; @@ -199,16 +194,15 @@ namespace NadekoBot.Modules.Administration { await Task.Delay(3000).ConfigureAwait(false); try { await msg.DeleteAsync().ConfigureAwait(false); } catch { } // if 502 or something, i don't want bot crashing - try { await usrMsg.DeleteAsync().ConfigureAwait(false); } catch { } + try { await Context.Message.DeleteAsync().ConfigureAwait(false); } catch { } }); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Iamnot(IUserMessage umsg, [Remainder] IRole role) + public async Task Iamnot([Remainder] IRole role) { - //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; bool autoDeleteSelfAssignedRoleMessages; @@ -224,7 +218,7 @@ namespace NadekoBot.Modules.Administration await Context.Channel.SendErrorAsync("๐Ÿ’ข That role is not self-assignable.").ConfigureAwait(false); return; } - if (!guildUser.Roles.Contains(role)) + if (!guildUser.RoleIds.Contains(role.Id)) { await Context.Channel.SendErrorAsync($"โŽ You don't have **{role.Name}** role.").ConfigureAwait(false); return; @@ -246,7 +240,7 @@ namespace NadekoBot.Modules.Administration { await Task.Delay(3000).ConfigureAwait(false); try { await msg.DeleteAsync().ConfigureAwait(false); } catch { } // if 502 or something, i don't want bot crashing - try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { } + try { await Context.Message.DeleteAsync().ConfigureAwait(false); } catch { } }); } } diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index a671d73e..04d9f61c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -1,5 +1,4 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using System.Linq; @@ -10,7 +9,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - class SelfCommands + class SelfCommands : ModuleBase { private ShardedDiscordClient _client; @@ -22,10 +21,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Leave(IUserMessage umsg, [Remainder] string guildStr) + public async Task Leave([Remainder] string guildStr) { - //var channel = (ITextChannel)Context.Channel; - guildStr = guildStr.Trim().ToUpperInvariant(); var server = _client.GetGuilds().FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == guildStr) ?? _client.GetGuilds().FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == guildStr); diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index 5309f750..a663d120 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -1,9 +1,9 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; -using NadekoBot.Services.Database; using NadekoBot.Services.Database.Models; using NLog; using System; @@ -15,7 +15,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class ServerGreetCommands + public class ServerGreetCommands : ModuleBase { private static Logger _log { get; } @@ -26,7 +26,7 @@ namespace NadekoBot.Modules.Administration _log = LogManager.GetCurrentClassLogger(); } - private static Task UserLeft(IGuildUser user) + private static Task UserLeft(SocketGuildUser user) { var leftTask = Task.Run(async () => { @@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Administration } if (!conf.SendChannelByeMessage) return; - //var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId); + var channel = (await user.Guild.GetTextChannelsAsync()).FirstOrDefault(c => c.Id == conf.ByeMessageChannelId); if (channel == null) //maybe warn the server owner that the channel is missing return; @@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Administration return; try { - var toDelete = await Context.Channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); + var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); if (conf.AutoDeleteByeMessagesTimer > 0) { var t = Task.Run(async () => @@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Administration if (conf.SendChannelGreetMessage) { - //var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.GreetMessageChannelId); + var channel = (await user.Guild.GetTextChannelsAsync()).FirstOrDefault(c => c.Id == conf.GreetMessageChannelId); if (channel != null) //maybe warn the server owner that the channel is missing { var msg = conf.ChannelGreetMessageText.Replace("%user%", user.Mention).Replace("%id%", user.Id.ToString()).Replace("%server%", user.Guild.Name); @@ -88,7 +88,7 @@ namespace NadekoBot.Modules.Administration { try { - var toDelete = await Context.Channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); + var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false); if (conf.AutoDeleteGreetMessagesTimer > 0) { var t = Task.Run(async () => @@ -105,14 +105,14 @@ namespace NadekoBot.Modules.Administration if (conf.SendDmGreetMessage) { - //var channel = await user.CreateDMChannelAsync(); + var channel = await user.CreateDMChannelAsync(); if (channel != null) { var msg = conf.DmGreetMessageText.Replace("%user%", user.Username).Replace("%server%", user.Guild.Name); if (!string.IsNullOrWhiteSpace(msg)) { - await Context.Channel.SendConfirmAsync(msg).ConfigureAwait(false); + await channel.SendConfirmAsync(msg).ConfigureAwait(false); } } } @@ -125,9 +125,9 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task GreetDel(IUserMessage umsg, int timer = 30) + public async Task GreetDel(int timer = 30) { - //var channel = (ITextChannel)Context.Channel; + var channel = (ITextChannel)Context.Channel; if (timer < 0 || timer > 600) return; @@ -158,9 +158,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Greet() { - //var channel = (ITextChannel)Context.Channel; - - var enabled = await ServerGreetCommands.SetGreet(Context.Guild.Id, channel.Id).ConfigureAwait(false); + var enabled = await ServerGreetCommands.SetGreet(Context.Guild.Id, Context.Channel.Id).ConfigureAwait(false); if (enabled) await Context.Channel.SendConfirmAsync("โœ… Greeting messages **enabled** on this channel.").ConfigureAwait(false); @@ -185,10 +183,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task GreetMsg(IUserMessage umsg, [Remainder] string text = null) + public async Task GreetMsg([Remainder] string text = null) { - //var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(text)) { string channelGreetMessageText; @@ -231,8 +227,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task GreetDm() { - //var channel = (ITextChannel)Context.Channel; - var enabled = await ServerGreetCommands.SetGreetDm(Context.Guild.Id).ConfigureAwait(false); if (enabled) @@ -257,10 +251,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task GreetDmMsg(IUserMessage umsg, [Remainder] string text = null) + public async Task GreetDmMsg([Remainder] string text = null) { - //var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(text)) { GuildConfig config; @@ -303,9 +295,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task Bye() { - //var channel = (ITextChannel)Context.Channel; - - var enabled = await ServerGreetCommands.SetBye(Context.Guild.Id, channel.Id).ConfigureAwait(false); + var enabled = await ServerGreetCommands.SetBye(Context.Guild.Id, Context.Channel.Id).ConfigureAwait(false); if (enabled) await Context.Channel.SendConfirmAsync("โœ… Bye announcements **enabled** on this channel.").ConfigureAwait(false); @@ -330,10 +320,8 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task ByeMsg(IUserMessage umsg, [Remainder] string text = null) + public async Task ByeMsg([Remainder] string text = null) { - //var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(text)) { string byeMessageText; @@ -376,8 +364,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageGuild)] public async Task ByeDel(IUserMessage umsg, int timer = 30) { - //var channel = (ITextChannel)Context.Channel; - await ServerGreetCommands.SetByeDel(Context.Guild.Id, timer).ConfigureAwait(false); if (timer > 0) diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 70172381..f9b2aa6c 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -15,7 +15,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class VoicePlusTextCommands + public class VoicePlusTextCommands : ModuleBase { private static Regex channelNameRegex = new Regex(@"[^a-zA-Z0-9 -]", RegexOptions.Compiled); @@ -29,9 +29,9 @@ namespace NadekoBot.Modules.Administration NadekoBot.Client.UserVoiceStateUpdated += UserUpdatedEventHandler; } - private static Task UserUpdatedEventHandler(IUser iuser, IVoiceState before, IVoiceState after) + private static Task UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after) { - var user = (iuser as IGuildUser); + var user = (iuser as SocketGuildUser); var guild = user?.Guild; if (guild == null) @@ -40,7 +40,7 @@ namespace NadekoBot.Modules.Administration { try { - var botUserPerms = guild.GetCurrentUser().GuildPermissions; + var botUserPerms = guild.CurrentUser.GuildPermissions; if (before.VoiceChannel == after.VoiceChannel) return; @@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Administration var beforeVch = before.VoiceChannel; if (beforeVch != null) { - var textChannel = guild.GetTextChannels().Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault(); + var textChannel = (await guild.GetTextChannelsAsync()).Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault(); if (textChannel != null) await textChannel.AddPermissionOverwriteAsync(user, new OverwritePermissions(readMessages: PermValue.Deny, @@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Administration var afterVch = after.VoiceChannel; if (afterVch != null && guild.AFKChannelId != afterVch.Id) { - var textChannel = guild.GetTextChannels() + var textChannel = (await guild.GetTextChannelsAsync()) .Where(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant()) .FirstOrDefault(); if (textChannel == null) @@ -110,7 +110,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageChannels)] public async Task VoicePlusText() { - //var channel = (ITextChannel)Context.Channel; var guild = Context.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); @@ -141,7 +140,7 @@ namespace NadekoBot.Modules.Administration if (!isEnabled) { voicePlusTextCache.TryRemove(guild.Id); - foreach (var textChannel in guild.GetTextChannels().Where(c => c.Name.EndsWith("-voice"))) + foreach (var textChannel in (await guild.GetTextChannelsAsync().ConfigureAwait(false)).Where(c => c.Name.EndsWith("-voice"))) { try { await textChannel.DeleteAsync().ConfigureAwait(false); } catch { } } @@ -163,7 +162,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] public async Task CleanVPlusT() { - //var channel = (ITextChannel)Context.Channel; var guild = Context.Guild; var botUser = await guild.GetCurrentUserAsync().ConfigureAwait(false); if (!botUser.GuildPermissions.Administrator) @@ -172,8 +170,8 @@ namespace NadekoBot.Modules.Administration return; } - var allTxtChannels = guild.GetTextChannels().Where(c => c.Name.EndsWith("-voice")); - var validTxtChannelNames = guild.GetVoiceChannels().Select(c => GetChannelName(c.Name).ToLowerInvariant()); + var allTxtChannels = (await guild.GetTextChannelsAsync()).Where(c => c.Name.EndsWith("-voice")); + var validTxtChannelNames = (await guild.GetVoiceChannelsAsync()).Select(c => GetChannelName(c.Name).ToLowerInvariant()); var invalidTxtChannels = allTxtChannels.Where(c => !validTxtChannelNames.Contains(c.Name)); diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 357d2cd7..40b9e999 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -7,7 +7,6 @@ using System.Threading.Tasks; using Discord; using NadekoBot.Services; using NadekoBot.Attributes; -using Discord.WebSocket; using NadekoBot.Services.Database.Models; using System.Linq; using NadekoBot.Extensions; @@ -59,8 +58,6 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task CreateWar(IUserMessage umsg, int size, [Remainder] string enemyClan = null) { - //var channel = (ITextChannel)Context.Channel; - if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) return; @@ -73,18 +70,15 @@ namespace NadekoBot.Modules.ClashOfClans return; } List wars; - //if (!ClashWars.TryGetValue(channel.Guild.Id, out wars)) - if (!ClashWars.TryGetValue(Context.Guild.Id, out wars)) + if (!ClashWars.TryGetValue(Context.Guild.Id, out wars)) { wars = new List(); if (!ClashWars.TryAdd(Context.Guild.Id, wars)) - //if (!ClashWars.TryAdd(channel.Guild.Id, wars)) return; } var cw = await CreateWar(enemyClan, size, Context.Guild.Id, Context.Channel.Id); - //var cw = await CreateWar(enemyClan, size, channel.Guild.Id, Context.Channel.Id); wars.Add(cw); await Context.Channel.SendConfirmAsync($"โ—๐Ÿ”ฐ**CREATED CLAN WAR AGAINST {cw.ShortPrint()}**").ConfigureAwait(false); @@ -94,12 +88,10 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task StartWar(IUserMessage umsg, [Remainder] string number = null) { - //var channel = (ITextChannel)Context.Channel; - int num = 0; int.TryParse(number, out num); - var warsInfo = GetWarInfo(umsg, num); + var warsInfo = GetWarInfo(umsg, Context.Guild, num); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -122,7 +114,6 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task ListWar(IUserMessage umsg, [Remainder] string number = null) { - //var channel = (ITextChannel)Context.Channel; // if number is null, print all wars in a short way if (string.IsNullOrWhiteSpace(number)) @@ -130,7 +121,6 @@ namespace NadekoBot.Modules.ClashOfClans //check if there are any wars List wars = null; ClashWars.TryGetValue(Context.Guild.Id, out wars); - //ClashWars.TryGetValue(channel.Guild.Id, out wars); if (wars == null || wars.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **No active wars.**").ConfigureAwait(false); @@ -153,7 +143,7 @@ namespace NadekoBot.Modules.ClashOfClans var num = 0; int.TryParse(number, out num); //if number is not null, print the war needed - var warsInfo = GetWarInfo(umsg, num); + var warsInfo = GetWarInfo(umsg, Context.Guild, num); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -166,8 +156,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task Claim(IUserMessage umsg, int number, int baseNumber, [Remainder] string other_name = null) { - //var channel = (ITextChannel)Context.Channel; - var warsInfo = GetWarInfo(umsg, number); + var warsInfo = GetWarInfo(umsg, Context.Guild, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -192,35 +181,30 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ClaimFinish1(IUserMessage umsg, int number, int baseNumber = 0) + public async Task ClaimFinish1(int number, int baseNumber = 0) { - //var channel = (ITextChannel)Context.Channel; - await FinishClaim(umsg, number, baseNumber - 1, 1); + await FinishClaim(number, baseNumber - 1, 1); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ClaimFinish2(IUserMessage umsg, int number, int baseNumber = 0) + public async Task ClaimFinish2(int number, int baseNumber = 0) { - //var channel = (ITextChannel)Context.Channel; - await FinishClaim(umsg, number, baseNumber - 1, 2); + await FinishClaim(number, baseNumber - 1, 2); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ClaimFinish(IUserMessage umsg, int number, int baseNumber = 0) + public async Task ClaimFinish(int number, int baseNumber = 0) { - //var channel = (ITextChannel)Context.Channel; - await FinishClaim(umsg, number, baseNumber - 1); + await FinishClaim(number, baseNumber - 1); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task EndWar(IUserMessage umsg, int number) + public async Task EndWar(int number) { - //var channel = (ITextChannel)Context.Channel; - - var warsInfo = GetWarInfo(umsg,number); + var warsInfo = GetWarInfo(Context.Message, Context.Guild, number); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ That war does not exist.").ConfigureAwait(false); @@ -239,9 +223,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task Unclaim(IUserMessage umsg, int number, [Remainder] string otherName = null) { - //var channel = (ITextChannel)Context.Channel; - - var warsInfo = GetWarInfo(umsg, number); + var warsInfo = GetWarInfo(umsg, Context.Guild, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -264,10 +246,9 @@ namespace NadekoBot.Modules.ClashOfClans } } - private async Task FinishClaim(IUserMessage umsg, int number, int baseNumber, int stars = 3) + private async Task FinishClaim(int number, int baseNumber, int stars = 3) { - //var channel = (ITextChannel)Context.Channel; - var warInfo = GetWarInfo(umsg, number); + var warInfo = GetWarInfo(Context.Message, Context.Guild, number); if (warInfo == null || warInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -293,12 +274,10 @@ namespace NadekoBot.Modules.ClashOfClans } } - private static Tuple, int> GetWarInfo(IUserMessage umsg, int num) + private static Tuple, int> GetWarInfo(IUserMessage umsg, IGuild guild, int num) { - //var channel = (ITextChannel)Context.Channel; - //check if there are any wars List wars = null; - ClashWars.TryGetValue(Context.Guild.Id, out wars); + ClashWars.TryGetValue(guild.Id, out wars); if (wars == null || wars.Count == 0) { return null; diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 81aa2a43..c16f7c91 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -7,6 +7,7 @@ using System.Collections.Concurrent; using NadekoBot.Services.Database.Models; using Discord; using NadekoBot.Extensions; +using Discord.WebSocket; namespace NadekoBot.Modules.CustomReactions { @@ -33,16 +34,16 @@ namespace NadekoBot.Modules.CustomReactions public void ClearStats() => ReactionStats.Clear(); - public static async Task TryExecuteCustomReaction() + public static async Task TryExecuteCustomReaction(SocketUserMessage umsg) { - //var channel = Context.Channel as ITextChannel; + var channel = umsg.Channel as SocketTextChannel; if (channel == null) return false; var content = umsg.Content.Trim().ToLowerInvariant(); ConcurrentHashSet reactions; - //GuildReactions.TryGetValue(channel.Guild.Id, out reactions); - GuildReactions.TryGetValue(Context.Guild.Id, out reactions); + + GuildReactions.TryGetValue(channel.Guild.Id, out reactions); if (reactions != null && reactions.Any()) { var reaction = reactions.Where(cr => @@ -54,7 +55,7 @@ namespace NadekoBot.Modules.CustomReactions if (reaction != null) { if (reaction.Response != "-") - try { await Context.Channel.SendMessageAsync(reaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } + try { await channel.SendMessageAsync(reaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } ReactionStats.AddOrUpdate(reaction.Trigger, 1, (k, old) => ++old); return true; @@ -69,7 +70,7 @@ namespace NadekoBot.Modules.CustomReactions if (greaction != null) { - try { await Context.Channel.SendMessageAsync(greaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } + try { await channel.SendMessageAsync(greaction.ResponseWithContext(umsg)).ConfigureAwait(false); } catch { } ReactionStats.AddOrUpdate(greaction.Trigger, 1, (k, old) => ++old); return true; } @@ -77,9 +78,9 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task AddCustReact(IUserMessage imsg, string key, [Remainder] string message) + public async Task AddCustReact(string key, [Remainder] string message) { - //var channel = Context.Channel as ITextChannel; + var channel = Context.Channel as ITextChannel; if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(key)) return; @@ -113,7 +114,6 @@ namespace NadekoBot.Modules.CustomReactions else { var reactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); - //var reactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); reactions.Add(cr); } @@ -127,18 +127,15 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] [Priority(0)] - public async Task ListCustReact(IUserMessage imsg, int page = 1) + public async Task ListCustReact(int page = 1) { - //var channel = Context.Channel as ITextChannel; - if (page < 1 || page > 1000) return; ConcurrentHashSet customReactions; - if (channel == null) + if (Context.Guild == null) customReactions = GlobalReactions; else customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); - //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -159,16 +156,13 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] [Priority(1)] - public async Task ListCustReact(IUserMessage imsg, All x) + public async Task ListCustReact(All x) { - //var channel = Context.Channel as ITextChannel; - ConcurrentHashSet customReactions; - if (channel == null) + if (Context.Guild == null) customReactions = GlobalReactions; else customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); - //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -180,7 +174,7 @@ namespace NadekoBot.Modules.CustomReactions .ToJson() .ToStream() .ConfigureAwait(false); - if (channel == null) // its a private one, just send back + if (Context.Guild == null) // its a private one, just send back await Context.Channel.SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); else await ((IGuildUser)Context.User).SendFileAsync(txtStream, "customreactions.txt", "List of all custom reactions").ConfigureAwait(false); @@ -188,17 +182,15 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task ListCustReactG(IUserMessage imsg, int page = 1) + public async Task ListCustReactG(int page = 1) { - //var channel = Context.Channel as ITextChannel; if (page < 1 || page > 10000) return; ConcurrentHashSet customReactions; - if (channel == null) + if (Context.Guild == null) customReactions = GlobalReactions; else customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); - //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); if (customReactions == null || !customReactions.Any()) await Context.Channel.SendErrorAsync("No custom reactions found").ConfigureAwait(false); @@ -216,14 +208,11 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task ShowCustReact(IUserMessage imsg, int id) { - //var channel = Context.Channel as ITextChannel; - ConcurrentHashSet customReactions; - if (channel == null) + if (Context.Guild == null) customReactions = GlobalReactions; else customReactions = GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()); - //customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()); var found = customReactions.FirstOrDefault(cr => cr.Id == id); @@ -242,9 +231,7 @@ namespace NadekoBot.Modules.CustomReactions [NadekoCommand, Usage, Description, Aliases] public async Task DelCustReact(IUserMessage imsg, int id) { - //var channel = Context.Channel as ITextChannel; - - if ((channel == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (channel != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) + if ((Context.Guild == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { try { await Context.Channel.SendErrorAsync("Insufficient permissions. Requires Bot ownership for global custom reactions, and Administrator for guild custom reactions."); } catch { } return; @@ -258,17 +245,16 @@ namespace NadekoBot.Modules.CustomReactions if (toDelete == null) //not found return; - if ((toDelete.GuildId == null || toDelete.GuildId == 0) && channel == null) + if ((toDelete.GuildId == null || toDelete.GuildId == 0) && Context.Guild == null) { uow.CustomReactions.Remove(toDelete); GlobalReactions.RemoveWhere(cr => cr.Id == toDelete.Id); success = true; } - else if ((toDelete.GuildId != null && toDelete.GuildId != 0) && channel?.Guild.Id == toDelete.GuildId) + else if ((toDelete.GuildId != null && toDelete.GuildId != 0) && Context.Guild.Id == toDelete.GuildId) { uow.CustomReactions.Remove(toDelete); GuildReactions.GetOrAdd(Context.Guild.Id, new ConcurrentHashSet()).RemoveWhere(cr => cr.Id == toDelete.Id); - //GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet()).RemoveWhere(cr => cr.Id == toDelete.Id); success = true; } if (success) diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index cd72023d..be453f43 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -1,5 +1,4 @@ ๏ปฟusing Discord.Commands; -using NadekoBot.Services; using NLog; namespace NadekoBot.Modules diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index f45ab74b..5751d1b2 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -16,7 +17,7 @@ namespace NadekoBot.Modules.Gambling public partial class Gambling { [Group] - public class AnimalRacing + public class AnimalRacing : ModuleBase { public static ConcurrentDictionary AnimalRaces { get; } = new ConcurrentDictionary(); @@ -24,9 +25,7 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Race() { - //var channel = (ITextChannel)Context.Channel; - - var ar = new AnimalRace(Context.Guild.Id, channel); + var ar = new AnimalRace(Context.Guild.Id, (ITextChannel)Context.Channel); if (ar.Fail) await Context.Channel.SendErrorAsync("๐Ÿ `Failed starting a race. Another race is probably running.`"); @@ -36,8 +35,6 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task JoinRace(IUserMessage umsg, int amount = 0) { - //var channel = (ITextChannel)Context.Channel; - if (amount < 0) amount = 0; @@ -194,12 +191,12 @@ namespace NadekoBot.Modules.Gambling } - private Task Client_MessageReceived(IMessage imsg) + private Task Client_MessageReceived(SocketMessage imsg) { var msg = imsg as IUserMessage; if (msg == null) return Task.CompletedTask; - if (msg.IsAuthor() || !(Context.Channel is ITextChannel) || Context.Channel != raceChannel) + if (msg.IsAuthor() || !(imsg.Channel is SocketTextChannel) || imsg.Channel != raceChannel) return Task.CompletedTask; messagesSinceGameStarted++; return Task.CompletedTask; @@ -233,7 +230,7 @@ namespace NadekoBot.Modules.Gambling return; } if (amount > 0) - if (!await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)u, "BetRace", amount, true).ConfigureAwait(false)) + if (!await CurrencyHandler.RemoveCurrencyAsync(u, "BetRace", amount, true).ConfigureAwait(false)) { try { await raceChannel.SendErrorAsync($"{u.Mention} You don't have enough {Gambling.CurrencyName}s.").ConfigureAwait(false); } catch { } return; diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index d60a45d9..1cb6abd7 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -6,10 +6,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using NadekoBot.Services; -using Discord.WebSocket; using NadekoBot.Services.Database.Models; using System.Collections.Generic; -using NadekoBot.Services.Database; namespace NadekoBot.Modules.Gambling { @@ -42,12 +40,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Raffle(IUserMessage umsg, [Remainder] IRole role = null) + public async Task Raffle([Remainder] IRole role = null) { - //var channel = (ITextChannel)Context.Channel; - - //role = role ?? channel.Guild.EveryoneRole; - role = role ?? Context.Guild.EveryoneRole; + role = role ?? Context.Guild.EveryoneRole; var members = role.Members().Where(u => u.Status != UserStatus.Offline && u.Status != UserStatus.Unknown); var membersArray = members as IUser[] ?? members.ToArray(); @@ -57,10 +52,8 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [Priority(0)] - public async Task Cash(IUserMessage umsg, [Remainder] IUser user = null) + public async Task Cash([Remainder] IUser user = null) { - //var channel = Context.Channel; - user = user ?? Context.User; await Context.Channel.SendConfirmAsync($"{user.Username} has {GetCurrency(user.Id)} {CurrencySign}").ConfigureAwait(false); @@ -68,18 +61,15 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [Priority(1)] - public async Task Cash(IUserMessage umsg, ulong userId) + public async Task Cash(ulong userId) { - //var channel = Context.Channel; - await Context.Channel.SendConfirmAsync($"`{userId}` has {GetCurrency(userId)} {CurrencySign}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Give(IUserMessage umsg, long amount, [Remainder] IGuildUser receiver) + public async Task Give(long amount, [Remainder] IGuildUser receiver) { - //var channel = (ITextChannel)Context.Channel; if (amount <= 0 || Context.User.Id == receiver.Id) return; var success = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, $"Gift to {receiver.Username} ({receiver.Id}).", amount, true).ConfigureAwait(false); @@ -96,17 +86,15 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] [OwnerOnly] [Priority(2)] - public Task Award(IUserMessage umsg, int amount, [Remainder] IGuildUser usr) => - Award(umsg, amount, usr.Id); + public Task Award(int amount, [Remainder] IGuildUser usr) => + Award(amount, usr.Id); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] [Priority(1)] - public async Task Award(IUserMessage umsg, int amount, ulong usrId) + public async Task Award(int amount, ulong usrId) { - //var channel = (ITextChannel)Context.Channel; - if (amount <= 0) return; @@ -119,11 +107,10 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] [OwnerOnly] [Priority(0)] - public async Task Award(IUserMessage umsg, int amount, [Remainder] IRole role) + public async Task Award(int amount, [Remainder] IRole role) { var channel = (ITextChannel)Context.Channel; var users = Context.Guild.GetUsers() - //var users = channel.Guild.GetUsers() .Where(u => u.Roles.Contains(role)) .ToList(); await Task.WhenAll(users.Select(u => CurrencyHandler.AddCurrencyAsync(u.Id, @@ -132,7 +119,6 @@ namespace NadekoBot.Modules.Gambling .ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"Awarded `{amount}` {Gambling.CurrencyPluralName} to `{users.Count}` users from `{role.Name}` role.") - //await channel.SendConfirmAsync($"Awarded `{amount}` {Gambling.CurrencyPluralName} to `{users.Count}` users from `{role.Name}` role.") .ConfigureAwait(false); } @@ -140,9 +126,8 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Take(IUserMessage umsg, long amount, [Remainder] IGuildUser user) + public async Task Take(long amount, [Remainder] IGuildUser user) { - //var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; @@ -156,9 +141,8 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task Take(IUserMessage umsg, long amount, [Remainder] ulong usrId) + public async Task Take(long amount, [Remainder] ulong usrId) { - //var channel = (ITextChannel)Context.Channel; if (amount <= 0) return; @@ -170,10 +154,8 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task BetRoll(IUserMessage umsg, long amount) + public async Task BetRoll(long amount) { - //var channel = (ITextChannel)Context.Channel; - if (amount < 1) return; @@ -222,8 +204,6 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Leaderboard() { - //var channel = (ITextChannel)Context.Channel; - IEnumerable richest = new List(); using (var uow = DbHandler.UnitOfWork()) { diff --git a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs index d3f3a8b1..d7a7bbdf 100644 --- a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs @@ -5,7 +5,6 @@ using NadekoBot.Extensions; using NadekoBot.Services; using NLog; using Services.CleverBotApi; -using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; @@ -19,7 +18,8 @@ namespace NadekoBot.Modules.Games { private static Logger _log { get; } - class CleverAnswer { + class CleverAnswer + { public string Status { get; set; } public string Response { get; set; } } @@ -41,7 +41,8 @@ namespace NadekoBot.Modules.Games } } - public static async Task TryAsk(IUserMessage msg) { + public static async Task TryAsk(IUserMessage msg) + { var channel = msg.Channel as ITextChannel; if (channel == null) diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index 4e8c699e..fcd096ce 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -6,7 +6,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Modules.Games.Commands.Hangman diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/IHangmanObject.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/IHangmanObject.cs index c7be7a2e..c2069477 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/IHangmanObject.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/IHangmanObject.cs @@ -1,10 +1,4 @@ -๏ปฟusing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Modules.Games.Commands.Hangman +๏ปฟnamespace NadekoBot.Modules.Games.Commands.Hangman { public class HangmanObject { diff --git a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs index 38be0a13..db631ec5 100644 --- a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs @@ -1,14 +1,10 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Games.Commands.Hangman; using NLog; using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Modules.Games diff --git a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs index d883a3d5..72ef1929 100644 --- a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs @@ -14,7 +14,7 @@ namespace NadekoBot.Modules.Games { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Leet(IUserMessage umsg, int level, [Remainder] string text = null) + public async Task Leet(int level, [Remainder] string text = null) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 35519859..04e43058 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; @@ -103,7 +102,7 @@ namespace NadekoBot.Modules.Games { var channel = (ITextChannel)Context.Channel; - if (!channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) + if (!(await channel.Guild.GetCurrentUserAsync()).GetPermissions(channel).ManageMessages) { await channel.SendErrorAsync("I need manage channel permissions in order to process this command.").ConfigureAwait(false); return; diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index 3b40898e..41ea2253 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using System; @@ -42,7 +43,7 @@ namespace NadekoBot.Modules.Games if (data.Length < 3) return; - var poll = new Poll(umsg, data[0], data.Skip(1), isPublic: isPublic); + var poll = new Poll(Context.Message, data[0], data.Skip(1), isPublic: isPublic); if (ActivePolls.TryAdd(channel.Guild, poll)) { await poll.StartPoll().ConfigureAwait(false); @@ -127,10 +128,10 @@ namespace NadekoBot.Modules.Games } } - private Task Vote(IMessage imsg) + private Task Vote(SocketMessage imsg) { // has to be a user message - var msg = imsg as IUserMessage; + var msg = imsg as SocketUserMessage; if (msg == null || imsg.Author.IsBot) return Task.CompletedTask; @@ -156,25 +157,25 @@ namespace NadekoBot.Modules.Games else { //if private, channel must be dm channel - if ((ch = Context.Channel as IDMChannel) == null) + if ((ch = msg.Channel as SocketDMChannel) == null) return; // user must be a member of the guild this poll is in var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); - if (!guildUsers.Any(u => u.Id == Context.User.Id)) + if (!guildUsers.Any(u => u.Id == msg.Author.Id)) return; } //user can vote only once - if (participants.TryAdd(Context.User.Id, vote)) + if (participants.TryAdd(msg.Author.Id, vote)) { if (!isPublic) { - await ch.SendConfirmAsync($"Thanks for voting **{Context.User.Username}**.").ConfigureAwait(false); + await ch.SendConfirmAsync($"Thanks for voting **{msg.Author.Username}**.").ConfigureAwait(false); } else { - var toDelete = await ch.SendConfirmAsync($"{Context.User.Mention} cast their vote.").ConfigureAwait(false); + var toDelete = await ch.SendConfirmAsync($"{msg.Author.Mention} cast their vote.").ConfigureAwait(false); await Task.Delay(5000); await toDelete.DeleteAsync().ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs index ffa8e30d..dfa55eea 100644 --- a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs @@ -16,7 +16,7 @@ namespace NadekoBot.Modules.Games [Group] public class TriviaCommands : ModuleBase { - public static ConcurrentDictionary RunningTrivias = new ConcurrentDictionary(); + public static ConcurrentDictionary RunningTrivias { get; } = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 3903c8a6..5872c16d 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -18,7 +18,8 @@ using System.Text.RegularExpressions; namespace NadekoBot.Modules.Music { - [NadekoModule("Music", "!!", AutoLoad = false)] + [NadekoModule("Music", "!!")] + [DontAutoLoad] public partial class Music : DiscordModule { public static ConcurrentDictionary MusicPlayers { get; } = new ConcurrentDictionary(); @@ -37,7 +38,7 @@ namespace NadekoBot.Modules.Music private async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) { - var usr = iusr as IGuildUser; + var usr = iusr as SocketGuildUser; if (usr == null || oldState.VoiceChannel == newState.VoiceChannel) return; @@ -62,13 +63,11 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public Task Next(int skipCount = 1) { - var channel = (ITextChannel)Context.Channel; - if (skipCount < 1) return Task.CompletedTask; MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return Task.CompletedTask; if (musicPlayer.PlaybackVoiceChannel == ((IGuildUser)Context.User).VoiceChannel) { while (--skipCount > 0) @@ -84,10 +83,8 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public Task Stop() { - var channel = (ITextChannel)Context.Channel; - MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return Task.CompletedTask; if (((IGuildUser)Context.User).VoiceChannel == musicPlayer.PlaybackVoiceChannel) { musicPlayer.Autoplay = false; @@ -100,12 +97,10 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public Task Destroy() { - var channel = (ITextChannel)Context.Channel; - MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return Task.CompletedTask; if (((IGuildUser)Context.User).VoiceChannel == musicPlayer.PlaybackVoiceChannel) - if(MusicPlayers.TryRemove(channel.Guild.Id, out musicPlayer)) + if(MusicPlayers.TryRemove(Context.Guild.Id, out musicPlayer)) musicPlayer.Destroy(); return Task.CompletedTask; } @@ -114,10 +109,8 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public Task Pause() { - var channel = (ITextChannel)Context.Channel; - MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return Task.CompletedTask; if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return Task.CompletedTask; musicPlayer.TogglePause(); @@ -128,10 +121,8 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Queue([Remainder] string query) { - var channel = (ITextChannel)Context.Channel; - - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, query).ConfigureAwait(false); - if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, query).ConfigureAwait(false); + if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -142,10 +133,8 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SoundCloudQueue([Remainder] string query) { - var channel = (ITextChannel)Context.Channel; - - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); - if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); + if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -156,11 +145,11 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task ListQueue(int page = 1) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) { - await channel.SendErrorAsync("๐ŸŽต No active music player.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐ŸŽต No active music player.").ConfigureAwait(false); return; } if (page <= 0) @@ -189,17 +178,15 @@ namespace NadekoBot.Modules.Music const int itemsPerPage = 15; int startAt = itemsPerPage * (page - 1); var number = 1 + startAt; - await channel.SendConfirmAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task NowPlaying() { - var channel = (ITextChannel)Context.Channel; - MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; var currentSong = musicPlayer.CurrentSong; if (currentSong == null) @@ -225,98 +212,97 @@ namespace NadekoBot.Modules.Music { embed.WithThumbnailUrl($"{currentSong.SongInfo.AlbumArt}"); } - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Volume(int val) { - var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (val < 0) return; var volume = musicPlayer.SetVolume(val); - await channel.SendConfirmAsync($"๐ŸŽต Volume set to {volume}%").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽต Volume set to {volume}%").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Defvol([Remainder] int val) { - var channel = (ITextChannel)Context.Channel; + if (val < 0 || val > 100) { - await channel.SendErrorAsync("Volume number invalid. Must be between 0 and 100").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Volume number invalid. Must be between 0 and 100").ConfigureAwait(false); return; } using (var uow = DbHandler.UnitOfWork()) { - uow.GuildConfigs.For(channel.Guild.Id, set => set).DefaultMusicVolume = val / 100.0f; + uow.GuildConfigs.For(Context.Guild.Id, set => set).DefaultMusicVolume = val / 100.0f; uow.Complete(); } - await channel.SendConfirmAsync($"๐ŸŽต Default volume set to {val}%").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽต Default volume set to {val}%").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ShufflePlaylist() { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; if (musicPlayer.Playlist.Count < 2) { - await channel.SendErrorAsync("๐Ÿ’ข Not enough songs in order to perform the shuffle.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ’ข Not enough songs in order to perform the shuffle.").ConfigureAwait(false); return; } musicPlayer.Shuffle(); - await channel.SendConfirmAsync("๐ŸŽต Songs shuffled.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐ŸŽต Songs shuffled.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Playlist([Remainder] string playlist) { - var channel = (ITextChannel)Context.Channel; + var arg = playlist; if (string.IsNullOrWhiteSpace(arg)) return; - if (((IGuildUser)Context.User).VoiceChannel?.Guild != channel.Guild) + if (((IGuildUser)Context.User).VoiceChannel?.Guild != Context.Guild) { - await channel.SendErrorAsync("๐Ÿ’ข You need to be in a **voice channel** on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ’ข You need to be in a **voice channel** on this server.\n If you are already in a voice (ITextChannel)Context.Channel, try rejoining it.").ConfigureAwait(false); return; } var plId = (await NadekoBot.Google.GetPlaylistIdsByKeywordsAsync(arg).ConfigureAwait(false)).FirstOrDefault(); if (plId == null) { - await channel.SendErrorAsync("No search results for that query."); + await Context.Channel.SendErrorAsync("No search results for that query."); return; } var ids = await NadekoBot.Google.GetPlaylistTracksAsync(plId, 500).ConfigureAwait(false); if (!ids.Any()) { - await channel.SendErrorAsync($"๐ŸŽต Failed to find any songs.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"๐ŸŽต Failed to find any songs.").ConfigureAwait(false); return; } var idArray = ids as string[] ?? ids.ToArray(); var count = idArray.Length; var msg = - await channel.SendMessageAsync($"๐ŸŽต Attempting to queue **{count}** songs".SnPl(count) + "...").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"๐ŸŽต Attempting to queue **{count}** songs".SnPl(count) + "...").ConfigureAwait(false); foreach (var id in idArray) { try { - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, id, true).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, id, true).ConfigureAwait(false); } catch (SongNotFoundException) { } catch { break; } @@ -328,7 +314,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SoundCloudPl([Remainder] string pl) { - var channel = (ITextChannel)Context.Channel; + pl = pl?.Trim(); if (string.IsNullOrWhiteSpace(pl)) @@ -337,10 +323,10 @@ namespace NadekoBot.Modules.Music using (var http = new HttpClient()) { var scvids = JObject.Parse(await http.GetStringAsync($"http://api.soundcloud.com/resolve?url={pl}&client_id={NadekoBot.Credentials.SoundCloudClientId}").ConfigureAwait(false))["tracks"].ToObject(); - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, scvids[0].TrackLink).ConfigureAwait(false); MusicPlayer mp; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out mp)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out mp)) return; foreach (var svideo in scvids.Skip(1)) @@ -366,7 +352,7 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task LocalPl([Remainder] string directory) { - var channel = (ITextChannel)Context.Channel; + var arg = directory; if (string.IsNullOrWhiteSpace(arg)) return; @@ -379,7 +365,7 @@ namespace NadekoBot.Modules.Music { try { - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, file.FullName, true, MusicType.Local).ConfigureAwait(false); } catch (PlaylistFullException) { @@ -387,7 +373,7 @@ namespace NadekoBot.Modules.Music } catch { } } - await channel.SendConfirmAsync("๐ŸŽต Directory queue complete.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐ŸŽต Directory queue complete.").ConfigureAwait(false); } catch { } } @@ -396,14 +382,14 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Radio(string radio_link) { - var channel = (ITextChannel)Context.Channel; - if (((IGuildUser)Context.User).VoiceChannel?.Guild != channel.Guild) + + if (((IGuildUser)Context.User).VoiceChannel?.Guild != Context.Guild) { - await channel.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice (ITextChannel)Context.Channel, try rejoining it.").ConfigureAwait(false); return; } - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); - if (channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages) + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); + if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -415,11 +401,11 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task Local([Remainder] string path) { - var channel = (ITextChannel)Context.Channel; + var arg = path; if (string.IsNullOrWhiteSpace(arg)) return; - await QueueSong(((IGuildUser)Context.User), channel, ((IGuildUser)Context.User).VoiceChannel, path, musicType: MusicType.Local).ConfigureAwait(false); + await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, path, musicType: MusicType.Local).ConfigureAwait(false); } @@ -427,10 +413,10 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Move() { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; var voiceChannel = ((IGuildUser)Context.User).VoiceChannel; - if (voiceChannel == null || voiceChannel.Guild != channel.Guild || !MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (voiceChannel == null || voiceChannel.Guild != Context.Guild || !MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; await musicPlayer.MoveToVoiceChannel(voiceChannel); } @@ -440,10 +426,10 @@ namespace NadekoBot.Modules.Music [Priority(0)] public async Task Remove(int num) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) { return; } @@ -453,7 +439,7 @@ namespace NadekoBot.Modules.Music return; var song = (musicPlayer.Playlist as List)?[num - 1]; musicPlayer.RemoveSongAt(num - 1); - await channel.SendConfirmAsync($"๐ŸŽต Track {song.PrettyName} at position `#{num}` has been **removed**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽต Track {song.PrettyName} at position `#{num}` has been **removed**.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -461,14 +447,14 @@ namespace NadekoBot.Modules.Music [Priority(1)] public async Task Remove(string all) { - var channel = (ITextChannel)Context.Channel; + if (all.Trim().ToUpperInvariant() != "ALL") return; MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; musicPlayer.ClearQueue(); - await channel.SendConfirmAsync($"๐ŸŽต Queue cleared!").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽต Queue cleared!").ConfigureAwait(false); return; } @@ -476,9 +462,9 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task MoveSong([Remainder] string fromto) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) { return; } @@ -494,7 +480,7 @@ namespace NadekoBot.Modules.Music !int.TryParse(fromtoArr[1], out n2) || n1 < 1 || n2 < 1 || n1 == n2 || n1 > playlist.Count || n2 > playlist.Count) { - await channel.SendErrorAsync("Invalid input.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Invalid input.").ConfigureAwait(false); return; } @@ -502,15 +488,15 @@ namespace NadekoBot.Modules.Music playlist.Insert(n2 - 1, s); var nn1 = n2 < n1 ? n1 : n1 - 1; playlist.RemoveAt(nn1); - - var embed = new EmbedBuilder() - .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") - .WithUrl($"{s.SongInfo.Query}") - .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) - .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) - .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) - .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed).ConfigureAwait(false); + + var embed = new EmbedBuilder() + .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") + .WithUrl($"{s.SongInfo.Query}") + .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) + .AddField(fb => fb.WithName("**From**").WithValue($"#{n1}").WithIsInline(true)) + .AddField(fb => fb.WithName("**To**").WithValue($"#{n2}").WithIsInline(true)) + .WithColor(NadekoBot.OkColor); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); //await channel.SendConfirmAsync($"๐ŸŽตMoved {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); @@ -521,29 +507,28 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SetMaxQueue(uint size) { - var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) { return; } musicPlayer.MaxQueueSize = size; - await channel.SendConfirmAsync($"๐ŸŽต Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}."); + await Context.Channel.SendConfirmAsync($"๐ŸŽต Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}."); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ReptCurSong() { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; var currentSong = musicPlayer.CurrentSong; if (currentSong == null) return; var currentValue = musicPlayer.ToggleRepeatSong(); - await channel.SendConfirmAsync(currentValue ? + await Context.Channel.SendConfirmAsync(currentValue ? $"๐Ÿ”‚ Repeating track: {currentSong.PrettyName}" : $"๐Ÿ”‚ Current track repeat stopped.") .ConfigureAwait(false); @@ -553,21 +538,21 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task RepeatPl() { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; var currentValue = musicPlayer.ToggleRepeatPlaylist(); - await channel.SendConfirmAsync($"๐Ÿ” Repeat playlist {(currentValue ? "**enabled**." : "**disabled**.")}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ” Repeat playlist {(currentValue ? "**enabled**." : "**disabled**.")}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Save([Remainder] string name) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; var curSong = musicPlayer.CurrentSong; @@ -594,15 +579,13 @@ namespace NadekoBot.Modules.Music await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync(($"๐ŸŽต Saved playlist as **{name}**, ID: {playlist.Id}.")).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync(($"๐ŸŽต Saved playlist as **{name}**, ID: {playlist.Id}.")).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Load([Remainder] int id) { - var channel = (ITextChannel)Context.Channel; - MusicPlaylist mpl; using (var uow = DbHandler.UnitOfWork()) { @@ -611,17 +594,17 @@ namespace NadekoBot.Modules.Music if (mpl == null) { - await channel.SendErrorAsync("Can't find playlist with that ID.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Can't find playlist with that ID.").ConfigureAwait(false); return; } IUserMessage msg = null; - try { msg = await channel.SendMessageAsync($"๐ŸŽถ Attempting to load **{mpl.Songs.Count}** songs...").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { msg = await Context.Channel.SendMessageAsync($"๐ŸŽถ Attempting to load **{mpl.Songs.Count}** songs...").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } foreach (var item in mpl.Songs) { var usr = (IGuildUser)Context.User; try { - await QueueSong(usr, channel, usr.VoiceChannel, item.Query, true, item.ProviderType).ConfigureAwait(false); + await QueueSong(usr, (ITextChannel)Context.Channel, usr.VoiceChannel, item.Query, true, item.ProviderType).ConfigureAwait(false); } catch (SongNotFoundException) { } catch { break; } @@ -634,7 +617,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Playlists([Remainder] int num = 1) { - var channel = (ITextChannel)Context.Channel; + if (num <= 0) return; @@ -646,7 +629,7 @@ namespace NadekoBot.Modules.Music playlists = uow.MusicPlaylists.GetPlaylistsOnPage(num); } - await channel.SendConfirmAsync($@"๐ŸŽถ **Page {num} of saved playlists:** + await Context.Channel.SendConfirmAsync($@"๐ŸŽถ **Page {num} of saved playlists:** " + string.Join("\n", playlists.Select(r => $"`#{r.Id}` - **{r.Name}** by __{r.Author}__ ({r.Songs.Count} songs)"))).ConfigureAwait(false); } @@ -656,7 +639,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task DeletePlaylist([Remainder] int id) { - var channel = (ITextChannel)Context.Channel; + bool success = false; MusicPlaylist pl = null; @@ -680,9 +663,9 @@ namespace NadekoBot.Modules.Music } if (!success) - await channel.SendErrorAsync("Failed to delete that playlist. It either doesn't exist, or you are not its author.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed to delete that playlist. It either doesn't exist, or you are not its author.").ConfigureAwait(false); else - await channel.SendConfirmAsync("๐Ÿ—‘ Playlist successfully **deleted**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿ—‘ Playlist successfully **deleted**.").ConfigureAwait(false); } catch (Exception ex) { @@ -694,10 +677,10 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Goto(int time) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; @@ -724,16 +707,16 @@ namespace NadekoBot.Modules.Music if (seconds.Length == 1) seconds = "0" + seconds; - await channel.SendConfirmAsync($"Skipped to `{minutes}:{seconds}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Skipped to `{minutes}:{seconds}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task GetLink(int index = 0) { - var channel = (ITextChannel)Context.Channel; + MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; if (index < 0) @@ -745,12 +728,12 @@ namespace NadekoBot.Modules.Music var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1); if (selSong == null) { - await channel.SendErrorAsync("Could not select song, likely wrong index"); + await Context.Channel.SendErrorAsync("Could not select song, likely wrong index"); } else { - await channel.SendConfirmAsync($"๐ŸŽถ Selected song **{selSong.SongInfo.Title}**: <{selSong.SongInfo.Query}>").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽถ Selected song **{selSong.SongInfo.Title}**: <{selSong.SongInfo.Query}>").ConfigureAwait(false); } } else @@ -758,7 +741,7 @@ namespace NadekoBot.Modules.Music var curSong = musicPlayer.CurrentSong; if (curSong == null) return; - await channel.SendConfirmAsync($"๐ŸŽถ Current song **{curSong.SongInfo.Title}**: <{curSong.SongInfo.Query}>").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐ŸŽถ Current song **{curSong.SongInfo.Title}**: <{curSong.SongInfo.Query}>").ConfigureAwait(false); } } @@ -766,15 +749,14 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Autoplay() { - var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; - if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) + if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; if (!musicPlayer.ToggleAutoplay()) - await channel.SendConfirmAsync("โŒ Autoplay disabled.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โŒ Autoplay disabled.").ConfigureAwait(false); else - await channel.SendConfirmAsync("โœ… Autoplay enabled.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โœ… Autoplay enabled.").ConfigureAwait(false); } public static async Task QueueSong(IGuildUser queuer, ITextChannel textCh, IVoiceChannel voiceCh, string query, bool silent = false, MusicType musicType = MusicType.Normal) @@ -782,7 +764,7 @@ namespace NadekoBot.Modules.Music if (voiceCh == null || voiceCh.Guild != textCh.Guild) { if (!silent) - await textCh.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining.").ConfigureAwait(false); + await textCh.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice (ITextChannel)Context.Channel, try rejoining.").ConfigureAwait(false); throw new ArgumentNullException(nameof(voiceCh)); } if (string.IsNullOrWhiteSpace(query) || query.Length < 3) diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index c6913a56..e4b0fa29 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -1,5 +1,4 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using Newtonsoft.Json.Linq; using System; diff --git a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs index 9a1489e7..02f752a4 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs +++ b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using NadekoBot.Services.Database.Models; using System; using System.Collections.Generic; diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index d71a991f..5c50f075 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -48,13 +48,11 @@ namespace NadekoBot.Modules.Permissions [RequireContext(ContextType.Guild)] public async Task Verbose(PermissionAction action) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); config.VerbosePermissions = action.Value; - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = Permission.GetDefaultRoot(), @@ -63,25 +61,24 @@ namespace NadekoBot.Modules.Permissions await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync("โ„น๏ธ I will " + (action.Value ? "now" : "no longer") + " show permission warnings.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("โ„น๏ธ I will " + (action.Value ? "now" : "no longer") + " show permission warnings.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task PermRole([Remainder] IRole role = null) { - var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.For(channel.Guild.Id, set => set); + var config = uow.GuildConfigs.For(Context.Guild.Id, set => set); if (role == null) { - await channel.SendConfirmAsync($"โ„น๏ธ Current permission role is **{config.PermissionRole}**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Current permission role is **{config.PermissionRole}**.").ConfigureAwait(false); return; } else { config.PermissionRole = role.Name.Trim(); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = Permission.GetDefaultRoot(), @@ -91,40 +88,37 @@ namespace NadekoBot.Modules.Permissions } } - await channel.SendConfirmAsync($"Users now require **{role.Name}** role in order to edit permissions.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Users now require **{role.Name}** role in order to edit permissions.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task ListPerms(int page = 1) { - var channel = (ITextChannel)Context.Channel; - if (page < 1 || page > 4) return; string toSend = ""; using (var uow = DbHandler.UnitOfWork()) { - var perms = uow.GuildConfigs.PermissionsFor(channel.Guild.Id).RootPermission; + var perms = uow.GuildConfigs.PermissionsFor(Context.Guild.Id).RootPermission; var i = 1 + 20 * (page - 1); - toSend = Format.Code($"๐Ÿ“„ Permissions page {page}") + "\n\n" + String.Join("\n", perms.AsEnumerable().Skip((page - 1) * 20).Take(20).Select(p => $"`{(i++)}.` {(p.Next == null ? Format.Bold(p.GetCommand(channel.Guild) + " [uneditable]") : (p.GetCommand(channel.Guild)))}")); + toSend = Format.Code($"๐Ÿ“„ Permissions page {page}") + "\n\n" + String.Join("\n", perms.AsEnumerable().Skip((page - 1) * 20).Take(20).Select(p => $"`{(i++)}.` {(p.Next == null ? Format.Bold(p.GetCommand(Context.Guild) + " [uneditable]") : (p.GetCommand(Context.Guild)))}")); } - await channel.SendMessageAsync(toSend).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(toSend).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RemovePerm(IUserMessage imsg, int index) + public async Task RemovePerm(int index) { - var channel = (ITextChannel)Context.Channel; index -= 1; try { Permission p; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.PermissionsFor(channel.Guild.Id); + var config = uow.GuildConfigs.PermissionsFor(Context.Guild.Id); var perms = config.RootPermission; if (index == perms.Count() - 1) { @@ -139,7 +133,7 @@ namespace NadekoBot.Modules.Permissions { p = perms.RemoveAt(index); } - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -154,21 +148,20 @@ namespace NadekoBot.Modules.Permissions uow2._context.SaveChanges(); } - await channel.SendConfirmAsync($"โœ… {Context.User.Mention} removed permission **{p.GetCommand(channel.Guild)}** from position #{index + 1}.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ… {Context.User.Mention} removed permission **{p.GetCommand(Context.Guild)}** from position #{index + 1}.").ConfigureAwait(false); } catch (ArgumentOutOfRangeException) { - await channel.SendErrorAsync("โ—๏ธ`No command on that index found.`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("โ—๏ธ`No command on that index found.`").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task MovePerm(IUserMessage imsg, int from, int to) + public async Task MovePerm(int from, int to) { from -= 1; to -= 1; - var channel = (ITextChannel)Context.Channel; if (!(from == to || from < 0 || to < 0)) { try @@ -177,7 +170,7 @@ namespace NadekoBot.Modules.Permissions Permission toPerm = null; using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.PermissionsFor(channel.Guild.Id); + var config = uow.GuildConfigs.PermissionsFor(Context.Guild.Id); var perms = config.RootPermission; var root = perms; var index = 0; @@ -206,13 +199,13 @@ namespace NadekoBot.Modules.Permissions { if (!fromFound) { - await channel.SendErrorAsync($"Can't find permission at index `#{++from}`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Can't find permission at index `#{++from}`").ConfigureAwait(false); return; } if (!toFound) { - await channel.SendErrorAsync($"Can't find permission at index `#{++to}`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Can't find permission at index `#{++to}`").ConfigureAwait(false); return; } } @@ -254,7 +247,7 @@ namespace NadekoBot.Modules.Permissions } config.RootPermission = fromPerm.GetRoot(); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -262,22 +255,20 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"`Moved permission:` \"{fromPerm.GetCommand(channel.Guild)}\" `from #{++from} to #{++to}.`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"`Moved permission:` \"{fromPerm.GetCommand(Context.Guild)}\" `from #{++from} to #{++to}.`").ConfigureAwait(false); return; } catch (Exception e) when (e is ArgumentOutOfRangeException || e is IndexOutOfRangeException) { } } - await channel.SendErrorAsync("`Invalid index(es) specified.`").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("`Invalid index(es) specified.`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrCmd(IUserMessage imsg, CommandInfo command, PermissionAction action) + public async Task SrvrCmd(CommandInfo command, PermissionAction action) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -288,8 +279,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -298,15 +289,13 @@ namespace NadekoBot.Modules.Permissions await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command on this server.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task SrvrMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action) + public async Task SrvrMdl(ModuleInfo module, PermissionAction action) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -317,8 +306,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = module.Name.ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -326,15 +315,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of **`{module.Name}`** module on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of **`{module.Name}`** module on this server.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UsrCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] IGuildUser user) + public async Task UsrCmd(CommandInfo command, PermissionAction action, [Remainder] IGuildUser user) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -345,8 +332,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -354,15 +341,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{user}` user.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{user}` user.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task UsrMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] IGuildUser user) + public async Task UsrMdl(ModuleInfo module, PermissionAction action, [Remainder] IGuildUser user) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -373,8 +358,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = module.Name.ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -382,15 +367,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{user}` user.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{user}` user.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RoleCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] IRole role) + public async Task RoleCmd(CommandInfo command, PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -401,8 +384,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -410,15 +393,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{role}` role.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{role}` role.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task RoleMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] IRole role) + public async Task RoleMdl(ModuleInfo module, PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -429,8 +410,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = module.Name.ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -438,14 +419,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{role}` role.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{role}` role.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlCmd(IUserMessage imsg, CommandInfo command, PermissionAction action, [Remainder] ITextChannel chnl) + public async Task ChnlCmd(CommandInfo command, PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)Context.Channel; try { using (var uow = DbHandler.UnitOfWork()) @@ -458,8 +438,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = command.Aliases.First().ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -471,15 +451,13 @@ namespace NadekoBot.Modules.Permissions catch (Exception ex) { _log.Error(ex); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{chnl}` channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{command.Aliases.First()}` command for `{chnl}` channel.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ChnlMdl(IUserMessage imsg, ModuleInfo module, PermissionAction action, [Remainder] ITextChannel chnl) + public async Task ChnlMdl(ModuleInfo module, PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -490,8 +468,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = module.Name.ToLowerInvariant(), State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -499,15 +477,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{chnl}` channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `{module.Name}` module for `{chnl}` channel.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AllChnlMdls(IUserMessage imsg, PermissionAction action, [Remainder] ITextChannel chnl) + public async Task AllChnlMdls(PermissionAction action, [Remainder] ITextChannel chnl) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -518,8 +494,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = "*", State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -527,15 +503,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{chnl}` channel.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{chnl}` channel.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AllRoleMdls(IUserMessage imsg, PermissionAction action, [Remainder] IRole role) + public async Task AllRoleMdls(PermissionAction action, [Remainder] IRole role) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -546,8 +520,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = "*", State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -555,15 +529,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{role}` role.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{role}` role.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AllUsrMdls(IUserMessage imsg, PermissionAction action, [Remainder] IUser user) + public async Task AllUsrMdls(PermissionAction action, [Remainder] IUser user) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -574,8 +546,8 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = "*", State = action.Value, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -583,15 +555,13 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{user}` user.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` for `{user}` user.").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AllSrvrMdls(IUserMessage imsg, PermissionAction action) + public async Task AllSrvrMdls(PermissionAction action) { - var channel = (ITextChannel)Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { var newPerm = new Permission @@ -602,7 +572,7 @@ namespace NadekoBot.Modules.Permissions SecondaryTargetName = "*", State = action.Value, }; - uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, newPerm); + uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, newPerm); var allowUser = new Permission { @@ -613,8 +583,8 @@ namespace NadekoBot.Modules.Permissions State = true, }; - var config = uow.GuildConfigs.SetNewRootPermission(channel.Guild.Id, allowUser); - Cache.AddOrUpdate(channel.Guild.Id, new PermissionCache() + var config = uow.GuildConfigs.SetNewRootPermission(Context.Guild.Id, allowUser); + Cache.AddOrUpdate(Context.Guild.Id, new PermissionCache() { PermRole = config.PermissionRole, RootPermission = config.RootPermission, @@ -622,7 +592,7 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` on this server.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{(action.Value ? "โœ… Allowed" : "๐Ÿ†— Denied")} usage of `ALL MODULES` on this server.").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Pokemon/Pokemon.cs b/src/NadekoBot/Modules/Pokemon/Pokemon.cs index 5000dcb9..51a4f1af 100644 --- a/src/NadekoBot/Modules/Pokemon/Pokemon.cs +++ b/src/NadekoBot/Modules/Pokemon/Pokemon.cs @@ -96,9 +96,8 @@ namespace NadekoBot.Modules.Pokemon [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Attack(IUserMessage umsg, string move, IGuildUser targetUser = null) + public async Task Attack(string move, IGuildUser targetUser = null) { - var channel = (ITextChannel)Context.Channel; IGuildUser user = (IGuildUser)Context.User; if (string.IsNullOrWhiteSpace(move)) { @@ -107,12 +106,12 @@ namespace NadekoBot.Modules.Pokemon if (targetUser == null) { - await channel.SendMessageAsync("No such person.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("No such person.").ConfigureAwait(false); return; } else if (targetUser == user) { - await channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false); return; } @@ -126,17 +125,17 @@ namespace NadekoBot.Modules.Pokemon //User not able if HP < 0, has made more than 4 attacks if (userStats.Hp < 0) { - await channel.SendMessageAsync($"{user.Mention} has fainted and was not able to move!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} has fainted and was not able to move!").ConfigureAwait(false); return; } if (userStats.MovesMade >= 5) { - await channel.SendMessageAsync($"{user.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false); return; } if (userStats.LastAttacked.Contains(targetUser.Id)) { - await channel.SendMessageAsync($"{user.Mention} can't attack again without retaliation!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} can't attack again without retaliation!").ConfigureAwait(false); return; } //get target stats @@ -146,7 +145,7 @@ namespace NadekoBot.Modules.Pokemon //If target's HP is below 0, no use attacking if (targetStats.Hp <= 0) { - await channel.SendMessageAsync($"{targetUser.Mention} has already fainted!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{targetUser.Mention} has already fainted!").ConfigureAwait(false); return; } @@ -156,7 +155,7 @@ namespace NadekoBot.Modules.Pokemon var enabledMoves = userType.Moves; if (!enabledMoves.Contains(move.ToLowerInvariant())) { - await channel.SendMessageAsync($"{user.Mention} is not able to use **{move}**. Type {NadekoBot.ModulePrefixes[typeof(Pokemon).Name]}ml to see moves").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} is not able to use **{move}**. Type {NadekoBot.ModulePrefixes[typeof(Pokemon).Name]}ml to see moves").ConfigureAwait(false); return; } @@ -208,7 +207,7 @@ namespace NadekoBot.Modules.Pokemon Stats[user.Id] = userStats; Stats[targetUser.Id] = targetStats; - await channel.SendMessageAsync(response).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(response).ConfigureAwait(false); } @@ -216,7 +215,6 @@ namespace NadekoBot.Modules.Pokemon [RequireContext(ContextType.Guild)] public async Task Movelist() { - var channel = (ITextChannel)Context.Channel; IGuildUser user = (IGuildUser)Context.User; var userType = GetPokeType(user.Id); @@ -226,18 +224,17 @@ namespace NadekoBot.Modules.Pokemon { str += $"\n{userType.Icon}{m}"; } - await channel.SendMessageAsync(str).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(str).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Heal(IUserMessage umsg, IGuildUser targetUser = null) + public async Task Heal(IGuildUser targetUser = null) { - var channel = (ITextChannel)Context.Channel; IGuildUser user = (IGuildUser)Context.User; if (targetUser == null) { - await channel.SendMessageAsync("No such person.").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("No such person.").ConfigureAwait(false); return; } @@ -246,7 +243,7 @@ namespace NadekoBot.Modules.Pokemon var targetStats = Stats[targetUser.Id]; if (targetStats.Hp == targetStats.MaxHp) { - await channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false); return; } //Payment~ @@ -257,7 +254,7 @@ namespace NadekoBot.Modules.Pokemon { if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"Poke-Heal {target}", amount, true).ConfigureAwait(false)) { - try { await channel.SendMessageAsync($"{user.Mention} You don't have enough {CurrencyName}s.").ConfigureAwait(false); } catch { } + try { await Context.Channel.SendMessageAsync($"{user.Mention} You don't have enough {CurrencyName}s.").ConfigureAwait(false); } catch { } return; } } @@ -270,29 +267,28 @@ namespace NadekoBot.Modules.Pokemon Stats[targetUser.Id].Hp = (targetStats.MaxHp / 2); if (target == "yourself") { - await channel.SendMessageAsync($"You revived yourself with one {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"You revived yourself with one {CurrencySign}").ConfigureAwait(false); } else { - await channel.SendMessageAsync($"{user.Mention} revived {targetUser.Mention} with one {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} revived {targetUser.Mention} with one {CurrencySign}").ConfigureAwait(false); } return; } - await channel.SendMessageAsync($"{user.Mention} healed {targetUser.Mention} with one {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{user.Mention} healed {targetUser.Mention} with one {CurrencySign}").ConfigureAwait(false); return; } else { - await channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"{targetUser.Mention} already has full HP!").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Type(IUserMessage umsg, IGuildUser targetUser = null) + public async Task Type(IGuildUser targetUser = null) { - var channel = (ITextChannel)Context.Channel; IGuildUser user = (IGuildUser)Context.User; if (targetUser == null) @@ -301,26 +297,29 @@ namespace NadekoBot.Modules.Pokemon } var pType = GetPokeType(targetUser.Id); - await channel.SendMessageAsync($"Type of {targetUser.Mention} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"Type of {targetUser.Mention} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Settype(IUserMessage umsg, [Remainder] string typeTargeted = null) + public async Task Settype([Remainder] string typeTargeted = null) { - var channel = (ITextChannel)Context.Channel; IGuildUser user = (IGuildUser)Context.User; var targetType = StringToPokemonType(typeTargeted); if (targetType == null) { - await channel.EmbedAsync(PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"), (eb, pt) => eb.AddField(efb => efb.WithName(pt.Name).WithValue(pt.Icon).WithIsInline(true))).WithColor(NadekoBot.OkColor)).ConfigureAwait(false); + await Context.Channel.EmbedAsync(PokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"), + (eb, pt) => eb.AddField(efb => efb.WithName(pt.Name) + .WithValue(pt.Icon) + .WithIsInline(true))) + .WithColor(NadekoBot.OkColor)).ConfigureAwait(false); return; } if (targetType == GetPokeType(user.Id)) { - await channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false); return; } @@ -330,7 +329,7 @@ namespace NadekoBot.Modules.Pokemon { if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"{user.Mention} change type to {typeTargeted}", amount, true).ConfigureAwait(false)) { - try { await channel.SendMessageAsync($"{user.Mention} You don't have enough {CurrencyName}s.").ConfigureAwait(false); } catch { } + try { await Context.Channel.SendMessageAsync($"{user.Mention} You don't have enough {CurrencyName}s.").ConfigureAwait(false); } catch { } return; } } @@ -363,7 +362,7 @@ namespace NadekoBot.Modules.Pokemon } //Now for the response - await channel.SendMessageAsync($"Set type of {user.Mention} to {typeTargeted}{targetType.Icon} for a {CurrencySign}").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"Set type of {user.Mention} to {typeTargeted}{targetType.Icon} for a {CurrencySign}").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Pokemon/PokemonType.cs b/src/NadekoBot/Modules/Pokemon/PokemonType.cs index d4cf9007..b73dec6b 100644 --- a/src/NadekoBot/Modules/Pokemon/PokemonType.cs +++ b/src/NadekoBot/Modules/Pokemon/PokemonType.cs @@ -1,8 +1,4 @@ -๏ปฟusing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +๏ปฟusing System.Collections.Generic; namespace NadekoBot.Modules.Pokemon { diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index d3444687..66402bb4 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -1,5 +1,4 @@ ๏ปฟusing Discord; -using Discord.API; using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; diff --git a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs index f84f9469..18da480c 100644 --- a/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/JokeCommands.cs @@ -1,5 +1,4 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Models; @@ -43,7 +42,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Yomama() { using (var http = new HttpClient()) @@ -54,7 +52,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Randjoke() { using (var http = new HttpClient()) @@ -65,7 +62,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task ChuckNorris() { using (var http = new HttpClient()) @@ -76,7 +72,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task WowJoke() { if (!wowJokes.Any()) @@ -89,7 +84,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task MagicItem() { if (!wowJokes.Any()) diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index 991fec8f..d7b3a857 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -1,5 +1,4 @@ ๏ปฟusing Discord; -using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -8,7 +7,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; -using System.Text; using System.Threading.Tasks; //todo drawing @@ -33,7 +31,6 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Lolban() { var showCount = 8; diff --git a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs index f4e1d317..5f7b0064 100644 --- a/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/MemegenCommands.cs @@ -1,10 +1,8 @@ -using Discord.Commands; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; -using Discord; using System.Threading.Tasks; using NadekoBot.Attributes; using System.Net.Http; @@ -15,7 +13,6 @@ namespace NadekoBot.Modules.Searches public partial class Searches { [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Memelist() { HttpClientHandler handler = new HttpClientHandler(); @@ -33,8 +30,7 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Memegen(IUserMessage umsg, string meme, string topText, string botText) + public async Task Memegen(string meme, string topText, string botText) { var top = Uri.EscapeDataString(topText.Replace(' ', '-')); var bot = Uri.EscapeDataString(botText.Replace(' ', '-')); diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/AnimeResult.cs b/src/NadekoBot/Modules/Searches/Commands/Models/AnimeResult.cs index 3d08da6e..f855c959 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/AnimeResult.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/AnimeResult.cs @@ -1,5 +1,4 @@ ๏ปฟusing NadekoBot.Extensions; -using System.Globalization; namespace NadekoBot.Modules.Searches.Models { diff --git a/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs b/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs index 3c6399f5..9d57f52a 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Models/OverwatchApiModel.cs @@ -1,6 +1,5 @@ using Newtonsoft.Json; using System; -using System.Collections.Generic; using System.Text.RegularExpressions; namespace NadekoBot.Modules.Searches.Models diff --git a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs index 9b4c0c1b..1ba35e02 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OMDB/OmdbProvider.cs @@ -1,5 +1,4 @@ ๏ปฟusing Discord; -using Discord.API; using Newtonsoft.Json; using System; using System.Net.Http; diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index fa665d5b..8d507d2f 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -58,13 +58,11 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Osub(IUserMessage umsg, [Remainder] string map) + public async Task Osub([Remainder] string map) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) { - await channel.SendErrorAsync("An osu! API key is required.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("An osu! API key is required.").ConfigureAwait(false); return; } @@ -83,19 +81,18 @@ namespace NadekoBot.Modules.Searches var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss"); sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}"); sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}"); - await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false); } } catch (Exception ex) { - await channel.SendErrorAsync("Something went wrong."); + await Context.Channel.SendErrorAsync("Something went wrong."); _log.Warn(ex, "Osub command failed"); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Osu5(IUserMessage umsg, string user, [Remainder] string mode = null) + public async Task Osu5(string user, [Remainder] string mode = null) { var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) diff --git a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs index ca1d1a7d..258bad9b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs @@ -3,10 +3,7 @@ using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Models; -using Newtonsoft.Json; -using NLog; -using System; -using System.Linq; +using Newtonsoft.Json; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -18,18 +15,12 @@ namespace NadekoBot.Modules.Searches [Group] public class OverwatchCommands : ModuleBase { - private Logger _log; - public OverwatchCommands() - { - _log = LogManager.GetCurrentClassLogger(); - } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Overwatch(IUserMessage umsg, string region, [Remainder] string query = null) + public async Task Overwatch(string region, [Remainder] string query = null) { if (string.IsNullOrWhiteSpace(query)) return; - var battletag = Regex.Replace(query, "#", "-", RegexOptions.IgnoreCase); + var battletag = query.Replace("#", "-"); try { var model = await GetProfile(region, battletag); diff --git a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs index 513a4e80..df53ae32 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs @@ -1,5 +1,4 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -32,7 +31,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Placelist() { await Context.Channel.SendConfirmAsync(typesStr) @@ -40,8 +38,7 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Place(IUserMessage imsg, PlaceType placeType, uint width = 0, uint height = 0) + public async Task Place(PlaceType placeType, uint width = 0, uint height = 0) { string url = ""; switch (placeType) diff --git a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs index 31269b00..9f33c789 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PokemonSearchCommands.cs @@ -41,7 +41,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Pokemon([Remainder] string pokemon = null) { pokemon = pokemon?.Trim().ToUpperInvariant(); @@ -67,7 +66,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task PokemonAbility([Remainder] string ability = null) { ability = ability?.Trim().ToUpperInvariant().Replace(" ", ""); diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 99d2fd03..fd010b19 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -1,22 +1,18 @@ ๏ปฟusing Discord.Commands; using Discord; -using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; -using Discord; using NadekoBot.Services; using System.Threading; using System.Collections.Generic; using NadekoBot.Services.Database.Models; using System.Net.Http; -using Discord.WebSocket; using NadekoBot.Attributes; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using NLog; -using NadekoBot.Services.Database; using NadekoBot.Extensions; namespace NadekoBot.Modules.Searches diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index 113eca2f..121ff140 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -53,7 +53,7 @@ namespace NadekoBot.Modules.Searches try { - var text = await TranslateInternal(umsg, langs, umsg.Resolve(userHandling: TagHandling.Ignore), true) + var text = await TranslateInternal(langs, umsg.Resolve(userHandling: TagHandling.Ignore), true) .ConfigureAwait(false); if (autoDelete) try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { } @@ -67,24 +67,21 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Translate(IUserMessage umsg, string langs, [Remainder] string text = null) { - var channel = (ITextChannel)Context.Channel; - try { await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); - var translation = await TranslateInternal(umsg, langs, text); - await channel.SendConfirmAsync("Translation " + langs, translation).ConfigureAwait(false); + var translation = await TranslateInternal(langs, text); + await Context.Channel.SendConfirmAsync("Translation " + langs, translation).ConfigureAwait(false); } catch { - await channel.SendErrorAsync("Bad input format, or something went wrong...").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Bad input format, or something went wrong...").ConfigureAwait(false); } } - private static async Task TranslateInternal(IUserMessage umsg, string langs, [Remainder] string text = null, bool silent = false) + private static async Task TranslateInternal(string langs, [Remainder] string text = null, bool silent = false) { var langarr = langs.ToLowerInvariant().Split('>'); if (langarr.Length != 2) diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 98ce1f78..8b916ed0 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -25,9 +25,8 @@ namespace NadekoBot.Modules.Searches { [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Weather(IUserMessage umsg, string city, string country) + public async Task Weather(string city, string country) { - var channel = (ITextChannel)Context.Channel; city = city.Replace(" ", ""); country = city.Replace(" ", ""); string response; @@ -47,75 +46,63 @@ namespace NadekoBot.Modules.Searches .AddField(fb => fb.WithName("๐ŸŒ„ **Sunrise**").WithValue($"{obj["sunrise"]}").WithIsInline(true)) .AddField(fb => fb.WithName("๐ŸŒ‡ **Sunset**").WithValue($"{obj["sunset"]}").WithIsInline(true)) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Youtube(IUserMessage umsg, [Remainder] string query = null) + public async Task Youtube([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - if (!(await ValidateQuery(channel, query).ConfigureAwait(false))) return; + if (!(await ValidateQuery(Context.Channel, query).ConfigureAwait(false))) return; var result = (await NadekoBot.Google.GetVideosByKeywordsAsync(query, 1)).FirstOrDefault(); if (string.IsNullOrWhiteSpace(result)) { - await channel.SendErrorAsync("No results found for that query.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No results found for that query.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(result).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(result).ConfigureAwait(false); - //await channel.EmbedAsync(new Discord.API.Embed() { Video = new Discord.API.EmbedVideo() { Url = result.Replace("watch?v=", "embed/") }, Color = NadekoBot.OkColor }).ConfigureAwait(false); + //await Context.Channel.EmbedAsync(new Discord.API.Embed() { Video = new Discord.API.EmbedVideo() { Url = result.Replace("watch?v=", "embed/") }, Color = NadekoBot.OkColor }).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Imdb(IUserMessage umsg, [Remainder] string query = null) + public async Task Imdb([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - - if (!(await ValidateQuery(channel, query).ConfigureAwait(false))) return; + if (!(await ValidateQuery(Context.Channel, query).ConfigureAwait(false))) return; await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); var movie = await OmdbProvider.FindMovie(query); if (movie == null) { - await channel.SendErrorAsync("Failed to find that movie.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed to find that movie.").ConfigureAwait(false); return; } - await channel.EmbedAsync(movie.GetEmbed()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(movie.GetEmbed()).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task RandomCat() { - var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { var res = JObject.Parse(await http.GetStringAsync("http://www.random.cat/meow").ConfigureAwait(false)); - await channel.SendMessageAsync(res["file"].ToString()).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(res["file"].ToString()).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task RandomDog() { - var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { - await channel.SendMessageAsync("http://random.dog/" + await http.GetStringAsync("http://random.dog/woof") + await Context.Channel.SendMessageAsync("http://random.dog/" + await http.GetStringAsync("http://random.dog/woof") .ConfigureAwait(false)).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task I(IUserMessage umsg, [Remainder] string query = null) + public async Task I([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(query)) return; try @@ -124,29 +111,26 @@ namespace NadekoBot.Modules.Searches { var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(query)}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.Credentials.GoogleApiKey}"; var obj = JObject.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); - await channel.SendMessageAsync(obj["items"][0]["link"].ToString()).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(obj["items"][0]["link"].ToString()).ConfigureAwait(false); } } catch (HttpRequestException exception) { if (exception.Message.Contains("403 (Forbidden)")) { - await channel.SendErrorAsync("Daily limit reached!"); + await Context.Channel.SendErrorAsync("Daily limit reached!"); } else { - await channel.SendErrorAsync("Something went wrong."); + await Context.Channel.SendErrorAsync("Something went wrong."); _log.Error(exception); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Ir(IUserMessage umsg, [Remainder] string query = null) + public async Task Ir([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(query)) return; try @@ -157,39 +141,34 @@ namespace NadekoBot.Modules.Searches var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(query)}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 50) }&fields=items%2Flink&key={NadekoBot.Credentials.GoogleApiKey}"; var obj = JObject.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); var items = obj["items"] as JArray; - await channel.SendMessageAsync(items[0]["link"].ToString()).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(items[0]["link"].ToString()).ConfigureAwait(false); } } catch (HttpRequestException exception) { if (exception.Message.Contains("403 (Forbidden)")) { - await channel.SendErrorAsync("Daily limit reached!"); + await Context.Channel.SendErrorAsync("Daily limit reached!"); } else { - await channel.SendErrorAsync("Something went wrong."); + await Context.Channel.SendErrorAsync("Something went wrong."); _log.Error(exception); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Lmgtfy(IUserMessage umsg, [Remainder] string ffs = null) + public async Task Lmgtfy([Remainder] string ffs = null) { - var channel = (ITextChannel)Context.Channel; - - if (string.IsNullOrWhiteSpace(ffs)) return; - await channel.SendConfirmAsync(await NadekoBot.Google.ShortenUrl($"")) + await Context.Channel.SendConfirmAsync(await NadekoBot.Google.ShortenUrl($"")) .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Shorten([Remainder] string arg) { if (string.IsNullOrWhiteSpace(arg)) @@ -211,28 +190,23 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Google(IUserMessage umsg, [Remainder] string terms = null) + public async Task Google([Remainder] string terms = null) { - var channel = (ITextChannel)Context.Channel; - terms = terms?.Trim(); if (string.IsNullOrWhiteSpace(terms)) return; - await channel.SendConfirmAsync($"https://google.com/search?q={ WebUtility.UrlEncode(terms).Replace(' ', '+') }") + await Context.Channel.SendConfirmAsync($"https://google.com/search?q={ WebUtility.UrlEncode(terms).Replace(' ', '+') }") .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task MagicTheGathering(IUserMessage umsg, [Remainder] string name = null) + public async Task MagicTheGathering([Remainder] string name = null) { - var channel = (ITextChannel)Context.Channel; var arg = name; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); return; } @@ -263,30 +237,28 @@ namespace NadekoBot.Modules.Searches .AddField(efb => efb.WithName("Types").WithValue(types).WithIsInline(true)); //.AddField(efb => efb.WithName("Store Url").WithValue(await NadekoBot.Google.ShortenUrl(items[0]["store_url"].ToString())).WithIsInline(true)); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } catch { - await channel.SendErrorAsync($"Error could not find the card '{arg}'.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Error could not find the card '{arg}'.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Hearthstone(IUserMessage umsg, [Remainder] string name = null) + public async Task Hearthstone([Remainder] string name = null) { - var channel = (ITextChannel)Context.Channel; var arg = name; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a card name to search for.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } @@ -301,7 +273,7 @@ namespace NadekoBot.Modules.Searches try { var items = JArray.Parse(response).Shuffle().ToList(); - var images = new List(); + var images = new List(); if (items == null) throw new KeyNotFoundException("Cannot find a card by that name"); foreach (var item in items.Where(item => item.HasValues && item["img"] != null).Take(4)) @@ -311,7 +283,7 @@ namespace NadekoBot.Modules.Searches var imgStream = new MemoryStream(); await sr.CopyToAsync(imgStream); imgStream.Position = 0; - images.Add(new Image(imgStream)); + images.Add(new ImageSharp.Image(imgStream)); } } string msg = null; @@ -322,32 +294,29 @@ namespace NadekoBot.Modules.Searches var ms = new MemoryStream(); images.AsEnumerable().Merge().SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, arg + ".png", msg).ConfigureAwait(false); + await Context.Channel.SendFileAsync(ms, arg + ".png", msg).ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($"Error occured.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Error occured.").ConfigureAwait(false); _log.Error(ex); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Yodify(IUserMessage umsg, [Remainder] string query = null) + public async Task Yodify([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter a sentence.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a sentence.").ConfigureAwait(false); return; } await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -364,31 +333,30 @@ namespace NadekoBot.Modules.Searches .WithAuthor(au => au.WithName("Yoda").WithIconUrl("http://www.yodaspeak.co.uk/yoda-small1.gif")) .WithDescription(res) .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } catch { - await channel.SendErrorAsync("Failed to yodify your sentence.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed to yodify your sentence.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task UrbanDict(IUserMessage umsg, [Remainder] string query = null) + public async Task UrbanDict([Remainder] string query = null) { var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); return; } await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -408,30 +376,27 @@ namespace NadekoBot.Modules.Searches .WithUrl(link) .WithAuthor(eab => eab.WithIconUrl("http://i.imgur.com/nwERwQE.jpg").WithName(word)) .WithDescription(def); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } catch { - await channel.SendErrorAsync("Failed finding a definition for that term.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed finding a definition for that term.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Hashtag(IUserMessage umsg, [Remainder] string query = null) + public async Task Hashtag([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a search term.").ConfigureAwait(false); return; } if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { - await channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); return; } @@ -451,7 +416,7 @@ namespace NadekoBot.Modules.Searches var hashtag = item["hashtag"].ToString(); var link = item["uri"].ToString(); var desc = item["text"].ToString(); - await channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .WithAuthor(eab => eab.WithUrl(link) .WithIconUrl("http://res.cloudinary.com/urbandictionary/image/upload/a_exif,c_fit,h_200,w_200/v1394975045/b8oszuu3tbq7ebyo7vo1.jpg") .WithName(query)) @@ -459,15 +424,13 @@ namespace NadekoBot.Modules.Searches } catch { - await channel.SendErrorAsync("Failed finding a definition for that tag.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Failed finding a definition for that tag.").ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Catfact() { - var channel = (ITextChannel)Context.Channel; using (var http = new HttpClient()) { var response = await http.GetStringAsync("http://catfacts-api.appspot.com/api/facts").ConfigureAwait(false); @@ -475,53 +438,42 @@ namespace NadekoBot.Modules.Searches return; var fact = JObject.Parse(response)["facts"][0].ToString(); - await channel.SendConfirmAsync("๐Ÿˆfact", fact).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("๐Ÿˆfact", fact).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Revav(IUserMessage umsg, [Remainder] IUser usr = null) + public async Task Revav([Remainder] IUser usr = null) { - var channel = (ITextChannel)Context.Channel; - if (usr == null) usr = Context.User; - await channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={usr.AvatarUrl}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Revimg(IUserMessage umsg, [Remainder] string imageLink = null) + public async Task Revimg([Remainder] string imageLink = null) { - var channel = (ITextChannel)Context.Channel; imageLink = imageLink?.Trim() ?? ""; if (string.IsNullOrWhiteSpace(imageLink)) return; - await channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"https://images.google.com/searchbyimage?image_url={imageLink}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Safebooru(IUserMessage umsg, [Remainder] string tag = null) + public async Task Safebooru([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var link = await GetSafebooruImageLink(tag).ConfigureAwait(false); if (link == null) - await channel.SendErrorAsync("No results."); + await Context.Channel.SendErrorAsync("No results."); else - await channel.SendMessageAsync(link).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(link).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Wiki(IUserMessage umsg, [Remainder] string query = null) + public async Task Wiki([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - query = query?.Trim(); if (string.IsNullOrWhiteSpace(query)) return; @@ -530,22 +482,19 @@ namespace NadekoBot.Modules.Searches var result = await http.GetStringAsync("https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info&redirects=1&formatversion=2&inprop=url&titles=" + Uri.EscapeDataString(query)); var data = JsonConvert.DeserializeObject(result); if (data.Query.Pages[0].Missing) - await channel.SendErrorAsync("That page could not be found."); + await Context.Channel.SendErrorAsync("That page could not be found."); else - await channel.SendMessageAsync(data.Query.Pages[0].FullUrl); + await Context.Channel.SendMessageAsync(data.Query.Pages[0].FullUrl); } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Color(IUserMessage umsg, [Remainder] string color = null) + public async Task Color([Remainder] string color = null) { - var channel = (ITextChannel)Context.Channel; - color = color?.Trim().Replace("#", ""); if (string.IsNullOrWhiteSpace((string)color)) return; - var img = new Image(50, 50); + var img = new ImageSharp.Image(50, 50); var red = Convert.ToInt32(color.Substring(0, 2), 16); var green = Convert.ToInt32(color.Substring(2, 2), 16); @@ -553,18 +502,15 @@ namespace NadekoBot.Modules.Searches img.BackgroundColor(new ImageSharp.Color(color)); - await channel.SendFileAsync(img.ToStream(), $"{color}.png"); + await Context.Channel.SendFileAsync(img.ToStream(), $"{color}.png"); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Videocall(IUserMessage umsg, [Remainder] string arg = null) + public async Task Videocall([Remainder] string arg = null) { - var channel = (ITextChannel)Context.Channel; - try { - var allUsrs = umsg.MentionedUsers.Append(Context.User); + var allUsrs = Context.Message.MentionedUsers.Append(Context.User); var allUsrsArray = allUsrs.ToArray(); var str = allUsrsArray.Aggregate("http://appear.in/", (current, usr) => current + Uri.EscapeUriString(usr.Username[0].ToString())); str += new NadekoRandom().Next(); @@ -580,18 +526,15 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Avatar(IUserMessage umsg, [Remainder] string mention = null) + public async Task Avatar([Remainder] string mention = null) { - var channel = (ITextChannel)Context.Channel; - - var usr = umsg.MentionedUsers().FirstOrDefault(); + var usr = Context.Message.MentionedUsers().FirstOrDefault(); if (usr == null) { - await channel.SendErrorAsync("Invalid user specified.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Invalid user specified.").ConfigureAwait(false); return; } - await channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl(usr.AvatarUrl).ConfigureAwait(false)).ConfigureAwait(false); + await Context.Channel.SendMessageAsync(await NadekoBot.Google.ShortenUrl(usr.AvatarUrl).ConfigureAwait(false)).ConfigureAwait(false); } public static async Task GetSafebooruImageLink(string tag) @@ -611,13 +554,11 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Wikia(IUserMessage umsg, string target, [Remainder] string query = null) + public async Task Wikia(string target, [Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; if (string.IsNullOrWhiteSpace(target) || string.IsNullOrWhiteSpace(query)) { - await channel.SendErrorAsync("Please enter a target wikia, followed by search query.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter a target wikia, followed by search query.").ConfigureAwait(false); return; } await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -632,24 +573,22 @@ namespace NadekoBot.Modules.Searches var response = $@"`Title:` {found["title"].ToString()} `Quality:` {found["quality"]} `URL:` {await NadekoBot.Google.ShortenUrl(found["url"].ToString()).ConfigureAwait(false)}"; - await channel.SendMessageAsync(response); + await Context.Channel.SendMessageAsync(response); } catch { - await channel.SendErrorAsync($"Failed finding `{query}`.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Failed finding `{query}`.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task MCPing(IUserMessage umsg, [Remainder] string query = null) + public async Task MCPing([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("๐Ÿ’ข Please enter a `ip:port`.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐Ÿ’ข Please enter a `ip:port`.").ConfigureAwait(false); return; } await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -669,24 +608,22 @@ namespace NadekoBot.Modules.Searches sb.AppendLine($"`Description:` {items["description"].ToString()}"); sb.AppendLine($"`Online Players:` {items["players"]["online"].ToString()}/{items["players"]["max"].ToString()}"); sb.Append($"`Latency:` {ping}"); - await channel.SendMessageAsync(sb.ToString()); + await Context.Channel.SendMessageAsync(sb.ToString()); } catch { - await channel.SendErrorAsync($"Failed finding `{arg}`.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Failed finding `{arg}`.").ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task MCQ(IUserMessage umsg, [Remainder] string query = null) + public async Task MCQ([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; var arg = query; if (string.IsNullOrWhiteSpace(arg)) { - await channel.SendErrorAsync("Please enter `ip:port`.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Please enter `ip:port`.").ConfigureAwait(false); return; } await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); @@ -709,16 +646,16 @@ namespace NadekoBot.Modules.Searches sb.AppendLine($"`Online Players:` {items["Players"]} / {items["MaxPlayers"]}"); sb.AppendLine($"`Plugins:` {items["Plugins"]}"); sb.Append($"`Version:` {items["Version"]}"); - await channel.SendMessageAsync(sb.ToString()); + await Context.Channel.SendMessageAsync(sb.ToString()); } catch { - await channel.SendErrorAsync($"Failed finding server `{arg}`.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"Failed finding server `{arg}`.").ConfigureAwait(false); } } } - public static async Task ValidateQuery(ITextChannel ch, string query) + public static async Task ValidateQuery(IMessageChannel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) return true; await ch.SendErrorAsync("Please specify search parameters.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs index 0f90db17..d8d40ade 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs @@ -1,13 +1,10 @@ -๏ปฟusing Discord; -using Discord.Commands; +๏ปฟusing Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Text; using System.Threading.Tasks; namespace NadekoBot.Modules.Utility diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 9c01b77c..3574dc05 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -4,7 +4,6 @@ using NadekoBot.Attributes; using NadekoBot.Extensions; using System; using System.Linq; -using System.Net.Http; using System.Text; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index 2f0300a4..ef6a92b2 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord; using Discord.Commands; -using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index 4238bcad..518b7c5a 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -12,7 +12,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; -using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index f91d8a02..f66d584c 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -4,17 +4,11 @@ using NadekoBot.Attributes; using System; using System.Linq; using System.Threading.Tasks; -using NadekoBot.Services; using System.Text; using NadekoBot.Extensions; using System.Text.RegularExpressions; using System.Reflection; -using Discord.WebSocket; using NadekoBot.Services.Impl; -using Discord.API; -using Embed = Discord.API.Embed; -using EmbedAuthor = Discord.API.EmbedAuthor; -using EmbedField = Discord.API.EmbedField; namespace NadekoBot.Modules.Utility { diff --git a/src/NadekoBot/Services/Database/Models/PokeType.cs b/src/NadekoBot/Services/Database/Models/PokeType.cs index 402ffd28..d4956c96 100644 --- a/src/NadekoBot/Services/Database/Models/PokeType.cs +++ b/src/NadekoBot/Services/Database/Models/PokeType.cs @@ -1,11 +1,4 @@ -๏ปฟusing Discord; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace NadekoBot.Services.Database.Models +๏ปฟnamespace NadekoBot.Services.Database.Models { public class UserPokeTypes : DbEntity { diff --git a/src/NadekoBot/Services/Database/Repositories/IPokeGameRepository.cs b/src/NadekoBot/Services/Database/Repositories/IPokeGameRepository.cs index ca698422..af9b003b 100644 --- a/src/NadekoBot/Services/Database/Repositories/IPokeGameRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/IPokeGameRepository.cs @@ -1,5 +1,4 @@ ๏ปฟusing NadekoBot.Services.Database.Models; -using System.Collections.Generic; namespace NadekoBot.Services.Database.Repositories { diff --git a/src/NadekoBot/Services/Database/Repositories/Impl/PokeGameRepository.cs b/src/NadekoBot/Services/Database/Repositories/Impl/PokeGameRepository.cs index f23f17ca..06662b06 100644 --- a/src/NadekoBot/Services/Database/Repositories/Impl/PokeGameRepository.cs +++ b/src/NadekoBot/Services/Database/Repositories/Impl/PokeGameRepository.cs @@ -1,7 +1,4 @@ ๏ปฟusing NadekoBot.Services.Database.Models; -using System; -using System.Collections.Generic; -using System.Linq; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 95c04854..618d8116 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -1,5 +1,4 @@ ๏ปฟusing Discord; -using Discord.WebSocket; using NadekoBot.Extensions; using System; using System.Collections.Generic; diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index 747ba4fa..8bb79fd6 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -66,7 +66,7 @@ namespace NadekoBot public ISelfUser[] GetAllCurrentUsers() => Clients.Select(c => c.CurrentUser).ToArray(); - public IReadOnlyCollection GetGuilds() => + public IReadOnlyCollection GetGuilds() => Clients.SelectMany(c => c.Guilds).ToList(); public IGuild GetGuild(ulong id) => diff --git a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs index 6128f6ff..389a2c8e 100644 --- a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs +++ b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs @@ -1,7 +1,6 @@ ๏ปฟusing Discord.Commands; using System.Linq; using System.Threading.Tasks; -using Discord; namespace NadekoBot.TypeReaders { diff --git a/src/NadekoBot/TypeReaders/GuildTypeReader.cs b/src/NadekoBot/TypeReaders/GuildTypeReader.cs index 37576b95..821a7327 100644 --- a/src/NadekoBot/TypeReaders/GuildTypeReader.cs +++ b/src/NadekoBot/TypeReaders/GuildTypeReader.cs @@ -1,7 +1,6 @@ ๏ปฟusing Discord.Commands; using System.Linq; using System.Threading.Tasks; -using Discord; namespace NadekoBot.TypeReaders { diff --git a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs index fbc36ac8..1cfd4204 100644 --- a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs @@ -1,7 +1,6 @@ ๏ปฟusing Discord.Commands; using System.Linq; using System.Threading.Tasks; -using Discord; namespace NadekoBot.TypeReaders { diff --git a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs index 76071620..fa44d17d 100644 --- a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs +++ b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs @@ -1,6 +1,5 @@ ๏ปฟusing Discord.Commands; using System.Threading.Tasks; -using Discord; using NadekoBot.Modules.Permissions; namespace NadekoBot.TypeReaders diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index ae947ee5..c47b2c51 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -1,6 +1,4 @@ ๏ปฟusing Discord; -using Discord.API; -using Discord.WebSocket; using ImageSharp; using Newtonsoft.Json; using System; @@ -10,7 +8,6 @@ using System.IO; using System.Linq; using System.Net.Http; using System.Security.Cryptography; -using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index 90ff822c..c12a7bf9 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -21,7 +21,7 @@ "CoreCLR-NCalc": "2.1.2", "Google.Apis.Urlshortener.v1": "1.19.0.138", "Google.Apis.YouTube.v3": "1.19.0.655", - "ImageSharp": "1.0.0-alpha-000079", + "ImageSharp": "1.0.0-alpha-*", "Microsoft.EntityFrameworkCore": "1.1.0", "Microsoft.EntityFrameworkCore.Design": "1.1.0", "Microsoft.EntityFrameworkCore.Sqlite": "1.1.0", @@ -38,7 +38,9 @@ "Newtonsoft.Json": "9.0.2-beta1", "NLog": "5.0.0-beta03", "System.Diagnostics.Contracts": "4.3.0", - "System.Xml.XPath": "4.3.0" + "System.Xml.XPath": "4.3.0", + "Discord.Net.Commands": "1.0.0-beta2-*", + "Discord.Net.WebSocket": "1.0.0-beta2-*" }, "tools": { "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final", From 091ea0fd32b7ed3a38c1abf4568d3c9120977e9a Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 17 Dec 2016 01:21:05 +0100 Subject: [PATCH 10/30] utility done --- .../Modules/Utility/Commands/CalcCommand.cs | 95 ++++---- .../Modules/Utility/Commands/InfoCommands.cs | 161 ++++++------- .../Modules/Utility/Commands/QuoteCommands.cs | 214 +++++++++--------- .../Utility/Commands/UnitConversion.cs | 13 +- src/NadekoBot/Modules/Utility/Utility.cs | 2 +- 5 files changed, 250 insertions(+), 235 deletions(-) diff --git a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs index d8d40ade..b0135fd0 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs @@ -11,55 +11,60 @@ namespace NadekoBot.Modules.Utility { public partial class Utility { - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Calculate([Remainder] string expression) + [Group] + public class CalcCommands : ModuleBase { - var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); - expr.EvaluateParameter += Expr_EvaluateParameter; - var result = expr.Evaluate(); - if (expr.Error == null) - await Context.Channel.SendConfirmAsync("Result", $"{result}"); - else - await Context.Channel.SendErrorAsync($"โš™ Error", expr.Error); - } - - private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args) - { - switch (name.ToLowerInvariant()) { - case "pi": args.Result= Math.PI; - break; - case "e": args.Result = Math.E; - break; - } - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task CalcOps() - { - var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x => + [NadekoCommand, Usage, Description, Aliases] + public async Task Calculate([Remainder] string expression) { - return x.Name; - }) - .Except(new[] { "ToString", + var expr = new NCalc.Expression(expression, NCalc.EvaluateOptions.IgnoreCase); + expr.EvaluateParameter += Expr_EvaluateParameter; + var result = expr.Evaluate(); + if (expr.Error == null) + await Context.Channel.SendConfirmAsync("Result", $"{result}"); + else + await Context.Channel.SendErrorAsync($"โš™ Error", expr.Error); + } + + private static void Expr_EvaluateParameter(string name, NCalc.ParameterArgs args) + { + switch (name.ToLowerInvariant()) + { + case "pi": + args.Result = Math.PI; + break; + case "e": + args.Result = Math.E; + break; + } + } + + [NadekoCommand, Usage, Description, Aliases] + public async Task CalcOps() + { + var selection = typeof(Math).GetTypeInfo().GetMethods().Except(typeof(object).GetTypeInfo().GetMethods()).Distinct(new MethodInfoEqualityComparer()).Select(x => + { + return x.Name; + }) + .Except(new[] { "ToString", "Equals", "GetHashCode", "GetType"}); - await Context.Channel.SendConfirmAsync(string.Join(", ",selection)); + await Context.Channel.SendConfirmAsync(string.Join(", ", selection)); + } } + + class MethodInfoEqualityComparer : IEqualityComparer + { + public bool Equals(MethodInfo x, MethodInfo y) => x.Name == y.Name; + + public int GetHashCode(MethodInfo obj) => obj.Name.GetHashCode(); + } + + class ExpressionContext + { + public double Pi { get; set; } = Math.PI; + } + } - - class MethodInfoEqualityComparer : IEqualityComparer - { - public bool Equals(MethodInfo x, MethodInfo y) => x.Name == y.Name; - - public int GetHashCode(MethodInfo obj) => obj.Name.GetHashCode(); - } - - class ExpressionContext - { - public double Pi { get; set; } = Math.PI; - } - -} +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 3574dc05..895395d0 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -11,88 +11,93 @@ namespace NadekoBot.Modules.Utility { public partial class Utility { - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task ServerInfo(string guildName = null) + [Group] + public class InfoCommands : ModuleBase { - var channel = (ITextChannel)Context.Channel; - guildName = guildName?.ToUpperInvariant(); - IGuild guild; - if (string.IsNullOrWhiteSpace(guildName)) - guild = channel.Guild; - else - guild = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guildName.ToUpperInvariant()).FirstOrDefault(); - if (guild == null) - return; - var ownername = await guild.GetUserAsync(guild.OwnerId); - var textchn = (await guild.GetTextChannelsAsync()).Count(); - var voicechn = (await guild.GetVoiceChannelsAsync()).Count(); - - var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22); - var sb = new StringBuilder(); - var users = await guild.GetUsersAsync().ConfigureAwait(false); - var embed = new EmbedBuilder() - .WithAuthor(eab => eab.WithName("Server Info")) - .WithTitle(guild.Name) - .AddField(fb => fb.WithName("**ID**").WithValue(guild.Id.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Owner**").WithValue(ownername.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Roles**").WithValue(guild.Roles.Count().ToString()).WithIsInline(true)) - .WithImageUrl(guild.IconUrl) - .WithColor(NadekoBot.OkColor); - if (guild.Emojis.Count() > 0) + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task ServerInfo(string guildName = null) { - embed.AddField(fb => fb.WithName("**Custom Emojis**").WithValue(Format.Italics(string.Join(", ", guild.Emojis))).WithIsInline(true)); + var channel = (ITextChannel)Context.Channel; + guildName = guildName?.ToUpperInvariant(); + IGuild guild; + if (string.IsNullOrWhiteSpace(guildName)) + guild = channel.Guild; + else + guild = NadekoBot.Client.GetGuilds().Where(g => g.Name.ToUpperInvariant() == guildName.ToUpperInvariant()).FirstOrDefault(); + if (guild == null) + return; + var ownername = await guild.GetUserAsync(guild.OwnerId); + var textchn = (await guild.GetTextChannelsAsync()).Count(); + var voicechn = (await guild.GetVoiceChannelsAsync()).Count(); + + var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(guild.Id >> 22); + var sb = new StringBuilder(); + var users = await guild.GetUsersAsync().ConfigureAwait(false); + var embed = new EmbedBuilder() + .WithAuthor(eab => eab.WithName("Server Info")) + .WithTitle(guild.Name) + .AddField(fb => fb.WithName("**ID**").WithValue(guild.Id.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Owner**").WithValue(ownername.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Members**").WithValue(users.Count.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Text Channels**").WithValue(textchn.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Voice Channels**").WithValue(voicechn.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Region**").WithValue(guild.VoiceRegionId.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Roles**").WithValue(guild.Roles.Count().ToString()).WithIsInline(true)) + .WithImageUrl(guild.IconUrl) + .WithColor(NadekoBot.OkColor); + if (guild.Emojis.Count() > 0) + { + embed.AddField(fb => fb.WithName("**Custom Emojis**").WithValue(Format.Italics(string.Join(", ", guild.Emojis))).WithIsInline(true)); + } + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } - await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); - } - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task ChannelInfo(ITextChannel channel = null) - { - var ch = channel ?? (ITextChannel)Context.Channel; - if (ch == null) - return; - var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); - var usercount = (await ch.GetUsersAsync().Flatten()).Count(); - var embed = new EmbedBuilder() - .WithTitle(ch.Name) - .WithDescription(ch.Topic?.SanitizeMentions()) - .AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true)) - .WithColor(NadekoBot.OkColor); - await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task UserInfo(IGuildUser usr = null) - { - var channel = (ITextChannel)Context.Channel; - var user = usr ?? Context.User as IGuildUser; - - if (user == null) - return; - - var embed = new EmbedBuilder() - .AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true)); - if (!string.IsNullOrWhiteSpace(user.Nickname)) { - embed.AddField(fb => fb.WithName("**Nickname**").WithValue(user.Nickname).WithIsInline(true)); + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task ChannelInfo(ITextChannel channel = null) + { + var ch = channel ?? (ITextChannel)Context.Channel; + if (ch == null) + return; + var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22); + var usercount = (await ch.GetUsersAsync().Flatten()).Count(); + var embed = new EmbedBuilder() + .WithTitle(ch.Name) + .WithDescription(ch.Topic?.SanitizeMentions()) + .AddField(fb => fb.WithName("**ID**").WithValue(ch.Id.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Created At**").WithValue($"{createdAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Users**").WithValue(usercount.ToString()).WithIsInline(true)) + .WithColor(NadekoBot.OkColor); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task UserInfo(IGuildUser usr = null) + { + var channel = (ITextChannel)Context.Channel; + var user = usr ?? Context.User as IGuildUser; + + if (user == null) + return; + + var embed = new EmbedBuilder() + .AddField(fb => fb.WithName("**Name**").WithValue($"**{user.Username}**#{user.Discriminator}").WithIsInline(true)); + if (!string.IsNullOrWhiteSpace(user.Nickname)) + { + embed.AddField(fb => fb.WithName("**Nickname**").WithValue(user.Nickname).WithIsInline(true)); + } + embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true)) + .AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true)) + .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) + .WithThumbnail(tn => tn.WithUrl(user.AvatarUrl)) + .WithColor(NadekoBot.OkColor); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } - embed.AddField(fb => fb.WithName("**ID**").WithValue(user.Id.ToString()).WithIsInline(true)) - .AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) - .WithThumbnail(tn => tn.WithUrl(user.AvatarUrl)) - .WithColor(NadekoBot.OkColor); - await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } } -} +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs index 1162f3d7..7796571d 100644 --- a/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/QuoteCommands.cs @@ -13,123 +13,127 @@ namespace NadekoBot.Modules.Utility { public partial class Utility { - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task ListQuotes(int page = 1) + [Group] + public class QuoteCommands : ModuleBase { - page -= 1; - - if (page < 0) - return; - - IEnumerable quotes; - using (var uow = DbHandler.UnitOfWork()) + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task ListQuotes(int page = 1) { - quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16); - } + page -= 1; - if (quotes.Any()) - await Context.Channel.SendConfirmAsync($"๐Ÿ’ฌ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") - .ConfigureAwait(false); - else - await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task ShowQuote([Remainder] string keyword) - { - if (string.IsNullOrWhiteSpace(keyword)) - return; - - keyword = keyword.ToUpperInvariant(); - - Quote quote; - using (var uow = DbHandler.Instance.GetUnitOfWork()) - { - quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false); - } - - if (quote == null) - return; - - await Context.Channel.SendMessageAsync("๐Ÿ“ฃ " + quote.Text.SanitizeMentions()); - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task AddQuote(string keyword, [Remainder] string text) - { - if (string.IsNullOrWhiteSpace(keyword) || string.IsNullOrWhiteSpace(text)) - return; - - keyword = keyword.ToUpperInvariant(); - - using (var uow = DbHandler.UnitOfWork()) - { - uow.Quotes.Add(new Quote - { - AuthorId = Context.Message.Author.Id, - AuthorName = Context.Message.Author.Username, - GuildId = Context.Guild.Id, - Keyword = keyword, - Text = text, - }); - await uow.CompleteAsync().ConfigureAwait(false); - } - await Context.Channel.SendConfirmAsync("โœ… Quote added.").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task DeleteQuote([Remainder] string keyword) - { - if (string.IsNullOrWhiteSpace(keyword)) - return; - - var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator; - - keyword = keyword.ToUpperInvariant(); - string response; - using (var uow = DbHandler.UnitOfWork()) - { - var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); - - if (qs==null || !qs.Any()) - { - await Context.Channel.SendErrorAsync("No quotes found.").ConfigureAwait(false); + if (page < 0) return; + + IEnumerable quotes; + using (var uow = DbHandler.UnitOfWork()) + { + quotes = uow.Quotes.GetGroup(Context.Guild.Id, page * 16, 16); } - var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id); - - uow.Quotes.Remove(q); - await uow.CompleteAsync().ConfigureAwait(false); - response = "๐Ÿ—‘ **Deleted a random quote.**"; + if (quotes.Any()) + await Context.Channel.SendConfirmAsync($"๐Ÿ’ฌ **Page {page + 1} of quotes:**\n```xl\n" + String.Join("\n", quotes.Select((q) => $"{q.Keyword,-20} by {q.AuthorName}")) + "\n```") + .ConfigureAwait(false); + else + await Context.Channel.SendErrorAsync("No quotes on this page.").ConfigureAwait(false); } - await Context.Channel.SendConfirmAsync(response); - } - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - [RequireUserPermission(GuildPermission.Administrator)] - public async Task DelAllQuotes([Remainder] string keyword) - { - if (string.IsNullOrWhiteSpace(keyword)) - return; - - keyword = keyword.ToUpperInvariant(); - - using (var uow = DbHandler.UnitOfWork()) + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task ShowQuote([Remainder] string keyword) { - var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); + if (string.IsNullOrWhiteSpace(keyword)) + return; - uow.Quotes.RemoveRange(quotes.ToArray());//wtf?! + keyword = keyword.ToUpperInvariant(); - await uow.CompleteAsync(); + Quote quote; + using (var uow = DbHandler.Instance.GetUnitOfWork()) + { + quote = await uow.Quotes.GetRandomQuoteByKeywordAsync(Context.Guild.Id, keyword).ConfigureAwait(false); + } + + if (quote == null) + return; + + await Context.Channel.SendMessageAsync("๐Ÿ“ฃ " + quote.Text.SanitizeMentions()); } - await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ **Deleted all quotes** with **{keyword}** keyword."); + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task AddQuote(string keyword, [Remainder] string text) + { + if (string.IsNullOrWhiteSpace(keyword) || string.IsNullOrWhiteSpace(text)) + return; + + keyword = keyword.ToUpperInvariant(); + + using (var uow = DbHandler.UnitOfWork()) + { + uow.Quotes.Add(new Quote + { + AuthorId = Context.Message.Author.Id, + AuthorName = Context.Message.Author.Username, + GuildId = Context.Guild.Id, + Keyword = keyword, + Text = text, + }); + await uow.CompleteAsync().ConfigureAwait(false); + } + await Context.Channel.SendConfirmAsync("โœ… Quote added.").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public async Task DeleteQuote([Remainder] string keyword) + { + if (string.IsNullOrWhiteSpace(keyword)) + return; + + var isAdmin = ((IGuildUser)Context.Message.Author).GuildPermissions.Administrator; + + keyword = keyword.ToUpperInvariant(); + string response; + using (var uow = DbHandler.UnitOfWork()) + { + var qs = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); + + if (qs == null || !qs.Any()) + { + await Context.Channel.SendErrorAsync("No quotes found.").ConfigureAwait(false); + return; + } + + var q = qs.Shuffle().FirstOrDefault(elem => isAdmin || elem.AuthorId == Context.Message.Author.Id); + + uow.Quotes.Remove(q); + await uow.CompleteAsync().ConfigureAwait(false); + response = "๐Ÿ—‘ **Deleted a random quote.**"; + } + await Context.Channel.SendConfirmAsync(response); + } + + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + [RequireUserPermission(GuildPermission.Administrator)] + public async Task DelAllQuotes([Remainder] string keyword) + { + if (string.IsNullOrWhiteSpace(keyword)) + return; + + keyword = keyword.ToUpperInvariant(); + + using (var uow = DbHandler.UnitOfWork()) + { + var quotes = uow.Quotes.GetAllQuotesByKeyword(Context.Guild.Id, keyword); + + uow.Quotes.RemoveRange(quotes.ToArray());//wtf?! + + await uow.CompleteAsync(); + } + + await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ **Deleted all quotes** with **{keyword}** keyword."); + } } } -} +} \ No newline at end of file diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index 518b7c5a..c0c1cc50 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -22,7 +22,6 @@ namespace NadekoBot.Modules.Utility [Group] public class UnitConverterCommands : ModuleBase { - public static List Units { get; set; } = new List(); private static Logger _log { get; } private static Timer _timer; @@ -42,7 +41,7 @@ namespace NadekoBot.Modules.Utility }).ToArray(); using (var uow = DbHandler.UnitOfWork()) - { + { if (uow.ConverterUnits.Empty()) { uow.ConverterUnits.AddRange(data); @@ -64,7 +63,8 @@ namespace NadekoBot.Modules.Utility } public async Task UpdateCurrency() - {try + { + try { var currencyRates = await UpdateCurrencyRates(); var unitTypeString = "currency"; @@ -95,18 +95,19 @@ namespace NadekoBot.Modules.Utility Units.AddRange(range); _log.Info("Updated Currency"); } - catch { + catch + { _log.Warn("Failed updating currency."); } } + [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task ConvertList() { var res = Units.GroupBy(x => x.UnitType) .Aggregate(new EmbedBuilder().WithTitle("__Units which can be used by the converter__") .WithColor(NadekoBot.OkColor), - (embed, g) => embed.AddField(efb => + (embed, g) => embed.AddField(efb => efb.WithName(g.Key.ToTitleCase()) .WithValue(String.Join(", ", g.Select(x => x.Triggers.FirstOrDefault()) .OrderBy(x => x))))); diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index f66d584c..b14406d8 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -211,7 +211,7 @@ namespace NadekoBot.Modules.Utility await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithColor(NadekoBot.OkColor), (embed, g) => embed.AddField(efb => efb.WithName(g.Name) - .WithValue($"```css\nID: {g.Id}\nMembers: {(g.GetUsersAsync().GetAwaiter().GetResult()).Count}\nOwnerID: {g.OwnerId} ```") + .WithValue($"```css\nID: {g.Id}\nMembers: {g.Users.Count}\nOwnerID: {g.OwnerId} ```") .WithIsInline(false)))) .ConfigureAwait(false); } From cf17d2a1ac19b6e3362b31ca731e641606ec5825 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 17 Dec 2016 05:09:04 +0100 Subject: [PATCH 11/30] almost done --- .gitmodules | 4 + Discord.Net | 1 + .../Modules/Administration/Administration.cs | 14 +- .../Commands/AntiRaidCommands.cs | 2 +- .../Administration/Commands/LogCommand.cs | 314 +++++++++--------- .../Commands/MessageRepeater.cs | 2 +- .../Administration/Commands/MuteCommands.cs | 2 +- .../Commands/SelfAssignedRolesCommand.cs | 6 +- .../Modules/ClashOfClans/ClashOfClans.cs | 8 +- .../Gambling/Commands/DiceRollCommand.cs | 40 +-- .../Modules/Gambling/Commands/DrawCommand.cs | 4 +- .../Gambling/Commands/FlipCoinCommand.cs | 3 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 6 +- .../Games/Commands/Hangman/HangmanGame.cs | 18 +- .../Games/Commands/Trivia/TriviaGame.cs | 10 +- src/NadekoBot/Modules/Help/Help.cs | 28 +- src/NadekoBot/Modules/Music/Music.cs | 8 +- .../Permissions/Commands/BlacklistCommands.cs | 28 +- .../Permissions/Commands/FilterCommands.cs | 2 +- .../Permissions/PermissionExtensions.cs | 3 +- .../Commands/StreamNotificationCommands.cs | 7 +- src/NadekoBot/Modules/Searches/Searches.cs | 7 +- .../Modules/Utility/Commands/InfoCommands.cs | 4 +- src/NadekoBot/Modules/Utility/Utility.cs | 4 +- src/NadekoBot/Services/CommandHandler.cs | 64 ++-- src/NadekoBot/Services/Impl/BotCredentials.cs | 2 +- src/NadekoBot/Services/Impl/StatsService.cs | 12 +- src/NadekoBot/ShardedDiscordClient.cs | 2 +- src/NadekoBot/_Extensions/Extensions.cs | 6 + 29 files changed, 287 insertions(+), 324 deletions(-) create mode 100644 .gitmodules create mode 160000 Discord.Net diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 00000000..08cf3841 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "Discord.Net"] + path = Discord.Net + url = https://github.com/Kwoth/Discord.Net + branch = rogue-dev diff --git a/Discord.Net b/Discord.Net new file mode 160000 index 00000000..c102f52b --- /dev/null +++ b/Discord.Net @@ -0,0 +1 @@ +Subproject commit c102f52bfa1a6fd6ffbbd7c7f65d07342e8b6851 diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 02bfb1dc..a79b6fc3 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -144,7 +144,7 @@ namespace NadekoBot.Modules.Administration { try { - if (roleToEdit.Position > (await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false)).Roles.Max(r => r.Position)) + if (roleToEdit.Position > (await Context.Guild.GetCurrentUserAsync().ConfigureAwait(false)).GetRoles().Max(r => r.Position)) { await Context.Channel.SendErrorAsync("๐Ÿšซ You can't edit roles higher than your highest role.").ConfigureAwait(false); return; @@ -165,7 +165,7 @@ namespace NadekoBot.Modules.Administration { try { - await user.RemoveRolesAsync(user.Roles).ConfigureAwait(false); + await user.RemoveRolesAsync(user.GetRoles()).ConfigureAwait(false); await Context.Channel.SendConfirmAsync($"๐Ÿ—‘ Successfully removed **all** roles from user **{user.Username}**").ConfigureAwait(false); } catch @@ -237,7 +237,7 @@ namespace NadekoBot.Modules.Administration { msg = "โ—๏ธNo reason provided."; } - if (Context.User.Id != user.Guild.OwnerId && Context.User.Roles.Select(r=>r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) + if (Context.User.Id != user.Guild.OwnerId && ((IGuildUser)Context.User).GetRoles().Select(r=>r.Position).Max() >= ((IGuildUser)Context.User).GetRoles().Select(r => r.Position).Max()) { await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy.").ConfigureAwait(false); return; @@ -271,7 +271,7 @@ namespace NadekoBot.Modules.Administration { msg = "โ—๏ธNo reason provided."; } - if (Context.User.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) + if (Context.User.Id != user.Guild.OwnerId && user.GetRoles().Select(r => r.Position).Max() >= ((IGuildUser)Context.User).GetRoles().Select(r => r.Position).Max()) { await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; @@ -308,7 +308,7 @@ namespace NadekoBot.Modules.Administration return; } - if (Context.Message.Author.Id != user.Guild.OwnerId && user.Roles.Select(r => r.Position).Max() >= ((IGuildUser)Context.User).Roles.Select(r => r.Position).Max()) + if (Context.Message.Author.Id != user.Guild.OwnerId && user.GetRoles().Select(r => r.Position).Max() >= ((IGuildUser)Context.User).GetRoles().Select(r => r.Position).Max()) { await Context.Channel.SendErrorAsync("โš ๏ธ You can't use this command on users with a role higher or equal to yours in the role hierarchy."); return; @@ -564,7 +564,7 @@ namespace NadekoBot.Modules.Administration else if (ids[1].ToUpperInvariant().StartsWith("U:")) { var uid = ulong.Parse(ids[1].Substring(2)); - var user = (await server.GetUsersAsync()).Where(u => u.Id == uid).FirstOrDefault(); + var user = server.Users.Where(u => u.Id == uid).FirstOrDefault(); if (user == null) { return; @@ -631,7 +631,7 @@ namespace NadekoBot.Modules.Administration foreach (var role in roles) { send += $"\n**{role.Name}**\n"; - send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Distinct().Select(u=>u.Mention)); + send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.GetRoles().Contains(role)).Distinct().Select(u=>u.Mention)); } while (send.Length > 2000) diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index 6126c994..a220076d 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -158,7 +158,7 @@ namespace NadekoBot.Modules.Administration case PunishmentAction.Mute: try { - await MuteCommands.Mute(gu).ConfigureAwait(false); + await MuteCommands.MuteUser(gu).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex, "I can't apply punishement"); } break; diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 9e63efda..ab358cb7 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; @@ -18,7 +19,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class LogCommands + public class LogCommands : ModuleBase { private static ShardedDiscordClient _client { get; } private static Logger _log { get; } @@ -29,7 +30,6 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary> UserPresenceUpdates { get; } = new ConcurrentDictionary>(); private static Timer timerReference { get; } - private IGoogleApiService _google { get; } static LogCommands() { @@ -60,10 +60,7 @@ namespace NadekoBot.Modules.Administration _log.Warn(ex); } }, null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10)); - } - public LogCommands() - { _client.MessageUpdated += _client_MessageUpdated; _client.MessageDeleted += _client_MessageDeleted; _client.UserBanned += _client_UserBanned; @@ -72,7 +69,7 @@ namespace NadekoBot.Modules.Administration _client.UserLeft += _client_UserLeft; _client.UserPresenceUpdated += _client_UserPresenceUpdated; _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated; - _client.UserUpdated += _client_UserUpdated; + //_client.UserUpdated += _client_UserUpdated; _client.ChannelCreated += _client_ChannelCreated; _client.ChannelDestroyed += _client_ChannelDestroyed; @@ -82,16 +79,16 @@ namespace NadekoBot.Modules.Administration MuteCommands.UserUnmuted += MuteCommands_UserUnmuted; } - private Task MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType) + private static async Task MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.IsLogging) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { @@ -111,19 +108,19 @@ namespace NadekoBot.Modules.Administration try { await logChannel.SendMessageAsync($"โ€ผ๏ธ๐Ÿ••`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__๐Ÿ”‡ **| User muted from the {mutes}. |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task MuteCommands_UserUnmuted(IGuildUser usr, MuteCommands.MuteType muteType) + private static async Task MuteCommands_UserUnmuted(IGuildUser usr, MuteCommands.MuteType muteType) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.IsLogging) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { @@ -143,7 +140,7 @@ namespace NadekoBot.Modules.Administration try { await logChannel.SendMessageAsync($"โ€ผ๏ธ๐Ÿ••`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__๐Ÿ”Š **| User unmuted from the {mutes}. |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } public static async Task TriggeredAntiProtection(IGuildUser[] users, PunishmentAction action, ProtectionType protection) @@ -156,7 +153,7 @@ namespace NadekoBot.Modules.Administration || !logSetting.IsLogging) return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(users.First().Guild, logSetting)) == null) + if ((logChannel = await TryGetLogChannel(users.First().Guild, logSetting)) == null) return; var punishment = ""; @@ -179,63 +176,63 @@ namespace NadekoBot.Modules.Administration //await logChannel.SendMessageAsync(String.Join("\n",users.Select(user=>$"{Format.Bold(user.ToString())} was **{punishment}** due to `{protection}` protection on **{user.Guild.Name}** server."))) .ConfigureAwait(false); } + //todo + //private static async Task _client_UserUpdated(SocketUser before, SocketUser after) + //{ + // LogSetting logSetting; + // if (!GuildLogSettings.TryGetValue(before.Guild.Id, out logSetting) + // || !logSetting.IsLogging + // || !logSetting.UserUpdated) + // return; - private Task _client_UserUpdated(IGuildUser before, IGuildUser after) - { - LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(before.Guild.Id, out logSetting) - || !logSetting.IsLogging - || !logSetting.UserUpdated) - return Task.CompletedTask; + // ITextChannel logChannel; + // if ((logChannel = await TryGetLogChannel(before.Guild, logSetting)) == null) + // return; - ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(before.Guild, logSetting)) == null) - return Task.CompletedTask; + // var task = Task.Run(async () => + // { + // try + // { + // string str = $"๐Ÿ•”`{prettyCurrentTime}`"; + // if (before.Username != after.Username) + // //str += $"**Name Changed**`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; + // str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Name Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`New:` **{after.ToString()}**"; + // else if (before.Nickname != after.Nickname) + // str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Nickname Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`Old:` **{before.Nickname}#{before.Discriminator}**\n\t\t`New:` **{after.Nickname}#{after.Discriminator}**"; + // //str += $"**Nickname Changed**`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; + // else if (before.AvatarUrl != after.AvatarUrl) + // //str += $"**Avatar Changed**๐Ÿ‘ค`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; + // str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿ–ผ {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; + // else if (!before.GetRoles().SequenceEqual(after.GetRoles())) + // { + // if (before.GetRoles().Count() < after.GetRoles().Count()) + // { + // var diffRoles = after.GetRoles().Where(r => !before.GetRoles().Contains(r)).Select(r => "**" + r.Name + "**"); + // //str += $"**User's Roles changed โš”โž•**๐Ÿ‘ค`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; + // str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Added |** ๐Ÿ†” `{before.Id}`\n\tโœ… {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; + // } + // else if (before.GetRoles().Count() > after.GetRoles().Count()) + // { + // var diffRoles = before.GetRoles().Where(r => !after.GetRoles().Contains(r)).Select(r => "**" + r.Name + "**"); + // //str += $"**User's Roles changed **`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; + // str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Removed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿšฎ {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; + // } + // } + // else + // return; + // try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + // } + // catch { } + // }); - var task = Task.Run(async () => - { - try - { - string str = $"๐Ÿ•”`{prettyCurrentTime}`"; - if (before.Username != after.Username) - //str += $"**Name Changed**`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; - str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Name Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`New:` **{after.ToString()}**"; - else if (before.Nickname != after.Nickname) - str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Nickname Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`Old:` **{before.Nickname}#{before.Discriminator}**\n\t\t`New:` **{after.Nickname}#{after.Discriminator}**"; - //str += $"**Nickname Changed**`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; - else if (before.AvatarUrl != after.AvatarUrl) - //str += $"**Avatar Changed**๐Ÿ‘ค`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; - str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿ–ผ {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; - else if (!before.Roles.SequenceEqual(after.Roles)) - { - if (before.Roles.Count() < after.Roles.Count()) - { - var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); - //str += $"**User's Roles changed โš”โž•**๐Ÿ‘ค`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; - str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Added |** ๐Ÿ†” `{before.Id}`\n\tโœ… {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** โš”"; - } - else if (before.Roles.Count() > after.Roles.Count()) - { - var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); - //str += $"**User's Roles changed **`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; - str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Removed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿšฎ {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** โš”"; - } - } - else - return; - try { await logChannel.SendMessageAsync(str).ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } - } - catch { } - }); + // return; + //} - return Task.CompletedTask; - } - - private Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter) + private static async Task _client_ChannelUpdated(IChannel cbefore, IChannel cafter) { var before = cbefore as IGuildChannel; if (before == null) - return Task.CompletedTask; + return; var after = (IGuildChannel)cafter; LogSetting logSetting; @@ -243,11 +240,11 @@ namespace NadekoBot.Modules.Administration || !logSetting.IsLogging || !logSetting.ChannelUpdated || logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == after.Id)) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(before.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(before.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { @@ -267,78 +264,78 @@ namespace NadekoBot.Modules.Administration catch { } }); - return Task.CompletedTask; + return; } - private Task _client_ChannelDestroyed(IChannel ich) + private static async Task _client_ChannelDestroyed(IChannel ich) { var ch = ich as IGuildChannel; if (ch == null) - return Task.CompletedTask; + return; LogSetting logSetting; if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.ChannelDestroyed || logSetting.IgnoredChannels.Any(ilc=>ilc.ChannelId == ch.Id)) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(ch.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"๐Ÿ••`{prettyCurrentTime}`๐Ÿ—‘ **| {(ch is IVoiceChannel ? "Voice" : "Text")} Channel Deleted #โƒฃ {ch.Name}** `({ch.Id})`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_ChannelCreated(IChannel ich) + private static async Task _client_ChannelCreated(IChannel ich) { var ch = ich as IGuildChannel; if (ch == null) - return Task.CompletedTask; + return; LogSetting logSetting; if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.ChannelCreated) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(ch.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"๐Ÿ•“`{prettyCurrentTime}`๐Ÿ†• **| {(ch is IVoiceChannel ? "Voice" : "Text")} Channel Created: #โƒฃ {ch.Name}** `({ch.Id})`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_UserVoiceStateUpdated(IUser iusr, IVoiceState before, IVoiceState after) + private static async Task _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { - var usr = iusr as IGuildUser; + var usr = iusr as SocketGuildUser; if (usr == null) - return Task.CompletedTask; + return; var beforeVch = before.VoiceChannel; var afterVch = after.VoiceChannel; if (beforeVch == afterVch) - return Task.CompletedTask; + return; LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.LogVoicePresence) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogChannelType.Voice)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogChannelType.Voice)) == null) + return; string str = null; if (beforeVch?.Guild == afterVch?.Guild) @@ -356,20 +353,24 @@ namespace NadekoBot.Modules.Administration if(str != null) UserPresenceUpdates.AddOrUpdate(logChannel, new List() { str }, (id, list) => { list.Add(str); return list; }); - return Task.CompletedTask; + return; } - private Task _client_UserPresenceUpdated(IGuildUser usr, IPresence before, IPresence after) + private static async Task _client_UserPresenceUpdated(Optional oGuild, SocketUser usr, SocketPresence before, SocketPresence after) { + if (!oGuild.IsSpecified) + return; + + var guild = oGuild.Value; LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(guild.Id, out logSetting) || !logSetting.LogUserPresence || before.Status == after.Status) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogChannelType.UserPresence)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(guild, logSetting, LogChannelType.UserPresence)) == null) + return; string str; if (before.Status != after.Status) str = $"๐Ÿ”ต`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}**__ is now **{after.Status}**."; @@ -378,116 +379,116 @@ namespace NadekoBot.Modules.Administration UserPresenceUpdates.AddOrUpdate(logChannel, new List() { str }, (id, list) => { list.Add(str); return list; }); - return Task.CompletedTask; + return; } - private Task _client_UserLeft(IGuildUser usr) + private static async Task _client_UserLeft(IGuildUser usr) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserLeft) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"โ—๏ธ๐Ÿ•›`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โŒ **| USER LEFT |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_UserJoined(IGuildUser usr) + private static async Task _client_UserJoined(IGuildUser usr) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserJoined) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"โ•๐Ÿ•“`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โœ… **| USER JOINED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_UserUnbanned(IUser usr, IGuild guild) + private static async Task _client_UserUnbanned(IUser usr, IGuild guild) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserUnbanned) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"โ•๐Ÿ•˜`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โ™ป๏ธ **| USER UN-BANNED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_UserBanned(IUser usr, IGuild guild) + private static async Task _client_UserBanned(IUser usr, IGuild guild) { LogSetting logSetting; if (!GuildLogSettings.TryGetValue(guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.UserBanned) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(guild, logSetting)) == null) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(guild, logSetting)) == null) + return; var task = Task.Run(async () => { try { await logChannel.SendMessageAsync($"โ€ผ๏ธ๐Ÿ••`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__๐Ÿšซ **| USER BANNED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_MessageDeleted(ulong arg1, Optional imsg) + private static async Task _client_MessageDeleted(ulong arg1, Optional imsg) { - var msg = (imsg.IsSpecified ? imsg.Value : null) as IUserMessage; + var msg = (imsg.IsSpecified ? imsg.Value : null) as SocketUserMessage; if (msg == null || msg.IsAuthor()) - return Task.CompletedTask; + return; - //var channel = Context.Channel as ITextChannel; + var channel = msg.Channel as SocketTextChannel; if (channel == null) - return Task.CompletedTask; + return; LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(Context.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.MessageDeleted || logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == channel.Id)) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(Context.Guild, logSetting)) == null || logChannel.Id == msg.Id) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting)) == null || logChannel.Id == msg.Id) + return; var task = Task.Run(async () => { try { - var str = $@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{Context.User.Username}#{Context.User.Discriminator}**__ **| Deleted Message |** ๐Ÿ†” `{Context.User.Id}` #โƒฃ `{channel.Name}` -๐Ÿ—‘ {msg.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator)}"; + var str = $@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{msg.Author.Username}#{msg.Author.Discriminator}**__ **| Deleted Message |** ๐Ÿ†” `{msg.Author.Id}` #โƒฃ `{channel.Name}` +๐Ÿ—‘ {msg.Resolve(userHandling: TagHandling.FullName)}"; if (msg.Attachments.Any()) str += $"{Environment.NewLine}๐Ÿ“Ž {string.Join(", ", msg.Attachments.Select(a => a.ProxyUrl))}"; await logChannel.SendMessageAsync(str.SanitizeMentions()).ConfigureAwait(false); @@ -495,48 +496,48 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } - private Task _client_MessageUpdated(Optional optmsg, IMessage imsg2) + private static async Task _client_MessageUpdated(Optional optmsg, SocketMessage imsg2) { - var after = imsg2 as IUserMessage; + var after = imsg2 as SocketUserMessage; if (after == null || after.IsAuthor()) - return Task.CompletedTask; + return ; - var before = (optmsg.IsSpecified ? optmsg.Value : null) as IUserMessage; + var before = (optmsg.IsSpecified ? optmsg.Value : null) as SocketUserMessage; if (before == null) - return Task.CompletedTask; + return; - //var channel = after.Channel as ITextChannel; + var channel = after.Channel as SocketTextChannel; if (channel == null) - return Task.CompletedTask; + return ; LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(Context.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out logSetting) || !logSetting.IsLogging || !logSetting.MessageUpdated || logSetting.IgnoredChannels.Any(ilc => ilc.ChannelId == channel.Id)) - return Task.CompletedTask; + return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(Context.Guild, logSetting)) == null || logChannel.Id == after.Channel.Id) - return Task.CompletedTask; + if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting)) == null || logChannel.Id == after.Channel.Id) + return; var task = Task.Run(async () => { //try { await logChannel.SendMessageAsync($@"๐Ÿ•”`{prettyCurrentTime}` **Message** ๐Ÿ“ `#{channel.Name}` //๐Ÿ‘ค`{before.Author.Username}` try { await logChannel.SendMessageAsync($@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{before.Author.Username}#{before.Author.Discriminator}**__ **| ๐Ÿ“ Edited Message |** ๐Ÿ†” `{before.Author.Id}` #โƒฃ `{channel.Name}` - `Old:` {before.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator).SanitizeMentions()} - **`New:`** {after.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator).SanitizeMentions()}").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + `Old:` {before.Resolve(userHandling: TagHandling.FullName).SanitizeMentions()} + **`New:`** {after.Resolve(userHandling: TagHandling.FullName).SanitizeMentions()}").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } }); - return Task.CompletedTask; + return; } private enum LogChannelType { Text, Voice, UserPresence }; - private static ITextChannel TryGetLogChannel(IGuild guild, LogSetting logSetting, LogChannelType logChannelType = LogChannelType.Text) + private static async Task TryGetLogChannel(IGuild guild, LogSetting logSetting, LogChannelType logChannelType = LogChannelType.Text) { ulong id = 0; switch (logChannelType) @@ -551,7 +552,7 @@ namespace NadekoBot.Modules.Administration id = logSetting.UserPresenceChannelId; break; } - //var channel = guild.GetTextChannel(id); + var channel = await guild.GetTextChannelAsync(id); if (channel == null) using (var uow = DbHandler.UnitOfWork()) @@ -591,7 +592,7 @@ namespace NadekoBot.Modules.Administration GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); logSetting.IsLogging = !logSetting.IsLogging; if (logSetting.IsLogging) - logSetting.ChannelId = channel.Id; + logSetting.ChannelId = Context.Channel.Id; await uow.CompleteAsync(); } @@ -607,17 +608,16 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogIgnore() { - //var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.For(Context.Guild.Id); LogSetting logSetting = GuildLogSettings.GetOrAdd(Context.Guild.Id, (id) => config.LogSetting); - removed = logSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == channel.Id); - config.LogSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == channel.Id); + removed = logSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == Context.Channel.Id); + config.LogSetting.IgnoredChannels.RemoveWhere(ilc => ilc.ChannelId == Context.Channel.Id); if (removed == 0) { - var toAdd = new IgnoredLogChannel { ChannelId = channel.Id }; + var toAdd = new IgnoredLogChannel { ChannelId = Context.Channel.Id }; logSetting.IgnoredChannels.Add(toAdd); config.LogSetting.IgnoredChannels.Add(toAdd); } @@ -625,9 +625,9 @@ namespace NadekoBot.Modules.Administration } if (removed == 0) - await Context.Channel.SendMessageAsync($"๐Ÿ†— Logging will **now ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"๐Ÿ†— Logging will **now ignore** #โƒฃ `{Context.Channel.Name} ({Context.Channel.Id})`").ConfigureAwait(false); else - await Context.Channel.SendMessageAsync($"โ„น๏ธ Logging will **no longer ignore** #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โ„น๏ธ Logging will **no longer ignore** #โƒฃ `{Context.Channel.Name} ({Context.Channel.Id})`").ConfigureAwait(false); } //[LocalizedCommand, LocalizedRemarks, LocalizedSummary, LocalizedAlias] @@ -705,7 +705,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task UserPresence() { - //var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { @@ -713,12 +712,12 @@ namespace NadekoBot.Modules.Administration GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); enabled = logSetting.LogUserPresence = !logSetting.LogUserPresence; if(enabled) - logSetting.UserPresenceChannelId = channel.Id; + logSetting.UserPresenceChannelId = Context.Channel.Id; await uow.CompleteAsync().ConfigureAwait(false); } if (enabled) - await Context.Channel.SendMessageAsync($"โœ… Logging **user presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โœ… Logging **user presence** updates in #โƒฃ `{Context.Channel.Name} ({Context.Channel.Id})`").ConfigureAwait(false); else await Context.Channel.SendMessageAsync($"โ„น๏ธ Stopped logging **user presence** updates.").ConfigureAwait(false); } @@ -728,7 +727,6 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task VoicePresence() { - //var channel = (ITextChannel)Context.Channel; bool enabled; using (var uow = DbHandler.UnitOfWork()) { @@ -738,12 +736,12 @@ namespace NadekoBot.Modules.Administration GuildLogSettings.AddOrUpdate(Context.Guild.Id, (id) => logSetting, (id, old) => logSetting); enabled = logSetting.LogVoicePresence = !logSetting.LogVoicePresence; if (enabled) - logSetting.VoicePresenceChannelId = channel.Id; + logSetting.VoicePresenceChannelId = Context.Channel.Id; await uow.CompleteAsync().ConfigureAwait(false); } if (enabled) - await Context.Channel.SendMessageAsync($"โœ… Logging **voice presence** updates in #โƒฃ `{channel.Name} ({channel.Id})`").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"โœ… Logging **voice presence** updates in #โƒฃ `{Context.Channel.Name} ({Context.Channel.Id})`").ConfigureAwait(false); else await Context.Channel.SendMessageAsync($"โ„น๏ธ Stopped logging **voice presence** updates.").ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index 1984bdf6..e470d4d1 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Administration { _log = LogManager.GetCurrentClassLogger(); this.Repeater = repeater; - this.Channel = channel ?? NadekoBot.Client.GetGuild(repeater.GuildId)?.GetTextChannel(repeater.ChannelId); + this.Channel = channel ?? NadekoBot.Client.GetGuild(repeater.GuildId)?.GetTextChannelAsync(repeater.ChannelId).GetAwaiter().GetResult(); if (Channel == null) return; Task.Run(Run); diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index 6780c6b4..fbf443de 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -118,7 +118,7 @@ namespace NadekoBot.Modules.Administration await guild.CreateRoleAsync(defaultMuteRoleName, GuildPermissions.None).ConfigureAwait(false); } - foreach (var toOverwrite in guild.GetTextChannels()) + foreach (var toOverwrite in (await guild.GetTextChannelsAsync())) { try { diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs index c78c88f7..3829f5c4 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfAssignedRolesCommand.cs @@ -170,9 +170,11 @@ namespace NadekoBot.Modules.Administration if (conf.ExclusiveSelfAssignedRoles) { - if (guildUser.RoleIds.Contains(role.Id)) + var sameRoleId = guildUser.RoleIds.Where(r => roles.Select(sar => sar.RoleId).Contains(r)).FirstOrDefault(); + var sameRole = Context.Guild.GetRole(sameRoleId); + if (sameRoleId != default(ulong)) { - await Context.Channel.SendErrorAsync($"You already have **{sameRoles.FirstOrDefault().Name}** `exclusive self-assigned` role.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"You already have **{sameRole?.Name}** `exclusive self-assigned` role.").ConfigureAwait(false); return; } } diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 40b9e999..d5831e81 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -28,7 +28,9 @@ namespace NadekoBot.Modules.ClashOfClans .Select(cw => { cw.Channel = NadekoBot.Client.GetGuild(cw.GuildId) - ?.GetTextChannel(cw.ChannelId); + ?.GetTextChannelAsync(cw.ChannelId) + .GetAwaiter() + .GetResult(); return cw; }) .Where(cw => cw?.Channel != null) @@ -294,6 +296,7 @@ namespace NadekoBot.Modules.ClashOfClans public static async Task CreateWar(string enemyClan, int size, ulong serverId, ulong channelId) { + var channel = await NadekoBot.Client.GetGuild(serverId)?.GetTextChannelAsync(channelId); using (var uow = DbHandler.UnitOfWork()) { var cw = new ClashWar @@ -303,8 +306,7 @@ namespace NadekoBot.Modules.ClashOfClans Bases = new List(size), GuildId = serverId, ChannelId = channelId, - Channel = NadekoBot.Client.GetGuild(serverId) - ?.GetTextChannel(channelId) + Channel = channel, }; cw.Bases.Capacity = size; for (int i = 0; i < size; i++) diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index a83b08fb..217b74d2 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -10,23 +10,20 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Image = ImageSharp.Image; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] - public class DriceRollCommands + public class DriceRollCommands : ModuleBase { private Regex dndRegex { get; } = new Regex(@"^(?\d+)d(?\d+)(?:\+(?\d+))?(?:\-(?\d+))?$", RegexOptions.Compiled); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Roll() { - //var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; var rng = new NadekoRandom(); var gen = rng.Next(1, 101); @@ -48,14 +45,9 @@ namespace NadekoBot.Modules.Gambling } //todo merge into internallDndRoll and internalRoll [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Roll(IUserMessage umsg, string arg) + public async Task Roll(string arg) { - //var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - var ordered = true; var rng = new NadekoRandom(); Match match; @@ -84,14 +76,9 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Roll(IUserMessage umsg, int num) + public async Task Roll(int num) { - //var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - var ordered = true; if (num < 1 || num > 30) @@ -138,13 +125,8 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Rolluo(IUserMessage umsg, string arg) + public async Task Rolluo(string arg) { - //var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - var ordered = false; var rng = new NadekoRandom(); Match match; @@ -173,13 +155,8 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Rolluo(IUserMessage umsg, int num) + public async Task Rolluo(int num) { - //var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - var ordered = false; if (num < 1 || num > 30) @@ -226,11 +203,8 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task NRoll(IUserMessage umsg, [Remainder] string range) + public async Task NRoll([Remainder] string range) { - //var channel = (ITextChannel)Context.Channel; - try { int rolled; diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index 19acfc47..abece27e 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -10,13 +10,14 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; +using Image = ImageSharp.Image; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] - public class DrawCommands + public class DrawCommands : ModuleBase { private static readonly ConcurrentDictionary AllDecks = new ConcurrentDictionary(); @@ -33,7 +34,6 @@ namespace NadekoBot.Modules.Gambling [RequireContext(ContextType.Guild)] public async Task Draw(int num = 1) { - //var channel = (ITextChannel)Context.Channel; var cards = AllDecks.GetOrAdd(Context.Guild, (s) => new Cards()); var images = new List(); var cardObjects = new List(); diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 554bcfef..5ea1c8a0 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -7,13 +7,14 @@ using NadekoBot.Services; using System; using System.IO; using System.Threading.Tasks; +using Image = ImageSharp.Image; namespace NadekoBot.Modules.Gambling { public partial class Gambling { [Group] - public class FlipCoinCommands + public class FlipCoinCommands : ModuleBase { private static NadekoRandom rng { get; } = new NadekoRandom(); private const string headsPath = "data/images/coins/heads.png"; diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 1cb6abd7..fa5468a7 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -110,8 +110,8 @@ namespace NadekoBot.Modules.Gambling public async Task Award(int amount, [Remainder] IRole role) { var channel = (ITextChannel)Context.Channel; - var users = Context.Guild.GetUsers() - .Where(u => u.Roles.Contains(role)) + var users = (await Context.Guild.GetUsersAsync()) + .Where(u => u.GetRoles().Contains(role)) .ToList(); await Task.WhenAll(users.Select(u => CurrencyHandler.AddCurrencyAsync(u.Id, $"Awarded by bot owner to **{role.Name}** role. ({Context.User.Username}/{Context.User.Id})", @@ -218,7 +218,7 @@ $@"```xl โ”ƒ Id โ”ƒ $$$ โ”ƒ "), (cur, cs) => cur.AppendLine($@"โ”ฃโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ•‹โ”โ”โ”โ”โ”โ”โ”โ”โ”ซ -โ”ƒ{(Context.Guild.GetUser(cs.UserId)?.Username?.TrimTo(18, true) ?? cs.UserId.ToString()),-20} โ”ƒ {cs.Amount,6} โ”ƒ") +โ”ƒ{(Context.Guild.GetUserAsync(cs.UserId).GetAwaiter().GetResult()?.Username?.TrimTo(18, true) ?? cs.UserId.ToString()),-20} โ”ƒ {cs.Amount,6} โ”ƒ") ).ToString() + "โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”ปโ”โ”โ”โ”โ”โ”โ”โ”โ”›```").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index fcd096ce..cd5b8a70 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman var embed = new EmbedBuilder().WithTitle("Hangman Game") .WithDescription(toSend) .AddField(efb => efb.WithName("It was").WithValue(Term.Word)) - .WithImage(eib => eib.WithUrl(Term.ImageUrl)); + .WithImageUrl(Term.ImageUrl); if (Errors >= MaxErrors) await GameChannel.EmbedAsync(embed.WithColor(NadekoBot.ErrorColor)).ConfigureAwait(false); else @@ -124,7 +124,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman private Task PotentialGuess(IMessage msg) { - if (Context.Channel != GameChannel) + if (msg.Channel != GameChannel) return Task.CompletedTask; // message's channel has to be the same as game's if (msg.Content.Length != 1) // message must be 1 char long { @@ -154,7 +154,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman { ++Errors; if (Errors < MaxErrors) - await GameChannel.SendErrorAsync("Hangman Game", $"{Context.User.Mention} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); + await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author.Mention} Letter `{guess}` has already been used.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); else await End().ConfigureAwait(false); return; @@ -166,19 +166,19 @@ namespace NadekoBot.Modules.Games.Commands.Hangman { if (GuessedAll) { - try { await GameChannel.SendConfirmAsync("Hangman Game", $"{Context.User.Mention} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { } + try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author.Mention} guessed a letter `{guess}`!").ConfigureAwait(false); } catch { } await End().ConfigureAwait(false); return; } - try { await GameChannel.SendConfirmAsync("Hangman Game", $"{Context.User.Mention} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); } catch { } + try { await GameChannel.SendConfirmAsync("Hangman Game", $"{msg.Author.Mention} guessed a letter `{guess}`!\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); } catch { } } else { ++Errors; if (Errors < MaxErrors) - await GameChannel.SendErrorAsync("Hangman Game", $"{Context.User.Mention} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); + await GameChannel.SendErrorAsync("Hangman Game", $"{msg.Author.Mention} Letter `{guess}` does not exist.\n" + ScrambledWord + "\n" + GetHangman()).ConfigureAwait(false); else await End().ConfigureAwait(false); } @@ -190,16 +190,12 @@ namespace NadekoBot.Modules.Games.Commands.Hangman return Task.CompletedTask; } - public string GetHangman() - { - return -$@"\_\_\_\_\_\_\_\_\_ + public string GetHangman() => $@"\_\_\_\_\_\_\_\_\_ | | | | {(Errors > 0 ? "๐Ÿ˜ฒ" : " ")} | {(Errors > 1 ? "/" : " ")} {(Errors > 2 ? "|" : " ")} {(Errors > 3 ? "\\" : " ")} | {(Errors > 4 ? "/" : " ")} {(Errors > 5 ? "\\" : " ")} | /-\"; - } } } diff --git a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs index 2ecfa08c..d24f8fd0 100644 --- a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs @@ -128,7 +128,7 @@ namespace NadekoBot.Modules.Games.Trivia private Task PotentialGuess(IMessage imsg) { - if (Context.User.IsBot) + if (imsg.Author.IsBot) return Task.CompletedTask; var umsg = imsg as IUserMessage; if (umsg == null) @@ -137,11 +137,11 @@ namespace NadekoBot.Modules.Games.Trivia { try { - if (!(Context.Channel is IGuildChannel && Context.Channel is ITextChannel)) return; - if ((Context.Channel as ITextChannel).Guild != guild) return; - if (Context.User.Id == NadekoBot.Client.CurrentUser().Id) return; + if (!(imsg.Channel is IGuildChannel && imsg.Channel is ITextChannel)) return; + if ((imsg.Channel as ITextChannel).Guild != guild) return; + if (imsg.Author.Id == NadekoBot.Client.CurrentUser().Id) return; - var guildUser = Context.User as IGuildUser; + var guildUser = imsg.Author as IGuildUser; var guess = false; await _guessLock.WaitAsync().ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index b24685fd..165c6203 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -102,21 +102,19 @@ namespace NadekoBot.Modules.Help await channel.EmbedAsync(embed).ConfigureAwait(false); } - private string GetCommandRequirements(CommandInfo cmd) - { - return String.Join(" ", cmd.Preconditions - .Where(ca => ca is OwnerOnlyAttribute || ca is RequireUserPermissionAttribute) - .Select(ca => - { - if (ca is OwnerOnlyAttribute) - return "**Bot Owner only.**"; - var cau = (RequireUserPermissionAttribute)ca; - if (cau.GuildPermission != null) - return $"**Requires {cau.GuildPermission} server permission.**".Replace("Guild", "Server"); - else - return $"**Requires {cau.ChannelPermission} channel permission.**".Replace("Guild", "Server"); - })); - } + private string GetCommandRequirements(CommandInfo cmd) => + String.Join(" ", cmd.Preconditions + .Where(ca => ca is OwnerOnlyAttribute || ca is RequireUserPermissionAttribute) + .Select(ca => + { + if (ca is OwnerOnlyAttribute) + return "**Bot Owner only.**"; + var cau = (RequireUserPermissionAttribute)ca; + if (cau.GuildPermission != null) + return $"**Requires {cau.GuildPermission} server permission.**".Replace("Guild", "Server"); + else + return $"**Requires {cau.ChannelPermission} channel permission.**".Replace("Guild", "Server"); + })); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index 5872c16d..a536f181 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -122,7 +122,7 @@ namespace NadekoBot.Modules.Music public async Task Queue([Remainder] string query) { await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, query).ConfigureAwait(false); - if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) + if ((await Context.Guild.GetCurrentUserAsync()).GetPermissions((IGuildChannel)Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -134,7 +134,7 @@ namespace NadekoBot.Modules.Music public async Task SoundCloudQueue([Remainder] string query) { await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); - if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) + if ((await Context.Guild.GetCurrentUserAsync()).GetPermissions((IGuildChannel)Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -389,7 +389,7 @@ namespace NadekoBot.Modules.Music return; } await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, radio_link, musicType: MusicType.Radio).ConfigureAwait(false); - if (Context.Guild.GetCurrentUser().GetPermissions(Context.Channel).ManageMessages) + if ((await Context.Guild.GetCurrentUserAsync()).GetPermissions((IGuildChannel)Context.Channel).ManageMessages) { await Task.Delay(10000).ConfigureAwait(false); await Context.Message.DeleteAsync().ConfigureAwait(false); @@ -793,7 +793,7 @@ namespace NadekoBot.Modules.Music try { lastFinishedMessage = await textCh.SendConfirmAsync($"๐ŸŽต Finished {song.PrettyName}").ConfigureAwait(false); } catch { } if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { - await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); + await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } diff --git a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs index b4a0932e..772cac45 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/BlacklistCommands.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions } [Group] - public class BlacklistCommands + public class BlacklistCommands : ModuleBase { public static ConcurrentHashSet BlacklistedItems { get; set; } = new ConcurrentHashSet(); @@ -35,33 +35,31 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public Task UserBlacklist(IUserMessage imsg, AddRemove action, ulong id) - => Blacklist(imsg, action, id, BlacklistType.User); + public Task UserBlacklist(AddRemove action, ulong id) + => Blacklist(action, id, BlacklistType.User); [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public Task UserBlacklist(IUserMessage imsg, AddRemove action, IUser usr) - => Blacklist(imsg, action, usr.Id, BlacklistType.User); + public Task UserBlacklist(AddRemove action, IUser usr) + => Blacklist(action, usr.Id, BlacklistType.User); [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public Task ChannelBlacklist(IUserMessage imsg, AddRemove action, ulong id) - => Blacklist(imsg, action, id, BlacklistType.Channel); + public Task ChannelBlacklist(AddRemove action, ulong id) + => Blacklist(action, id, BlacklistType.Channel); [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public Task ServerBlacklist(IUserMessage imsg, AddRemove action, ulong id) - => Blacklist(imsg, action, id, BlacklistType.Server); + public Task ServerBlacklist(AddRemove action, ulong id) + => Blacklist(action, id, BlacklistType.Server); [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public Task ServerBlacklist(IUserMessage imsg, AddRemove action, IGuild guild) - => Blacklist(imsg, action, guild.Id, BlacklistType.Server); + public Task ServerBlacklist(AddRemove action, IGuild guild) + => Blacklist(action, guild.Id, BlacklistType.Server); - private async Task Blacklist(IUserMessage imsg, AddRemove action, ulong id, BlacklistType type) + private async Task Blacklist(AddRemove action, ulong id, BlacklistType type) { - var channel = Context.Channel; - using (var uow = DbHandler.UnitOfWork()) { if (action == AddRemove.Add) @@ -105,7 +103,7 @@ namespace NadekoBot.Modules.Permissions } - await channel.SendConfirmAsync($"Blacklisted a `{type}` with id `{id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Blacklisted a `{type}` with id `{id}`").ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index cc92b01a..c6ca8919 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -12,7 +12,7 @@ namespace NadekoBot.Modules.Permissions public partial class Permissions { [Group] - public class FilterCommands + public class FilterCommands : ModuleBase { public static ConcurrentHashSet InviteFilteringChannels { get; } public static ConcurrentHashSet InviteFilteringServers { get; } diff --git a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs index 02f752a4..cf8f0ed3 100644 --- a/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs +++ b/src/NadekoBot/Modules/Permissions/PermissionExtensions.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Services.Database.Models; using System; using System.Collections.Generic; @@ -85,7 +86,7 @@ namespace NadekoBot.Modules.Permissions return null; } - public static string GetCommand(this Permission perm, IGuild guild = null) + public static string GetCommand(this Permission perm, SocketGuild guild = null) { var com = ""; switch (perm.PrimaryTarget) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index fd010b19..25433273 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -227,10 +227,11 @@ namespace NadekoBot.Modules.Searches return; } - var text = string.Join("\n", streams.Select(snc => + var text = string.Join("\n", await Task.WhenAll(streams.Select(async snc => { - return $"`{snc.Username}`'s stream on **{Context.Guild.GetTextChannel(snc.ChannelId)?.Name}** channel. ใ€`{snc.Type.ToString()}`ใ€‘"; - })); + var ch = await Context.Guild.GetTextChannelAsync(snc.ChannelId); + return $"`{snc.Username}`'s stream on **{(ch)?.Name}** channel. ใ€`{snc.Type.ToString()}`ใ€‘"; + }))); await Context.Channel.SendConfirmAsync($"You are following **{streams.Count()}** streams on this server.\n\n" + text).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 8b916ed0..1b320d58 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -506,11 +506,11 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - public async Task Videocall([Remainder] string arg = null) + public async Task Videocall([Remainder] params IUser[] users) { try { - var allUsrs = Context.Message.MentionedUsers.Append(Context.User); + var allUsrs = users.Append(Context.User); var allUsrsArray = allUsrs.ToArray(); var str = allUsrsArray.Aggregate("http://appear.in/", (current, usr) => current + Uri.EscapeUriString(usr.Username[0].ToString())); str += new NadekoRandom().Next(); @@ -526,9 +526,8 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - public async Task Avatar([Remainder] string mention = null) + public async Task Avatar([Remainder] IUser usr = null) { - var usr = Context.Message.MentionedUsers().FirstOrDefault(); if (usr == null) { await Context.Channel.SendErrorAsync("Invalid user specified.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 895395d0..9d155774 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -93,8 +93,8 @@ namespace NadekoBot.Modules.Utility .AddField(fb => fb.WithName("**Joined Server**").WithValue($"{user.JoinedAt?.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Joined Discord**").WithValue($"{user.CreatedAt.ToString("dd.MM.yyyy HH:mm")}").WithIsInline(true)) .AddField(fb => fb.WithName("**Current Game**").WithValue($"{(user.Game?.Name == null ? "-" : user.Game.Value.Name)}").WithIsInline(true)) - .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.Roles.Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) - .WithThumbnail(tn => tn.WithUrl(user.AvatarUrl)) + .AddField(fb => fb.WithName("**Roles**").WithValue($"**({user.RoleIds.Count})** - {string.Join(", ", user.GetRoles().Select(r => r.Name)).SanitizeMentions()}").WithIsInline(true)) + .WithThumbnailUrl(user.AvatarUrl) .WithColor(NadekoBot.OkColor); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index b14406d8..cb87b710 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -54,7 +54,7 @@ namespace NadekoBot.Modules.Utility var role = Context.Guild.Roles.Where(r => r.Name.ToUpperInvariant() == roleStr).FirstOrDefault(); if (role == null) continue; send += $"```css\n[{role.Name}]\n"; - send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.Roles.Contains(role)).Select(u => u.ToString())); + send += string.Join(", ", (await Context.Guild.GetUsersAsync()).Where(u => u.RoleIds.Contains(role.Id)).Select(u => u.ToString())); send += $"\n```"; } var usr = Context.User as IGuildUser; @@ -125,7 +125,7 @@ namespace NadekoBot.Modules.Utility return; if (target != null) { - await channel.SendConfirmAsync($"โš” **Page #{page} of roles for {target.Username}**", $"```css\nโ€ข " + string.Join("\nโ€ข ", target.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); + await channel.SendConfirmAsync($"โš” **Page #{page} of roles for {target.Username}**", $"```css\nโ€ข " + string.Join("\nโ€ข ", target.GetRoles().Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); } else { diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 10615415..d00c2e00 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -21,15 +21,9 @@ namespace NadekoBot.Services { public class IGuildUserComparer : IEqualityComparer { - public bool Equals(IGuildUser x, IGuildUser y) - { - return x.Id == y.Id; - } + public bool Equals(IGuildUser x, IGuildUser y) => x.Id == y.Id; - public int GetHashCode(IGuildUser obj) - { - return obj.Id.GetHashCode(); - } + public int GetHashCode(IGuildUser obj) => obj.Id.GetHashCode(); } public class CommandHandler { @@ -49,7 +43,7 @@ namespace NadekoBot.Services } public async Task StartHandling() { - ownerChannels = (await Task.WhenAll(_client.GetGuilds().SelectMany(g => g.GetUsersAsync().GetAwaiter().GetResult()) + ownerChannels = (await Task.WhenAll(_client.GetGuilds().SelectMany(g => g.Users) .Where(u => NadekoBot.Credentials.OwnerIds.Contains(u.Id)) .Distinct(new IGuildUserComparer()) .Select(async u => { try { return await u.CreateDMChannelAsync(); } catch { return null; } }))) @@ -70,14 +64,14 @@ namespace NadekoBot.Services if (usrMsg == null) return; - if (usrContext.User.IsBot || !NadekoBot.Ready) //no bots + if (msg.Author.IsBot || !NadekoBot.Ready) //no bots return; - var guild = (Context.Channel as SocketTextChannel)?.Guild; + var guild = (msg.Channel as SocketTextChannel)?.Guild; - if (guild != null && guild.OwnerId != usrContext.User.Id) + if (guild != null && guild.OwnerId != msg.Author.Id) { - if (Permissions.FilterCommands.InviteFilteringChannels.Contains(usrContext.Channel.Id) || + if (Permissions.FilterCommands.InviteFilteringChannels.Contains(msg.Channel.Id) || Permissions.FilterCommands.InviteFilteringServers.Contains(guild.Id)) { if (usrMsg.Content.IsDiscordInvite()) @@ -89,12 +83,12 @@ namespace NadekoBot.Services } catch (HttpException ex) { - _log.Warn("I do not have permission to filter invites in channel with id " + usrContext.Channel.Id, ex); + _log.Warn("I do not have permission to filter invites in channel with id " + msg.Channel.Id, ex); } } } - var filteredWords = Permissions.FilterCommands.FilteredWordsForChannel(usrContext.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id)); + var filteredWords = Permissions.FilterCommands.FilteredWordsForChannel(msg.Channel.Id, guild.Id).Concat(Permissions.FilterCommands.FilteredWordsForServer(guild.Id)); var wordsInMessage = usrMsg.Content.ToLowerInvariant().Split(' '); if (filteredWords.Any(w => wordsInMessage.Contains(w))) { @@ -105,7 +99,7 @@ namespace NadekoBot.Services } catch (HttpException ex) { - _log.Warn("I do not have permission to filter words in channel with id " + usrContext.Channel.Id, ex); + _log.Warn("I do not have permission to filter words in channel with id " + msg.Channel.Id, ex); } } } @@ -113,8 +107,8 @@ namespace NadekoBot.Services BlacklistItem blacklistedItem; if ((blacklistedItem = Permissions.BlacklistCommands.BlacklistedItems.FirstOrDefault(bi => (bi.Type == BlacklistItem.BlacklistType.Server && bi.ItemId == guild?.Id) || - (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == Context.Channel.Id) || - (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == usrContext.User.Id))) != null) + (bi.Type == BlacklistItem.BlacklistType.Channel && bi.ItemId == msg.Channel.Id) || + (bi.Type == BlacklistItem.BlacklistType.User && bi.ItemId == msg.Author.Id))) != null) { return; } @@ -146,12 +140,12 @@ namespace NadekoBot.Services try { - var t = await ExecuteCommand(usrMsg, usrMsg.Content, guild, usrContext.User, MultiMatchHandling.Best); + var t = await ExecuteCommand(usrMsg, usrMsg.Content, guild, msg.Author, MultiMatchHandling.Best); var command = t.Item1; var permCache = t.Item2; var result = t.Item3; sw.Stop(); - var channel = (usrContext.Channel as ITextChannel); + var channel = (msg.Channel as ITextChannel); if (result.IsSuccess) { await CommandExecuted(usrMsg, command); @@ -160,7 +154,7 @@ namespace NadekoBot.Services "Server: {1}\n\t" + "Channel: {2}\n\t" + "Message: {3}", - usrContext.User + " [" + usrContext.User.Id + "]", // {0} + msg.Author + " [" + msg.Author.Id + "]", // {0} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} usrMsg.Content, // {3} @@ -175,7 +169,7 @@ namespace NadekoBot.Services "Channel: {2}\n\t" + "Message: {3}\n\t" + "Error: {4}", - usrContext.User + " [" + usrContext.User.Id + "]", // {0} + msg.Author + " [" + msg.Author.Id + "]", // {0} (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} usrMsg.Content,// {3} @@ -185,18 +179,18 @@ namespace NadekoBot.Services if (guild != null && command != null && result.Error == CommandError.Exception) { if (permCache != null && permCache.Verbose) - try { await Context.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } + try { await msg.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } } } else { - if (Context.Channel is IPrivateChannel) + if (msg.Channel is IPrivateChannel) { //rofl, gotta do this to prevent this message from occuring on polls int vote; if (int.TryParse(msg.Content, out vote)) return; - await Context.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); + await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); await DMForwardCommands.HandleDMForwarding(msg, ownerChannels); } @@ -212,7 +206,7 @@ namespace NadekoBot.Services return; } - public async Task> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) { + public async Task> ExecuteCommand(IUserMessage message, string input, SocketGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) { var searchResult = _commandService.Search(message, input); if (!searchResult.IsSuccess) return new Tuple(null, null, searchResult); @@ -273,16 +267,16 @@ namespace NadekoBot.Services } }); int index; - if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(message, cmd.Text, cmd.Module.Name, out index)) + if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(message, cmd.Aliases.First(), cmd.Module.Name, out index)) { var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand(guild)}** is preventing this action."; return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); } - if (cmd.Module.Source.Name == typeof(Permissions).Name) //permissions, you must have special role + if (cmd.Module.Name == typeof(Permissions).Name) { - if (!((IGuildUser)user).Roles.Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) + if (!((IGuildUser)user).GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) { return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); } @@ -299,16 +293,4 @@ namespace NadekoBot.Services return new Tuple(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); } } - - public class CommandExecutedEventArgs - { - public CommandInfo Command { get; } - public IUserMessage Message { get; } - - public CommandExecutedEventArgs(CommandInfo cmd) - { - Message = msg; - Command = cmd; - } - } } diff --git a/src/NadekoBot/Services/Impl/BotCredentials.cs b/src/NadekoBot/Services/Impl/BotCredentials.cs index 2aa58a33..fdd0a1fa 100644 --- a/src/NadekoBot/Services/Impl/BotCredentials.cs +++ b/src/NadekoBot/Services/Impl/BotCredentials.cs @@ -46,7 +46,7 @@ namespace NadekoBot.Services.Impl configBuilder.AddJsonFile(credsFileName, true) .AddEnvironmentVariables("NadekoBot_"); - var data = configBuilder; + var data = configBuilder.Build(); Token = data[nameof(Token)]; if (string.IsNullOrWhiteSpace(Token)) diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 618d8116..357a5f32 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -22,8 +22,8 @@ namespace NadekoBot.Services.Impl public int CommandsRan { get; private set; } = 0; public string Heap => Math.Round((double)GC.GetTotalMemory(false) / 1.MiB(), 2).ToString(); public double MessagesPerSecond => MessageCounter / (double)GetUptime().TotalSeconds; - public int TextChannels => client.GetGuilds().SelectMany(g => g.GetChannels().Where(c => c is ITextChannel)).Count(); - public int VoiceChannels => client.GetGuilds().SelectMany(g => g.GetChannels().Where(c => c is IVoiceChannel)).Count(); + public int TextChannels => client.GetGuilds().SelectMany(g => g.Channels.Where(c => c is ITextChannel)).Count(); + public int VoiceChannels => client.GetGuilds().SelectMany(g => g.Channels.Where(c => c is IVoiceChannel)).Count(); public string OwnerIds => string.Join(", ", NadekoBot.Credentials.OwnerIds); @@ -64,10 +64,10 @@ namespace NadekoBot.Services.Impl catch { } }, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1)); } - public async Task Print() + public Task Print() { - var curUser = await client.CurrentUser(); - return $@" + var curUser = client.CurrentUser(); + return Task.FromResult($@" Author: [{Author}] | Library: [{Library}] Bot Version: [{BotVersion}] Bot ID: {curUser.Id} @@ -75,7 +75,7 @@ Owner ID(s): {OwnerIds} Uptime: {GetUptimeString()} Servers: {client.GetGuilds().Count} | TextChannels: {TextChannels} | VoiceChannels: {VoiceChannels} Commands Ran this session: {CommandsRan} -Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]"; +Messages: {MessageCounter} [{MessagesPerSecond:F2}/sec] Heap: [{Heap} MB]"); } public Task Reset() diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index 8bb79fd6..6be032d6 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -69,7 +69,7 @@ namespace NadekoBot public IReadOnlyCollection GetGuilds() => Clients.SelectMany(c => c.Guilds).ToList(); - public IGuild GetGuild(ulong id) => + public SocketGuild GetGuild(ulong id) => Clients.Select(c => c.GetGuild(id)).FirstOrDefault(g => g != null); public Task GetDMChannelAsync(ulong channelId) => diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index c47b2c51..37ddc535 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -30,6 +30,12 @@ namespace NadekoBot.Extensions return await ownerPrivate.SendMessageAsync(message).ConfigureAwait(false); } + //public static async Task> MentionedUsers(this IUserMessage msg) => + + + public static IEnumerable GetRoles(this IGuildUser user) => + user.RoleIds.Select(r => user.Guild.GetRole(r)).Where(r => r != null); + public static IEnumerable ForEach(this IEnumerable elems, Action exec) { foreach (var elem in elems) From caef908a0ea00b313bff7d24d0608466d4965207 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 18 Dec 2016 01:52:53 +0100 Subject: [PATCH 12/30] more work --- NadekoBot.sln | 32 ++++++++++++++++++ .../Modules/Permissions/Permissions.cs | 7 ++-- src/NadekoBot/NadekoBot.cs | 2 +- src/NadekoBot/Services/CommandHandler.cs | 33 ++++++++++--------- src/NadekoBot/Services/Impl/StatsService.cs | 2 +- src/NadekoBot/ShardedDiscordClient.cs | 8 ++--- src/NadekoBot/project.json | 10 ++++-- 7 files changed, 68 insertions(+), 26 deletions(-) diff --git a/NadekoBot.sln b/NadekoBot.sln index 6a872243..350bd395 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -12,6 +12,14 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NadekoBot", "src\NadekoBot\NadekoBot.xproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}" EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "Discord.Net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "Discord.Net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{E5F4786F-58F3-469E-8C87-1908A95436B7}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "Discord.Net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{63F5B5C8-56FE-4B53-8003-B58CEB451EF9}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "Discord.Net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{8CBA56CD-A954-481E-8358-F36273757A6B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -25,6 +33,30 @@ Global {45EC1473-C678-4857-A544-07DFE0D0B478}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.ActiveCfg = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.Build.0 = Release|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.Build.0 = Release|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E5F4786F-58F3-469E-8C87-1908A95436B7}.Release|Any CPU.Build.0 = Release|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.Build.0 = Release|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8CBA56CD-A954-481E-8358-F36273757A6B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 5c50f075..7d260490 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -8,6 +8,7 @@ using Discord; using NadekoBot.Services.Database.Models; using System.Collections.Concurrent; using NadekoBot.Extensions; +using Discord.WebSocket; namespace NadekoBot.Modules.Permissions { @@ -102,7 +103,7 @@ namespace NadekoBot.Modules.Permissions { var perms = uow.GuildConfigs.PermissionsFor(Context.Guild.Id).RootPermission; var i = 1 + 20 * (page - 1); - toSend = Format.Code($"๐Ÿ“„ Permissions page {page}") + "\n\n" + String.Join("\n", perms.AsEnumerable().Skip((page - 1) * 20).Take(20).Select(p => $"`{(i++)}.` {(p.Next == null ? Format.Bold(p.GetCommand(Context.Guild) + " [uneditable]") : (p.GetCommand(Context.Guild)))}")); + toSend = Format.Code($"๐Ÿ“„ Permissions page {page}") + "\n\n" + String.Join("\n", perms.AsEnumerable().Skip((page - 1) * 20).Take(20).Select(p => $"`{(i++)}.` {(p.Next == null ? Format.Bold(p.GetCommand((SocketGuild)Context.Guild) + " [uneditable]") : (p.GetCommand((SocketGuild)Context.Guild)))}")); } await Context.Channel.SendMessageAsync(toSend).ConfigureAwait(false); @@ -148,7 +149,7 @@ namespace NadekoBot.Modules.Permissions uow2._context.SaveChanges(); } - await Context.Channel.SendConfirmAsync($"โœ… {Context.User.Mention} removed permission **{p.GetCommand(Context.Guild)}** from position #{index + 1}.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"โœ… {Context.User.Mention} removed permission **{p.GetCommand((SocketGuild)Context.Guild)}** from position #{index + 1}.").ConfigureAwait(false); } catch (ArgumentOutOfRangeException) { @@ -255,7 +256,7 @@ namespace NadekoBot.Modules.Permissions }, (id, old) => { old.RootPermission = config.RootPermission; return old; }); await uow.CompleteAsync().ConfigureAwait(false); } - await Context.Channel.SendConfirmAsync($"`Moved permission:` \"{fromPerm.GetCommand(Context.Guild)}\" `from #{++from} to #{++to}.`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"`Moved permission:` \"{fromPerm.GetCommand((SocketGuild)Context.Guild)}\" `from #{++from} to #{++to}.`").ConfigureAwait(false); return; } catch (Exception e) when (e is ArgumentOutOfRangeException || e is IndexOutOfRangeException) diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 6168b062..1178508e 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -83,7 +83,7 @@ namespace NadekoBot //setup typereaders CommandService.AddTypeReader(new PermissionActionTypeReader()); CommandService.AddTypeReader(new CommandTypeReader()); - CommandService.AddTypeReader(new ModuleTypeReader()); + CommandService.AddTypeReader(new ModuleTypeReader()); CommandService.AddTypeReader(new GuildTypeReader()); //connect diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index d00c2e00..42d4e9d1 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -60,7 +60,7 @@ namespace NadekoBot.Services private async Task MessageReceivedHandler(SocketMessage msg) { - var usrMsg = msg as SocketUserMessage; + var usrMsg = msg as SocketUserMessage; if (usrMsg == null) return; @@ -140,7 +140,7 @@ namespace NadekoBot.Services try { - var t = await ExecuteCommand(usrMsg, usrMsg.Content, guild, msg.Author, MultiMatchHandling.Best); + var t = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), usrMsg.Content, DependencyMap.Empty, MultiMatchHandling.Best); var command = t.Item1; var permCache = t.Item2; var result = t.Item3; @@ -206,24 +206,27 @@ namespace NadekoBot.Services return; } - public async Task> ExecuteCommand(IUserMessage message, string input, SocketGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) { - var searchResult = _commandService.Search(message, input); + public async Task> ExecuteCommand(CommandContext context, string input, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) + { + dependencyMap = dependencyMap ?? DependencyMap.Empty; + + var searchResult = _commandService.Search(context, input); if (!searchResult.IsSuccess) return new Tuple(null, null, searchResult); var commands = searchResult.Commands; for (int i = commands.Count - 1; i >= 0; i--) { - var preconditionResult = await commands[i].CheckPreconditions(message); + var preconditionResult = await commands[i].CheckPreconditionsAsync(context).ConfigureAwait(false); if (!preconditionResult.IsSuccess) { if (commands.Count == 1) - return new Tuple(null, null, searchResult); + return new Tuple(null, null, preconditionResult); else continue; } - var parseResult = await commands[i].Parse(message, searchResult, preconditionResult); + var parseResult = await commands[i].ParseAsync(context, searchResult, preconditionResult).ConfigureAwait(false); if (!parseResult.IsSuccess) { if (parseResult.Error == CommandError.MultipleMatches) @@ -251,13 +254,13 @@ namespace NadekoBot.Services var cmd = commands[i]; bool resetCommand = cmd.Name == "ResetPermissions"; PermissionCache pc; - if (guild != null) + if (context.Guild != null) { - pc = Permissions.Cache.GetOrAdd(guild.Id, (id) => + pc = Permissions.Cache.GetOrAdd(context.Guild.Id, (id) => { using (var uow = DbHandler.UnitOfWork()) { - var config = uow.GuildConfigs.PermissionsFor(guild.Id); + var config = uow.GuildConfigs.PermissionsFor(context.Guild.Id); return new PermissionCache() { Verbose = config.VerbosePermissions, @@ -267,16 +270,16 @@ namespace NadekoBot.Services } }); int index; - if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(message, cmd.Aliases.First(), cmd.Module.Name, out index)) + if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(context.Message, cmd.Aliases.First(), cmd.Module.Name, out index)) { - var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand(guild)}** is preventing this action."; + var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand((SocketGuild)context.Guild)}** is preventing this action."; return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); } if (cmd.Module.Name == typeof(Permissions).Name) { - if (!((IGuildUser)user).GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) + if (!((IGuildUser)context.User).GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) { return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); } @@ -284,10 +287,10 @@ namespace NadekoBot.Services } - if (CmdCdsCommands.HasCooldown(cmd, guild, user)) + if (CmdCdsCommands.HasCooldown(cmd, context.Guild, context.User)) return new Tuple(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); - return new Tuple(commands[i], null, await commands[i].Execute(message, parseResult)); + return new Tuple(commands[i], null, await commands[i].Execute(context, parseResult, dependencyMap)); } return new Tuple(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); diff --git a/src/NadekoBot/Services/Impl/StatsService.cs b/src/NadekoBot/Services/Impl/StatsService.cs index 357a5f32..a691b373 100644 --- a/src/NadekoBot/Services/Impl/StatsService.cs +++ b/src/NadekoBot/Services/Impl/StatsService.cs @@ -14,7 +14,7 @@ namespace NadekoBot.Services.Impl private ShardedDiscordClient client; private DateTime started; - public const string BotVersion = "1.0-rc2"; + public const string BotVersion = "1.0-rc3"; public string Author => "Kwoth#2560"; public string Library => "Discord.Net"; diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index 6be032d6..450289e6 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -60,11 +60,11 @@ namespace NadekoBot Clients = clientList.AsReadOnly(); } - public ISelfUser CurrentUser() => - Clients[0].CurrentUser; + public DiscordSocketClient MainClient => + Clients[0]; - public ISelfUser[] GetAllCurrentUsers() => - Clients.Select(c => c.CurrentUser).ToArray(); + public SocketSelfUser CurrentUser() => + Clients[0].CurrentUser; public IReadOnlyCollection GetGuilds() => Clients.SelectMany(c => c.Guilds).ToList(); diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index c12a7bf9..31325e07 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -39,8 +39,14 @@ "NLog": "5.0.0-beta03", "System.Diagnostics.Contracts": "4.3.0", "System.Xml.XPath": "4.3.0", - "Discord.Net.Commands": "1.0.0-beta2-*", - "Discord.Net.WebSocket": "1.0.0-beta2-*" + "Discord.Net.Commands": { + "target": "project", + "version": "1.0.0-*" + }, + "Discord.Net.WebSocket": { + "target": "project", + "version": "1.0.0-*" + } }, "tools": { "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final", From 5b55ab67756e799bf4d3c00b2a9546154321ac20 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 21 Dec 2016 09:33:47 +0100 Subject: [PATCH 13/30] More work on moving to beta2, almost done --- src/NadekoBot/Attributes/NadekoModule.cs | 2 +- .../Commands/AntiRaidCommands.cs | 4 +- .../Commands/AutoAssignRoleCommands.cs | 2 +- .../Commands/CrossServerTextChannel.cs | 2 +- .../Administration/Commands/LogCommand.cs | 2 +- .../Commands/MessageRepeater.cs | 2 +- .../Administration/Commands/MuteCommands.cs | 4 +- .../Commands/PlayingRotateCommands.cs | 4 +- .../Commands/ServerGreetCommands.cs | 2 +- .../Modules/ClashOfClans/ClashOfClans.cs | 24 ++++---- .../CustomReactions/CustomReactions.cs | 8 +-- .../Modules/Gambling/Commands/AnimalRacing.cs | 2 +- .../Gambling/Commands/FlipCoinCommand.cs | 4 +- .../Modules/Games/Commands/PollCommands.cs | 2 +- src/NadekoBot/Modules/Help/Help.cs | 10 ++-- src/NadekoBot/Modules/NSFW/NSFW.cs | 2 +- .../Permissions/Commands/CmdCdsCommands.cs | 2 +- .../Permissions/Commands/FilterCommands.cs | 2 +- .../Searches/Commands/AnimeSearchCommands.cs | 4 +- .../Modules/Searches/Commands/LoLCommands.cs | 2 +- .../Commands/StreamNotificationCommands.cs | 2 +- .../Modules/Searches/Commands/Translator.cs | 2 +- .../Modules/Utility/Commands/Remind.cs | 8 +-- src/NadekoBot/Modules/Utility/Utility.cs | 2 +- src/NadekoBot/NadekoBot.cs | 4 +- src/NadekoBot/Services/CommandHandler.cs | 56 ++++++++++++++----- src/NadekoBot/_Extensions/Extensions.cs | 15 ++++- 27 files changed, 109 insertions(+), 66 deletions(-) diff --git a/src/NadekoBot/Attributes/NadekoModule.cs b/src/NadekoBot/Attributes/NadekoModule.cs index 832d7ad4..30ef1c51 100644 --- a/src/NadekoBot/Attributes/NadekoModule.cs +++ b/src/NadekoBot/Attributes/NadekoModule.cs @@ -26,7 +26,7 @@ namespace NadekoBot.Attributes } } - public NadekoModuleAttribute(string moduleName, string defaultPrefix) : base(GetModulePrefix(moduleName, defaultPrefix)) + public NadekoModuleAttribute(string moduleName, string defaultPrefix) : base(GetModulePrefix(moduleName, defaultPrefix), moduleName) { //AppendSpace = false; } diff --git a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs index a220076d..2ef5dff0 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AntiRaidCommands.cs @@ -197,7 +197,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] - public async Task AntiRaid(IUserMessage imsg, int userThreshold, int seconds, PunishmentAction action) + public async Task AntiRaid(int userThreshold, int seconds, PunishmentAction action) { if (userThreshold < 2 || userThreshold > 30) { @@ -239,7 +239,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] - public async Task AntiSpam(IUserMessage imsg, int messageCount=3, PunishmentAction action = PunishmentAction.Mute) + public async Task AntiSpam(int messageCount=3, PunishmentAction action = PunishmentAction.Mute) { if (messageCount < 2 || messageCount > 10) return; diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 902f4348..41c43c46 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -46,7 +46,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] - public async Task AutoAssignRole(IUserMessage umsg, [Remainder] IRole role = null) + public async Task AutoAssignRole([Remainder] IRole role = null) { GuildConfig conf; using (var uow = DbHandler.UnitOfWork()) diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index 09335700..85847287 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -73,7 +73,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task Jcsc(IUserMessage imsg, int token) + public async Task Jcsc(int token) { ConcurrentHashSet set; if (!Subscribers.TryGetValue(token, out set)) diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index ab358cb7..91a25b1b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -748,7 +748,7 @@ namespace NadekoBot.Modules.Administration //[LocalizedCommand, LocalizedDescription, LocalizedSummary, LocalizedAlias] //[RequireContext(ContextType.Guild)] - //public async Task VoiPresIgnore(IUserMessage imsg, IVoiceChannel voiceChannel) + //public async Task VoiPresIgnore(IVoiceChannel voiceChannel) //{ // //var channel = (ITextChannel)Context.Channel; // int removed; diff --git a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs index e470d4d1..c28f2700 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MessageRepeater.cs @@ -116,7 +116,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageMessages)] - public async Task Repeat(IUserMessage imsg, int minutes, [Remainder] string message) + public async Task Repeat(int minutes, [Remainder] string message) { if (minutes < 1 || minutes > 10080) return; diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index fbf443de..007ac331 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -136,7 +136,7 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(1)] - public async Task SetMuteRole(IUserMessage imsg, [Remainder] string name) + public async Task SetMuteRole([Remainder] string name) { //var channel = (ITextChannel)Context.Channel; name = name.Trim(); @@ -158,7 +158,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.ManageRoles)] [Priority(0)] public Task SetMuteRole([Remainder] IRole role) - => SetMuteRole(Context.Message, role.Name); + => SetMuteRole(role.Name); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs index 0101e1c0..cd06fcff 100644 --- a/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/PlayingRotateCommands.cs @@ -104,7 +104,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task AddPlaying(IUserMessage umsg, [Remainder] string status) + public async Task AddPlaying([Remainder] string status) { using (var uow = DbHandler.UnitOfWork()) { @@ -134,7 +134,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [OwnerOnly] - public async Task RemovePlaying(IUserMessage umsg, int index) + public async Task RemovePlaying(int index) { index -= 1; diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index a663d120..44e8b37d 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -362,7 +362,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.ManageGuild)] - public async Task ByeDel(IUserMessage umsg, int timer = 30) + public async Task ByeDel(int timer = 30) { await ServerGreetCommands.SetByeDel(Context.Guild.Id, timer).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index d5831e81..4ee08f4b 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -58,7 +58,7 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CreateWar(IUserMessage umsg, int size, [Remainder] string enemyClan = null) + public async Task CreateWar(int size, [Remainder] string enemyClan = null) { if (!(Context.User as IGuildUser).GuildPermissions.ManageChannels) return; @@ -88,12 +88,12 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task StartWar(IUserMessage umsg, [Remainder] string number = null) + public async Task StartWar([Remainder] string number = null) { int num = 0; int.TryParse(number, out num); - var warsInfo = GetWarInfo(umsg, Context.Guild, num); + var warsInfo = GetWarInfo(Context.Guild, num); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -114,7 +114,7 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ListWar(IUserMessage umsg, [Remainder] string number = null) + public async Task ListWar([Remainder] string number = null) { // if number is null, print all wars in a short way @@ -145,7 +145,7 @@ namespace NadekoBot.Modules.ClashOfClans var num = 0; int.TryParse(number, out num); //if number is not null, print the war needed - var warsInfo = GetWarInfo(umsg, Context.Guild, num); + var warsInfo = GetWarInfo(Context.Guild, num); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -156,9 +156,9 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Claim(IUserMessage umsg, int number, int baseNumber, [Remainder] string other_name = null) + public async Task Claim(int number, int baseNumber, [Remainder] string other_name = null) { - var warsInfo = GetWarInfo(umsg, Context.Guild, number); + var warsInfo = GetWarInfo(Context.Guild, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.ClashOfClans [RequireContext(ContextType.Guild)] public async Task EndWar(int number) { - var warsInfo = GetWarInfo(Context.Message, Context.Guild, number); + var warsInfo = GetWarInfo(Context.Guild, number); if (warsInfo == null) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ That war does not exist.").ConfigureAwait(false); @@ -223,9 +223,9 @@ namespace NadekoBot.Modules.ClashOfClans [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Unclaim(IUserMessage umsg, int number, [Remainder] string otherName = null) + public async Task Unclaim(int number, [Remainder] string otherName = null) { - var warsInfo = GetWarInfo(umsg, Context.Guild, number); + var warsInfo = GetWarInfo(Context.Guild, number); if (warsInfo == null || warsInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -250,7 +250,7 @@ namespace NadekoBot.Modules.ClashOfClans private async Task FinishClaim(int number, int baseNumber, int stars = 3) { - var warInfo = GetWarInfo(Context.Message, Context.Guild, number); + var warInfo = GetWarInfo(Context.Guild, number); if (warInfo == null || warInfo.Item1.Count == 0) { await Context.Channel.SendErrorAsync("๐Ÿ”ฐ **That war does not exist.**").ConfigureAwait(false); @@ -276,7 +276,7 @@ namespace NadekoBot.Modules.ClashOfClans } } - private static Tuple, int> GetWarInfo(IUserMessage umsg, IGuild guild, int num) + private static Tuple, int> GetWarInfo(IGuild guild, int num) { List wars = null; ClashWars.TryGetValue(guild.Id, out wars); diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index c16f7c91..4f99c99b 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task ShowCustReact(IUserMessage imsg, int id) + public async Task ShowCustReact(int id) { ConcurrentHashSet customReactions; if (Context.Guild == null) @@ -229,7 +229,7 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task DelCustReact(IUserMessage imsg, int id) + public async Task DelCustReact(int id) { if ((Context.Guild == null && !NadekoBot.Credentials.IsOwner(Context.User)) || (Context.Guild != null && !((IGuildUser)Context.User).GuildPermissions.Administrator)) { @@ -268,7 +268,7 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task CrStatsClear(IUserMessage imsg, string trigger = null) + public async Task CrStatsClear(string trigger = null) { if (string.IsNullOrWhiteSpace(trigger)) { @@ -290,7 +290,7 @@ namespace NadekoBot.Modules.CustomReactions } [NadekoCommand, Usage, Description, Aliases] - public async Task CrStats(IUserMessage imsg, int page = 1) + public async Task CrStats(int page = 1) { if (page < 1) return; diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index 5751d1b2..50f4f450 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task JoinRace(IUserMessage umsg, int amount = 0) + public async Task JoinRace(int amount = 0) { if (amount < 0) amount = 0; diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 5ea1c8a0..fc6c60a6 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -22,7 +22,7 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Flip(IUserMessage imsg, int count = 1) + public async Task Flip(int count = 1) { //var channel = (ITextChannel)Context.Channel; if (count == 1) @@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Betflip(IUserMessage umsg, int amount, string guess) + public async Task Betflip(int amount, string guess) { //var channel = (ITextChannel)Context.Channel; var guildUser = (IGuildUser)Context.User; diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index 41ea2253..ad077586 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireUserPermission(GuildPermission.ManageMessages)] [RequireContext(ContextType.Guild)] - public Task PublicPoll(IUserMessage umsg, [Remainder] string arg = null) + public Task PublicPoll([Remainder] string arg = null) => InternalStartPoll(arg, isPublic: true); private async Task InternalStartPoll(string arg, bool isPublic = false) diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 165c6203..16fb59f3 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -38,12 +38,14 @@ namespace NadekoBot.Modules.Help public async Task Modules() { - await Context.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`") + await Context.Channel.SendMessageAsync("๐Ÿ“œ **List of modules:** ```css\nโ€ข " + string.Join("\nโ€ข ", + NadekoBot.CommandService.Modules.GroupBy(mi => mi.GetTopLevelModule()).Select(m => m.Key.Name).OrderBy(m => m)) + + $"\n``` โ„น๏ธ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") .ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - public async Task Commands(IUserMessage umsg, [Remainder] string module = null) + public async Task Commands([Remainder] string module = null) { var channel = Context.Channel; @@ -73,7 +75,7 @@ namespace NadekoBot.Modules.Help } [NadekoCommand, Usage, Description, Aliases] - public async Task H(IUserMessage umsg, [Remainder] string comToFind = null) + public async Task H([Remainder] string comToFind = null) { var channel = Context.Channel; @@ -142,7 +144,7 @@ namespace NadekoBot.Modules.Help helpstr.AppendLine("----------------|--------------|-------"); lastModule = com.Module.Name; } - helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.Prefix)} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.Prefix)}"); + helpstr.AppendLine($"{string.Join(" ", com.Aliases.Select(a => "`" + a + "`"))} | {string.Format(com.Summary, com.Module.GetPrefix())} {GetCommandRequirements(com)} | {string.Format(com.Remarks, com.Module.GetPrefix())}"); } helpstr = helpstr.Replace(NadekoBot.Client.CurrentUser().Username , "@BotName"); File.WriteAllText("../../docs/Commands List.md", helpstr.ToString()); diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index e4b0fa29..b01d9480 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -214,7 +214,7 @@ namespace NadekoBot.Modules.NSFW if (matches.Count == 0) return null; - return matches[rng.Next(0, matches.Count)].Groups["ll"].Value; + return "http:" + matches[rng.Next(0, matches.Count)].Groups["ll"].Value; } } diff --git a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs index 4097783d..8ba1379a 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/CmdCdsCommands.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Permissions } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CmdCooldown(IUserMessage imsg, CommandInfo command, int secs) + public async Task CmdCooldown(CommandInfo command, int secs) { var channel = (ITextChannel)Context.Channel; if (secs < 0 || secs > 3600) diff --git a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs index c6ca8919..c4711a7f 100644 --- a/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs +++ b/src/NadekoBot/Modules/Permissions/Commands/FilterCommands.cs @@ -180,7 +180,7 @@ namespace NadekoBot.Modules.Permissions [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task FilterWord(IUserMessage imsg, [Remainder] string word) + public async Task FilterWord([Remainder] string word) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index 66402bb4..7508012d 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -53,7 +53,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Anime(IUserMessage umsg, [Remainder] string query) + public async Task Anime([Remainder] string query) { var channel = (ITextChannel)Context.Channel; @@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Manga(IUserMessage umsg, [Remainder] string query) + public async Task Manga([Remainder] string query) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs index d7b3a857..e0e95d97 100644 --- a/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/LoLCommands.cs @@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Searches // public override void Init(CommandGroupBuilder cgb) // { -// cgb.CreateCommand(Module.Prefix + "lolchamp") +// cgb.CreateCommand(Module.Name + "lolchamp") // .Description($"Shows League Of Legends champion statistics. If there are spaces/apostrophes or in the name - omit them. Optional second parameter is a role. |`{Prefix}lolchamp Riven` or `{Prefix}lolchamp Annie sup`") // .Parameter("champ", ParameterType.Required) // .Parameter("position", ParameterType.Unparsed) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 25433273..f607a5d9 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -268,7 +268,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task CheckStream(IUserMessage imsg, FollowedStream.FollowedStreamType platform, [Remainder] string username) + public async Task CheckStream(FollowedStream.FollowedStreamType platform, [Remainder] string username) { var stream = username?.Trim(); if (string.IsNullOrWhiteSpace(stream)) diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index 121ff140..0222ba81 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -67,7 +67,7 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - public async Task Translate(IUserMessage umsg, string langs, [Remainder] string text = null) + public async Task Translate(string langs, [Remainder] string text = null) { try { diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index ef6a92b2..92bbb3fb 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -100,7 +100,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Remind(IUserMessage umsg, MeOrHere meorhere, string timeStr, [Remainder] string message) + public async Task Remind(MeOrHere meorhere, string timeStr, [Remainder] string message) { IMessageChannel target; if (meorhere == MeOrHere.Me) @@ -111,13 +111,13 @@ namespace NadekoBot.Modules.Utility { target = Context.Channel; } - await Remind(umsg, target, timeStr, message).ConfigureAwait(false); + await Remind(target, timeStr, message).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Remind(IUserMessage umsg, IMessageChannel ch, string timeStr, [Remainder] string message) + public async Task Remind(IMessageChannel ch, string timeStr, [Remainder] string message) { var channel = (ITextChannel)Context.Channel; @@ -193,7 +193,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task RemindTemplate(IUserMessage umsg, [Remainder] string arg) + public async Task RemindTemplate([Remainder] string arg) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index cb87b710..d24d51a0 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -192,7 +192,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] - public async Task ListServers(IUserMessage imsg, int page = 1) + public async Task ListServers(int page = 1) { var channel = (ITextChannel)Context.Channel; diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index 1178508e..3ee8e2e5 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -28,7 +28,7 @@ namespace NadekoBot public static CommandService CommandService { get; private set; } public static CommandHandler CommandHandler { get; private set; } - public static ShardedDiscordClient Client { get; private set; } + public static ShardedDiscordClient Client { get; private set; } public static BotCredentials Credentials { get; private set; } public static GoogleApiService Google { get; private set; } @@ -96,7 +96,7 @@ namespace NadekoBot //load commands and prefixes using (var uow = DbHandler.UnitOfWork()) { - ModulePrefixes = new ConcurrentDictionary(uow.BotConfig.GetOrCreate().ModulePrefixes.ToDictionary(m => m.ModuleName, m => m.Prefix)); + ModulePrefixes = new ConcurrentDictionary(uow.BotConfig.GetOrCreate().ModulePrefixes.OrderByDescending(mp => mp.Prefix.Length).ToDictionary(m => m.ModuleName, m => m.Prefix)); } // start handling messages received in commandhandler await CommandHandler.StartHandling().ConfigureAwait(false); diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 42d4e9d1..d46f1a66 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -71,6 +71,7 @@ namespace NadekoBot.Services if (guild != null && guild.OwnerId != msg.Author.Id) { + //todo split checks into their own modules if (Permissions.FilterCommands.InviteFilteringChannels.Contains(msg.Channel.Id) || Permissions.FilterCommands.InviteFilteringServers.Contains(guild.Id)) { @@ -133,6 +134,18 @@ namespace NadekoBot.Services } catch { } + string messageContent = usrMsg.Content; + foreach (var k in NadekoBot.ModulePrefixes.Values) + { + if (usrMsg.Content.ToLowerInvariant().StartsWith(k)) + { + messageContent = messageContent.Insert(k.Length, " "); + break; + } + + } + + var throwaway = Task.Run(async () => { var sw = new Stopwatch(); @@ -140,10 +153,10 @@ namespace NadekoBot.Services try { - var t = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), usrMsg.Content, DependencyMap.Empty, MultiMatchHandling.Best); - var command = t.Item1; - var permCache = t.Item2; - var result = t.Item3; + var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best); + var command = exec.CommandInfo; + var permCache = exec.PermissionCache; + var result = exec.Result; sw.Stop(); var channel = (msg.Channel as ITextChannel); if (result.IsSuccess) @@ -205,14 +218,17 @@ namespace NadekoBot.Services }); return; } + public Task ExecuteCommandAsync(CommandContext context, int argPos, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) + => ExecuteCommand(context, context.Message.Content.Substring(argPos), dependencyMap, multiMatchHandling); - public async Task> ExecuteCommand(CommandContext context, string input, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) + + public async Task ExecuteCommand(CommandContext context, string input, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) { dependencyMap = dependencyMap ?? DependencyMap.Empty; var searchResult = _commandService.Search(context, input); if (!searchResult.IsSuccess) - return new Tuple(null, null, searchResult); + return new ExecuteCommandResult(null, null, searchResult); var commands = searchResult.Commands; for (int i = commands.Count - 1; i >= 0; i--) @@ -221,7 +237,7 @@ namespace NadekoBot.Services if (!preconditionResult.IsSuccess) { if (commands.Count == 1) - return new Tuple(null, null, preconditionResult); + return new ExecuteCommandResult(null, null, preconditionResult); else continue; } @@ -245,7 +261,7 @@ namespace NadekoBot.Services if (!parseResult.IsSuccess) { if (commands.Count == 1) - return new Tuple(null, null, parseResult); + return new ExecuteCommandResult(null, null, parseResult); else continue; } @@ -273,7 +289,7 @@ namespace NadekoBot.Services if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(context.Message, cmd.Aliases.First(), cmd.Module.Name, out index)) { var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand((SocketGuild)context.Guild)}** is preventing this action."; - return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); + return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)); } @@ -281,19 +297,33 @@ namespace NadekoBot.Services { if (!((IGuildUser)context.User).GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant())) { - return new Tuple(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); + return new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")); } } } if (CmdCdsCommands.HasCooldown(cmd, context.Guild, context.User)) - return new Tuple(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); + return new ExecuteCommandResult(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); - return new Tuple(commands[i], null, await commands[i].Execute(context, parseResult, dependencyMap)); + return new ExecuteCommandResult(commands[i], null, await commands[i].Execute(context, parseResult, dependencyMap)); } - return new Tuple(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); + return new ExecuteCommandResult(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); + } + + public struct ExecuteCommandResult + { + public readonly CommandInfo CommandInfo; + public readonly PermissionCache PermissionCache; + public readonly IResult Result; + + public ExecuteCommandResult(CommandInfo commandInfo, PermissionCache cache, IResult result) + { + this.CommandInfo = commandInfo; + this.PermissionCache = cache; + this.Result = result; + } } } } diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 37ddc535..97692a5d 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -1,4 +1,5 @@ ๏ปฟusing Discord; +using Discord.Commands; using ImageSharp; using Newtonsoft.Json; using System; @@ -22,6 +23,16 @@ namespace NadekoBot.Extensions http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } + public static string GetPrefix(this ModuleInfo module) => NadekoBot.ModulePrefixes[module.GetTopLevelModule().Name]; + + public static ModuleInfo GetTopLevelModule(this ModuleInfo module) { + while (module.Parent != null) + { + module = module.Parent; + } + return module; + } + public static async Task SendMessageToOwnerAsync(this IGuild guild, string message) { var ownerPrivate = await (await guild.GetOwnerAsync().ConfigureAwait(false)).CreateDMChannelAsync() @@ -85,8 +96,8 @@ namespace NadekoBot.Extensions public static async Task SendErrorAsync(this IGuildUser user, string error) => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error)); - public static async Task SendFileAsync(this IGuildUser user, string filePath, string caption = null, bool isTTS = false) => - await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(filePath, caption, isTTS).ConfigureAwait(false); + public static async Task SendFileAsync(this IGuildUser user, string filePath, string caption = null, string text = null, bool isTTS = false) => + await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(File.Open(filePath, FileMode.Open), caption ?? "x", text, isTTS).ConfigureAwait(false); public static async Task SendFileAsync(this IGuildUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); From ed505a7809efce691e8d40664875309b9fcfb46f Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 21 Dec 2016 12:52:01 +0100 Subject: [PATCH 14/30] more work! --- NadekoBot.sln | 44 ++++-- .../Modules/Administration/Administration.cs | 19 +-- .../Modules/ClashOfClans/ClashOfClans.cs | 5 +- src/NadekoBot/Modules/DiscordModule.cs | 2 +- .../Gambling/Commands/DiceRollCommand.cs | 137 ++++++++++-------- .../Modules/Gambling/Commands/DrawCommand.cs | 1 - .../Gambling/Commands/FlipCoinCommand.cs | 12 +- .../Games/Commands/Hangman/HangmanGame.cs | 4 +- .../Games/Commands/PlantAndPickCommands.cs | 2 - .../Modules/Games/Commands/TriviaCommands.cs | 2 +- src/NadekoBot/Modules/Help/Help.cs | 4 +- .../Modules/Music/Classes/MusicControls.cs | 1 + src/NadekoBot/Modules/Music/Classes/Song.cs | 18 +-- .../Searches/Commands/OverwatchCommands.cs | 1 + .../Modules/Utility/Commands/CalcCommand.cs | 2 +- src/NadekoBot/Modules/Utility/Utility.cs | 20 ++- src/NadekoBot/Services/CommandHandler.cs | 16 +- src/NadekoBot/Services/CurrencyHandler.cs | 2 +- .../Services/Impl/GoogleApiService.cs | 3 +- src/NadekoBot/TypeReaders/ModuleTypeReader.cs | 3 +- src/NadekoBot/_Extensions/Extensions.cs | 16 +- 21 files changed, 174 insertions(+), 140 deletions(-) diff --git a/NadekoBot.sln b/NadekoBot.sln index 350bd395..3380667d 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -12,13 +12,17 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NadekoBot", "src\NadekoBot\NadekoBot.xproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "Discord.Net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net", "discord.net\src\Discord.Net\Discord.Net.xproj", "{91E9E7BD-75C9-4E98-84AA-2C271922E5C2}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "Discord.Net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{E5F4786F-58F3-469E-8C87-1908A95436B7}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "Discord.Net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{63F5B5C8-56FE-4B53-8003-B58CEB451EF9}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "Discord.Net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{8CBA56CD-A954-481E-8358-F36273757A6B}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rpc", "discord.net\src\Discord.Net.Rpc\Discord.Net.Rpc.xproj", "{0E741C78-869B-4E05-A300-0C5B32F07734}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "Discord.Net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -33,12 +37,18 @@ Global {45EC1473-C678-4857-A544-07DFE0D0B478}.GlobalNadeko|Any CPU.Build.0 = GlobalNadeko|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.ActiveCfg = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.Build.0 = Release|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.Build.0 = Release|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.ActiveCfg = Release|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.Build.0 = Release|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.Build.0 = Release|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.ActiveCfg = Release|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.Build.0 = Release|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.Build.0 = Release|Any CPU {E5F4786F-58F3-469E-8C87-1908A95436B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E5F4786F-58F3-469E-8C87-1908A95436B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {E5F4786F-58F3-469E-8C87-1908A95436B7}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU @@ -51,12 +61,18 @@ Global {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.Build.0 = Release|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CBA56CD-A954-481E-8358-F36273757A6B}.Release|Any CPU.Build.0 = Release|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0E741C78-869B-4E05-A300-0C5B32F07734}.Release|Any CPU.Build.0 = Release|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index a79b6fc3..8bf3901a 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -25,6 +25,8 @@ namespace NadekoBot.Modules.Administration private static ConcurrentDictionary GuildMuteRoles { get; } = new ConcurrentDictionary(); + private static ConcurrentHashSet DeleteMessagesOnCommand { get; } = new ConcurrentHashSet(); + private new static Logger _log { get; } public Administration() : base() @@ -36,6 +38,7 @@ namespace NadekoBot.Modules.Administration _log = LogManager.GetCurrentClassLogger(); NadekoBot.CommandHandler.CommandExecuted += DelMsgOnCmd_Handler; + DeleteMessagesOnCommand = new ConcurrentHashSet(NadekoBot.AllGuildConfigs.Where(g => g.DeleteMessageOnCommand).Select(g => g.GuildId)); } @@ -46,15 +49,7 @@ namespace NadekoBot.Modules.Administration var channel = msg.Channel as SocketTextChannel; if (channel == null) return; - - //todo cache this - bool shouldDelete; - using (var uow = DbHandler.UnitOfWork()) - { - shouldDelete = uow.GuildConfigs.For(channel.Guild.Id, set => set).DeleteMessageOnCommand; - } - - if (shouldDelete) + if (DeleteMessagesOnCommand.Contains(channel.Guild.Id)) await msg.DeleteAsync().ConfigureAwait(false); } catch (Exception ex) @@ -99,9 +94,15 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } if (enabled) + { + DeleteMessagesOnCommand.Add(Context.Guild.Id); await Context.Channel.SendConfirmAsync("โœ… **Now automatically deleting successful command invokations.**").ConfigureAwait(false); + } else + { + DeleteMessagesOnCommand.TryRemove(Context.Guild.Id); await Context.Channel.SendConfirmAsync("โ—**Stopped automatic deletion of successful command invokations.**").ConfigureAwait(false); + } } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 4ee08f4b..10840d81 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -38,9 +38,6 @@ namespace NadekoBot.Modules.ClashOfClans .ToDictionary(g => g.Key, g => g.ToList())); } } - public ClashOfClans() : base() - { - } private static async Task CheckWar(TimeSpan callExpire, ClashWar war) { @@ -52,7 +49,7 @@ namespace NadekoBot.Modules.ClashOfClans { Bases[i] = null; try { await war.Channel.SendErrorAsync($"โ—๐Ÿ”ฐ**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false); } catch { } - } + } } } diff --git a/src/NadekoBot/Modules/DiscordModule.cs b/src/NadekoBot/Modules/DiscordModule.cs index be453f43..711431d5 100644 --- a/src/NadekoBot/Modules/DiscordModule.cs +++ b/src/NadekoBot/Modules/DiscordModule.cs @@ -3,7 +3,7 @@ using NLog; namespace NadekoBot.Modules { - public class DiscordModule : ModuleBase + public abstract class DiscordModule : ModuleBase { protected Logger _log { get; } protected string _prefix { get; } diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index 217b74d2..a3148dab 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -21,6 +21,11 @@ namespace NadekoBot.Modules.Gambling { private Regex dndRegex { get; } = new Regex(@"^(?\d+)d(?\d+)(?:\+(?\d+))?(?:\-(?\d+))?$", RegexOptions.Compiled); + public enum RoleOrderType { + Ordered, + Unordered + } + [NadekoCommand, Usage, Description, Aliases] public async Task Roll() { @@ -43,37 +48,6 @@ namespace NadekoBot.Modules.Gambling await Context.Channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } - //todo merge into internallDndRoll and internalRoll - [NadekoCommand, Usage, Description, Aliases] - [Priority(1)] - public async Task Roll(string arg) - { - var ordered = true; - var rng = new NadekoRandom(); - Match match; - if ((match = dndRegex.Match(arg)).Length != 0) - { - int n1; - int n2; - if (int.TryParse(match.Groups["n1"].ToString(), out n1) && - int.TryParse(match.Groups["n2"].ToString(), out n2) && - n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) - { - var add = 0; - var sub = 0; - int.TryParse(match.Groups["add"].Value, out add); - int.TryParse(match.Groups["sub"].Value, out sub); - - var arr = new int[n1]; - for (int i = 0; i < n1; i++) - { - arr[i] = rng.Next(1, n2 + 1) + add - sub; - } - var elemCnt = 0; - await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); - } - } - } [NadekoCommand, Usage, Description, Aliases] [Priority(0)] @@ -123,37 +97,7 @@ namespace NadekoBot.Modules.Gambling ms.Position = 0; await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } - - [NadekoCommand, Usage, Description, Aliases] - public async Task Rolluo(string arg) - { - var ordered = false; - var rng = new NadekoRandom(); - Match match; - if ((match = dndRegex.Match(arg)).Length != 0) - { - int n1; - int n2; - if (int.TryParse(match.Groups["n1"].ToString(), out n1) && - int.TryParse(match.Groups["n2"].ToString(), out n2) && - n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) - { - var add = 0; - var sub = 0; - int.TryParse(match.Groups["add"].Value, out add); - int.TryParse(match.Groups["sub"].Value, out sub); - - var arr = new int[n1]; - for (int i = 0; i < n1; i++) - { - arr[i] = rng.Next(1, n2 + 1) + add - sub; - } - var elemCnt = 0; - await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); - } - } - } - + [NadekoCommand, Usage, Description, Aliases] public async Task Rolluo(int num) { @@ -202,6 +146,73 @@ namespace NadekoBot.Modules.Gambling await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } + //todo merge into internallDndRoll and internalRoll + [NadekoCommand, Usage, Description, Aliases] + [Priority(1)] + public async Task Roll(string arg) + { + + } + + [NadekoCommand, Usage, Description, Aliases] + public async Task Rolluo(string arg) + { + var ordered = false; + var rng = new NadekoRandom(); + Match match; + if ((match = dndRegex.Match(arg)).Length != 0) + { + int n1; + int n2; + if (int.TryParse(match.Groups["n1"].ToString(), out n1) && + int.TryParse(match.Groups["n2"].ToString(), out n2) && + n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) + { + var add = 0; + var sub = 0; + int.TryParse(match.Groups["add"].Value, out add); + int.TryParse(match.Groups["sub"].Value, out sub); + + var arr = new int[n1]; + for (int i = 0; i < n1; i++) + { + arr[i] = rng.Next(1, n2 + 1) + add - sub; + } + var elemCnt = 0; + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + } + } + } + + private async Task InternalDndRoll(string arg, RoleOrderType ordType) + { + var ordered = ordType == RoleOrderType.Ordered; + var rng = new NadekoRandom(); + Match match; + if ((match = dndRegex.Match(arg)).Length != 0) + { + int n1; + int n2; + if (int.TryParse(match.Groups["n1"].ToString(), out n1) && + int.TryParse(match.Groups["n2"].ToString(), out n2) && + n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) + { + var add = 0; + var sub = 0; + int.TryParse(match.Groups["add"].Value, out add); + int.TryParse(match.Groups["sub"].Value, out sub); + + var arr = new int[n1]; + for (int i = 0; i < n1; i++) + { + arr[i] = rng.Next(1, n2 + 1) + add - sub; + } + var elemCnt = 0; + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); + } + } + } + [NadekoCommand, Usage, Description, Aliases] public async Task NRoll([Remainder] string range) { @@ -215,7 +226,7 @@ namespace NadekoBot.Modules.Gambling .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) - throw new ArgumentException("First argument should be bigger than the second one."); + throw new ArgumentException("Second argument must be larger than the first one."); rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index abece27e..a57a4872 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -53,7 +53,6 @@ namespace NadekoBot.Modules.Gambling MemoryStream bitmapStream = new MemoryStream(); images.Merge().SaveAsPng(bitmapStream); bitmapStream.Position = 0; - //todo CARD NAMES? var toSend = $"{Context.User.Mention}"; if (cardObjects.Count == 5) toSend += $" drew `{Cards.GetHandValue(cardObjects)}`"; diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index fc6c60a6..e1c05a05 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -64,16 +64,10 @@ namespace NadekoBot.Modules.Gambling .ConfigureAwait(false); return; } - // todo update this - long userFlowers; - using (var uow = DbHandler.UnitOfWork()) + var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, "Betflip Gamble", amount, false).ConfigureAwait(false); + if (!removed) { - userFlowers = uow.Currency.GetOrCreate(Context.User.Id).Amount; - } - - if (userFlowers < amount) - { - await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); return; } diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index cd5b8a70..c2a93f63 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -143,9 +143,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman return Task.CompletedTask; var guess = char.ToUpperInvariant(msg.Content[0]); - // todo hmmmm - // how do i want to limit the users on guessing? - // one guess every 5 seconds if wrong? + Task.Run(async () => { try diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 04e43058..88bcc91e 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -16,8 +16,6 @@ using System.Threading.Tasks; namespace NadekoBot.Modules.Games { - //todo make currency generation change and cooldown modifyable - //only by bot owner through commands public partial class Games { /// diff --git a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs index dfa55eea..90492643 100644 --- a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs @@ -8,7 +8,7 @@ using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; -//todo Rewrite? Fix trivia not stopping bug + namespace NadekoBot.Modules.Games { public partial class Games diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 16fb59f3..53ae37d7 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -38,9 +38,9 @@ namespace NadekoBot.Modules.Help public async Task Modules() { + var mdls = NadekoBot.CommandService.Modules.GroupBy(mi => mi.GetTopLevelModule()).Select(m => m.Key.Name).OrderBy(m => m); await Context.Channel.SendMessageAsync("๐Ÿ“œ **List of modules:** ```css\nโ€ข " + string.Join("\nโ€ข ", - NadekoBot.CommandService.Modules.GroupBy(mi => mi.GetTopLevelModule()).Select(m => m.Key.Name).OrderBy(m => m)) + - $"\n``` โ„น๏ธ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") + mdls) + $"\n``` โ„น๏ธ **Type** `-commands module_name` **to get a list of commands in that module.** ***e.g.*** `-commands games`") .ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Music/Classes/MusicControls.cs b/src/NadekoBot/Modules/Music/Classes/MusicControls.cs index 8555d3a3..dea84b09 100644 --- a/src/NadekoBot/Modules/Music/Classes/MusicControls.cs +++ b/src/NadekoBot/Modules/Music/Classes/MusicControls.cs @@ -130,6 +130,7 @@ namespace NadekoBot.Modules.Music.Classes { Console.WriteLine("Music thread almost crashed."); Console.WriteLine(ex); + await Task.Delay(30000); } finally { diff --git a/src/NadekoBot/Modules/Music/Classes/Song.cs b/src/NadekoBot/Modules/Music/Classes/Song.cs index 2623f680..379d8caf 100644 --- a/src/NadekoBot/Modules/Music/Classes/Song.cs +++ b/src/NadekoBot/Modules/Music/Classes/Song.cs @@ -24,22 +24,22 @@ namespace NadekoBot.Modules.Music.Classes public string Query { get; set; } public string Title { get; set; } public string Uri { get; set; } - public string AlbumArt { get; set; } + public string AlbumArt { get; set; } } public class Song { - public StreamState State { get; set; } + public StreamState State { get; set; } public string PrettyName => $"**{SongInfo.Title.TrimTo(55)} `{(SongInfo.Provider ?? "-")} by {QueuerName}`**"; - //$"{SongInfo.Title.TrimTo(70)}"; + //$"{SongInfo.Title.TrimTo(70)}"; public SongInfo SongInfo { get; } public MusicPlayer MusicPlayer { get; set; } - - public string PrettyUser => + + public string PrettyUser => $"{QueuerName}"; public string QueuerName { get; set; } - - public string PrettyProvider => + + public string PrettyProvider => $"{(SongInfo.Provider ?? "No Provider")}"; public string PrettyCurrentTime() @@ -320,7 +320,7 @@ namespace NadekoBot.Modules.Music.Classes Uri = svideo.StreamLink, ProviderType = musicType, Query = svideo.TrackLink, - AlbumArt = svideo.artwork_url, + AlbumArt = svideo.artwork_url, }) { TotalLength = TimeSpan.FromMilliseconds(svideo.Duration) }; } @@ -335,7 +335,7 @@ namespace NadekoBot.Modules.Music.Classes Uri = svideo.StreamLink, ProviderType = MusicType.Normal, Query = svideo.TrackLink, - AlbumArt = svideo.artwork_url, + AlbumArt = svideo.artwork_url, }) { TotalLength = TimeSpan.FromMilliseconds(svideo.Duration) }; } diff --git a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs index 258bad9b..0b309e12 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs @@ -23,6 +23,7 @@ namespace NadekoBot.Modules.Searches var battletag = query.Replace("#", "-"); try { + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); var model = await GetProfile(region, battletag); var rankimg = $"{model.Competitive.rank_img}"; diff --git a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs index b0135fd0..b4327c85 100644 --- a/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs +++ b/src/NadekoBot/Modules/Utility/Commands/CalcCommand.cs @@ -50,7 +50,7 @@ namespace NadekoBot.Modules.Utility "Equals", "GetHashCode", "GetType"}); - await Context.Channel.SendConfirmAsync(string.Join(", ", selection)); + await Context.Channel.SendConfirmAsync("Available functions in calc", string.Join(", ", selection)); } } diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index d24d51a0..2b976ac6 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -125,11 +125,27 @@ namespace NadekoBot.Modules.Utility return; if (target != null) { - await channel.SendConfirmAsync($"โš” **Page #{page} of roles for {target.Username}**", $"```css\nโ€ข " + string.Join("\nโ€ข ", target.GetRoles().Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); + var roles = target.GetRoles().Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage); + if (!roles.Any()) + { + await channel.SendErrorAsync("No roles on this page."); + } + else + { + await channel.SendConfirmAsync($"โš” **Page #{page} of roles for {target.Username}**", $"```css\nโ€ข " + string.Join("\nโ€ข ", roles).SanitizeMentions() + "\n```"); + } } else { - await channel.SendConfirmAsync($"โš” **Page #{page} of all roles on this server:**", $"```css\nโ€ข " + string.Join("\nโ€ข ", guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage)).SanitizeMentions() + "\n```"); + var roles = guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * RolesPerPage).Take(RolesPerPage); + if (!roles.Any()) + { + await channel.SendErrorAsync("No roles on this page."); + } + else + { + await channel.SendConfirmAsync($"โš” **Page #{page} of all roles on this server:**", $"```css\nโ€ข " + string.Join("\nโ€ข ", roles).SanitizeMentions() + "\n```"); + } } } diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index d46f1a66..463d257e 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -135,15 +135,15 @@ namespace NadekoBot.Services catch { } string messageContent = usrMsg.Content; - foreach (var k in NadekoBot.ModulePrefixes.Values) - { - if (usrMsg.Content.ToLowerInvariant().StartsWith(k)) - { - messageContent = messageContent.Insert(k.Length, " "); - break; - } + //foreach (var k in NadekoBot.ModulePrefixes.Values) + //{ + // if (usrMsg.Content.ToLowerInvariant().StartsWith(k)) + // { + // messageContent = messageContent.Insert(k.Length, " "); + // break; + // } - } + //} var throwaway = Task.Run(async () => diff --git a/src/NadekoBot/Services/CurrencyHandler.cs b/src/NadekoBot/Services/CurrencyHandler.cs index 45383968..fb8d68a6 100644 --- a/src/NadekoBot/Services/CurrencyHandler.cs +++ b/src/NadekoBot/Services/CurrencyHandler.cs @@ -9,7 +9,7 @@ namespace NadekoBot.Services { public static class CurrencyHandler { - public static async Task RemoveCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage) + public static async Task RemoveCurrencyAsync(IUser author, string reason, long amount, bool sendMessage) { var success = await RemoveCurrencyAsync(author.Id, reason, amount); diff --git a/src/NadekoBot/Services/Impl/GoogleApiService.cs b/src/NadekoBot/Services/Impl/GoogleApiService.cs index 6a18c686..6e5727f7 100644 --- a/src/NadekoBot/Services/Impl/GoogleApiService.cs +++ b/src/NadekoBot/Services/Impl/GoogleApiService.cs @@ -167,7 +167,8 @@ namespace NadekoBot.Services.Impl remaining -= toGet; var q = yt.Videos.List("contentDetails"); - q.Id = string.Join(",", videoIds); + q.Id = string.Join(",", videoIdsList.Take(toGet)); + videoIdsList = videoIdsList.Skip(toGet).ToList(); var items = (await q.ExecuteAsync().ConfigureAwait(false)).Items; foreach (var i in items) { diff --git a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs index 1cfd4204..3363c83e 100644 --- a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs @@ -1,4 +1,5 @@ ๏ปฟusing Discord.Commands; +using NadekoBot.Extensions; using System.Linq; using System.Threading.Tasks; @@ -9,7 +10,7 @@ namespace NadekoBot.TypeReaders public override Task Read(CommandContext context, string input) { input = input.ToUpperInvariant(); - var module = NadekoBot.CommandService.Modules.FirstOrDefault(m => m.Name.ToUpperInvariant() == input); + var module = NadekoBot.CommandService.Modules.GroupBy(m => m.GetTopLevelModule()).FirstOrDefault(m => m.Key.Name.ToUpperInvariant() == input); if (module == null) return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "No such module found.")); diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index 97692a5d..284b72ba 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -79,34 +79,34 @@ namespace NadekoBot.Extensions public static double UnixTimestamp(this DateTime dt) => dt.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds; - public static async Task SendMessageAsync(this IGuildUser user, string message, bool isTTS = false) => + public static async Task SendMessageAsync(this IUser user, string message, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(message, isTTS).ConfigureAwait(false); - public static async Task SendConfirmAsync(this IGuildUser user, string text) + public static async Task SendConfirmAsync(this IUser user, string text) => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text)); - public static async Task SendConfirmAsync(this IGuildUser user, string title, string text, string url = null) + public static async Task SendConfirmAsync(this IUser user, string title, string text, string url = null) => await(await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text) .WithTitle(title).WithUrl(url)); - public static async Task SendErrorAsync(this IGuildUser user, string title, string error, string url = null) + public static async Task SendErrorAsync(this IUser user, string title, string error, string url = null) => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error) .WithTitle(title).WithUrl(url)); - public static async Task SendErrorAsync(this IGuildUser user, string error) + public static async Task SendErrorAsync(this IUser user, string error) => await (await user.CreateDMChannelAsync()).SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error)); - public static async Task SendFileAsync(this IGuildUser user, string filePath, string caption = null, string text = null, bool isTTS = false) => + public static async Task SendFileAsync(this IUser user, string filePath, string caption = null, string text = null, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(File.Open(filePath, FileMode.Open), caption ?? "x", text, isTTS).ConfigureAwait(false); - public static async Task SendFileAsync(this IGuildUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => + public static async Task SendFileAsync(this IUser user, Stream fileStream, string fileName, string caption = null, bool isTTS = false) => await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendFileAsync(fileStream, fileName, caption, isTTS).ConfigureAwait(false); public static bool IsAuthor(this IUserMessage msg) => NadekoBot.Client.CurrentUser().Id == msg.Author.Id; public static IEnumerable Members(this IRole role) => - role.Guild.GetUsersAsync().GetAwaiter().GetResult() ?? Enumerable.Empty(); + role.Guild.GetUsersAsync().GetAwaiter().GetResult().Where(u => u.RoleIds.Contains(role.Id)) ?? Enumerable.Empty(); public static Task EmbedAsync(this IMessageChannel ch, EmbedBuilder embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); From 1d2e44c7bed7b54a56537d2954caed325afe98a8 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 21 Dec 2016 13:14:24 +0100 Subject: [PATCH 15/30] Music format --- src/NadekoBot/Modules/Music/Music.cs | 123 ++++++++++++++------------- 1 file changed, 65 insertions(+), 58 deletions(-) diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index a536f181..24e0e476 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -15,6 +15,7 @@ using Newtonsoft.Json.Linq; using System.Collections.Generic; using NadekoBot.Services.Database.Models; using System.Text.RegularExpressions; +using System.Threading; namespace NadekoBot.Modules.Music { @@ -30,13 +31,13 @@ namespace NadekoBot.Modules.Music { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } - - NadekoBot.Client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated; + + NadekoBot.Client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated; Directory.CreateDirectory(MusicDataPath); } - - private async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) + + private async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) { var usr = iusr as SocketGuildUser; if (usr == null || @@ -100,7 +101,7 @@ namespace NadekoBot.Modules.Music MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return Task.CompletedTask; if (((IGuildUser)Context.User).VoiceChannel == musicPlayer.PlaybackVoiceChannel) - if(MusicPlayers.TryRemove(Context.Guild.Id, out musicPlayer)) + if (MusicPlayers.TryRemove(Context.Guild.Id, out musicPlayer)) musicPlayer.Destroy(); return Task.CompletedTask; } @@ -145,7 +146,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task ListQueue(int page = 1) { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) { @@ -165,7 +166,7 @@ namespace NadekoBot.Modules.Music } //var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName} " + $"`{currentSong.PrettyCurrentTime()}`\n"; - var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName}\n"; + var toSend = $"๐ŸŽต Currently Playing {currentSong.PrettyName}\n"; if (musicPlayer.RepeatSong) toSend += "๐Ÿ”‚"; else if (musicPlayer.RepeatPlaylist) @@ -191,28 +192,28 @@ namespace NadekoBot.Modules.Music var currentSong = musicPlayer.CurrentSong; if (currentSong == null) return; - var videoid = Regex.Match(currentSong.SongInfo.Query, "<=v=[a-zA-Z0-9-]+(?=&)|(?<=[0-9])[^&\n]+|(?<=v=)[^&\n]+"); + var videoid = Regex.Match(currentSong.SongInfo.Query, "<=v=[a-zA-Z0-9-]+(?=&)|(?<=[0-9])[^&\n]+|(?<=v=)[^&\n]+"); if (currentSong.TotalLength == TimeSpan.Zero) { await musicPlayer.UpdateSongDurationsAsync().ConfigureAwait(false); } - var embed = new EmbedBuilder() - .WithAuthor(eab => eab.WithName("Now Playing").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) - .WithTitle($"{currentSong.SongInfo.Title}") - .WithUrl($"{currentSong.SongInfo.Query}") - .WithDescription($"{currentSong.PrettyCurrentTime()}") - .WithFooter(ef => ef.WithText($"{currentSong.PrettyProvider} | {currentSong.PrettyUser}")) - .WithColor(NadekoBot.OkColor); - if (currentSong.SongInfo.Provider.Equals("YouTube", StringComparison.OrdinalIgnoreCase)) - { + var embed = new EmbedBuilder() + .WithAuthor(eab => eab.WithName("Now Playing").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) + .WithTitle($"{currentSong.SongInfo.Title}") + .WithUrl($"{currentSong.SongInfo.Query}") + .WithDescription($"{currentSong.PrettyCurrentTime()}") + .WithFooter(ef => ef.WithText($"{currentSong.PrettyProvider} | {currentSong.PrettyUser}")) + .WithColor(NadekoBot.OkColor); + if (currentSong.SongInfo.Provider.Equals("YouTube", StringComparison.OrdinalIgnoreCase)) + { embed.WithThumbnailUrl($"https://img.youtube.com/vi/{videoid}/0.jpg"); - } - else if (currentSong.SongInfo.Provider.Equals("SoundCloud", StringComparison.OrdinalIgnoreCase)) - { + } + else if (currentSong.SongInfo.Provider.Equals("SoundCloud", StringComparison.OrdinalIgnoreCase)) + { embed.WithThumbnailUrl($"{currentSong.SongInfo.AlbumArt}"); - } - await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); + } + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -234,7 +235,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Defvol([Remainder] int val) { - + if (val < 0 || val > 100) { @@ -253,7 +254,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task ShufflePlaylist() { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; @@ -273,7 +274,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Playlist([Remainder] string playlist) { - + var arg = playlist; if (string.IsNullOrWhiteSpace(arg)) return; @@ -298,15 +299,22 @@ namespace NadekoBot.Modules.Music var count = idArray.Length; var msg = await Context.Channel.SendMessageAsync($"๐ŸŽต Attempting to queue **{count}** songs".SnPl(count) + "...").ConfigureAwait(false); - foreach (var id in idArray) + var cancelSource = new CancellationTokenSource(); + + var tasks = Task.WhenAll(idArray.Select(async id => { + if (cancelSource.Token.IsCancellationRequested) + return; try { await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, id, true).ConfigureAwait(false); } catch (SongNotFoundException) { } - catch { break; } - } + catch { try { cancelSource.Cancel(); } catch { } } + })); + + await Task.WhenAny(tasks, Task.Delay(Timeout.Infinite, cancelSource.Token)); + await msg.ModifyAsync(m => m.Content = "โœ… Playlist queue complete.").ConfigureAwait(false); } @@ -314,7 +322,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task SoundCloudPl([Remainder] string pl) { - + pl = pl?.Trim(); if (string.IsNullOrWhiteSpace(pl)) @@ -352,7 +360,7 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task LocalPl([Remainder] string directory) { - + var arg = directory; if (string.IsNullOrWhiteSpace(arg)) return; @@ -382,7 +390,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Radio(string radio_link) { - + if (((IGuildUser)Context.User).VoiceChannel?.Guild != Context.Guild) { await Context.Channel.SendErrorAsync("๐Ÿ’ข You need to be in a voice channel on this server.\n If you are already in a voice (ITextChannel)Context.Channel, try rejoining it.").ConfigureAwait(false); @@ -401,7 +409,7 @@ namespace NadekoBot.Modules.Music [OwnerOnly] public async Task Local([Remainder] string path) { - + var arg = path; if (string.IsNullOrWhiteSpace(arg)) return; @@ -413,7 +421,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Move() { - + MusicPlayer musicPlayer; var voiceChannel = ((IGuildUser)Context.User).VoiceChannel; if (voiceChannel == null || voiceChannel.Guild != Context.Guild || !MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) @@ -426,7 +434,7 @@ namespace NadekoBot.Modules.Music [Priority(0)] public async Task Remove(int num) { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) @@ -447,7 +455,7 @@ namespace NadekoBot.Modules.Music [Priority(1)] public async Task Remove(string all) { - + if (all.Trim().ToUpperInvariant() != "ALL") return; @@ -520,7 +528,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task ReptCurSong() { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; @@ -538,7 +546,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task RepeatPl() { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; @@ -550,14 +558,15 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Save([Remainder] string name) { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; var curSong = musicPlayer.CurrentSong; var songs = musicPlayer.Playlist.Append(curSong) - .Select(s=> new PlaylistSong() { + .Select(s => new PlaylistSong() + { Provider = s.SongInfo.Provider, ProviderType = s.SongInfo.ProviderType, Title = s.SongInfo.Title, @@ -617,7 +626,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Playlists([Remainder] int num = 1) { - + if (num <= 0) return; @@ -639,7 +648,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task DeletePlaylist([Remainder] int id) { - + bool success = false; MusicPlaylist pl = null; @@ -677,8 +686,6 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Goto(int time) { - - MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; @@ -714,7 +721,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task GetLink(int index = 0) { - + MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) return; @@ -779,7 +786,7 @@ namespace NadekoBot.Modules.Music } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; - IUserMessage lastFinishedMessage = null; + IUserMessage lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { if (song.PrintStatusMessage) @@ -807,21 +814,21 @@ namespace NadekoBot.Modules.Music if (sender == null) return; - var msgTxt = $"๐ŸŽต Playing {song.PrettyName}\t `Vol: {(int)(sender.Volume * 100)}%`"; + var msgTxt = $"๐ŸŽต Playing {song.PrettyName}\t `Vol: {(int)(sender.Volume * 100)}%`"; try { playingMessage = await textCh.SendConfirmAsync(msgTxt).ConfigureAwait(false); } catch { } } }; - mp.OnPauseChanged += async (paused) => - { - try - { - if (paused) - await textCh.SendConfirmAsync("๐ŸŽต Music playback **paused**.").ConfigureAwait(false); - else - await textCh.SendConfirmAsync("๐ŸŽต Music playback **resumed**.").ConfigureAwait(false); - } - catch { } - }; + mp.OnPauseChanged += async (paused) => + { + try + { + if (paused) + await textCh.SendConfirmAsync("๐ŸŽต Music playback **paused**.").ConfigureAwait(false); + else + await textCh.SendConfirmAsync("๐ŸŽต Music playback **resumed**.").ConfigureAwait(false); + } + catch { } + }; return mp; }); Song resolvedSong; @@ -850,7 +857,7 @@ namespace NadekoBot.Modules.Music try { await Task.Delay(10000).ConfigureAwait(false); - + await queuedMessage.DeleteAsync().ConfigureAwait(false); } catch { } From 67888103f80203f8f181ca945644f1003c3a13b9 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 21 Dec 2016 23:26:59 +0100 Subject: [PATCH 16/30] coc fix --- NadekoBot.sln | 6 +- .../Modules/ClashOfClans/ClashOfClans.cs | 35 +++++++- .../Gambling/Commands/DiceRollCommand.cs | 80 +++---------------- 3 files changed, 43 insertions(+), 78 deletions(-) diff --git a/NadekoBot.sln b/NadekoBot.sln index 3380667d..4624958a 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -16,13 +16,13 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net", "discord.net\ EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "Discord.Net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{E5F4786F-58F3-469E-8C87-1908A95436B7}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "discord.net\src\Discord.Net.Core\Discord.Net.Core.xproj", "{E5F4786F-58F3-469E-8C87-1908A95436B7}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "Discord.Net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{63F5B5C8-56FE-4B53-8003-B58CEB451EF9}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "discord.net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{63F5B5C8-56FE-4B53-8003-B58CEB451EF9}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rpc", "discord.net\src\Discord.Net.Rpc\Discord.Net.Rpc.xproj", "{0E741C78-869B-4E05-A300-0C5B32F07734}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "Discord.Net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "discord.net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index 10840d81..eec973fd 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -10,6 +10,7 @@ using NadekoBot.Attributes; using NadekoBot.Services.Database.Models; using System.Linq; using NadekoBot.Extensions; +using System.Threading; namespace NadekoBot.Modules.ClashOfClans { @@ -18,6 +19,8 @@ namespace NadekoBot.Modules.ClashOfClans { public static ConcurrentDictionary> ClashWars { get; set; } = new ConcurrentDictionary>(); + private static Timer checkWarTimer { get; } + static ClashOfClans() { using (var uow = DbHandler.UnitOfWork()) @@ -37,6 +40,21 @@ namespace NadekoBot.Modules.ClashOfClans .GroupBy(cw => cw.GuildId) .ToDictionary(g => g.Key, g => g.ToList())); } + + checkWarTimer = new Timer(async _ => + { + foreach (var kvp in ClashWars) + { + foreach (var war in kvp.Value) + { + try { await CheckWar(TimeSpan.FromHours(2), war).ConfigureAwait(false); } catch { } + } + } + }, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); + } + public ClashOfClans() : base() + { + } private static async Task CheckWar(TimeSpan callExpire, ClashWar war) @@ -44,11 +62,20 @@ namespace NadekoBot.Modules.ClashOfClans var Bases = war.Bases; for (var i = 0; i < Bases.Count; i++) { - if (Bases[i].CallUser == null) continue; - if (!Bases[i].BaseDestroyed && DateTime.UtcNow - Bases[i].TimeAdded >= callExpire) + var callUser = Bases[i].CallUser; + if (callUser == null) continue; + if ((!Bases[i].BaseDestroyed) && DateTime.UtcNow - Bases[i].TimeAdded >= callExpire) { - Bases[i] = null; - try { await war.Channel.SendErrorAsync($"โ—๐Ÿ”ฐ**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false); } catch { } + if (Bases[i].Stars != 3) + Bases[i].BaseDestroyed = true; + else + Bases[i] = null; + try + { + SaveWar(war); + await war.Channel.SendErrorAsync($"โ—๐Ÿ”ฐ**Claim from @{Bases[i].CallUser} for a war against {war.ShortPrint()} has expired.**").ConfigureAwait(false); + } + catch { } } } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index a3148dab..015dd851 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -53,56 +53,19 @@ namespace NadekoBot.Modules.Gambling [Priority(0)] public async Task Roll(int num) { - var ordered = true; - - if (num < 1 || num > 30) - { - await Context.Channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); - return; - } - - var rng = new NadekoRandom(); - - var dice = new List(num); - var values = new List(num); - for (var i = 0; i < num; i++) - { - var randomNumber = rng.Next(1, 7); - var toInsert = dice.Count; - if (ordered) - { - if (randomNumber == 6 || dice.Count == 0) - toInsert = 0; - else if (randomNumber != 1) - for (var j = 0; j < dice.Count; j++) - { - if (values[j] < randomNumber) - { - toInsert = j; - break; - } - } - } - else - { - toInsert = dice.Count; - } - dice.Insert(toInsert, GetDice(randomNumber)); - values.Insert(toInsert, randomNumber); - } - - var bitmap = dice.Merge(); - var ms = new MemoryStream(); - bitmap.SaveAsPng(ms); - ms.Position = 0; - await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await InternalRoll(num, RoleOrderType.Ordered).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task Rolluo(int num) { - var ordered = false; + await InternalRoll(num, RoleOrderType.Unordered).ConfigureAwait(false); + } + + private async Task InternalRoll(int num, RoleOrderType ordType) + { + var ordered = ordType == RoleOrderType.Ordered; if (num < 1 || num > 30) { await Context.Channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); @@ -146,42 +109,17 @@ namespace NadekoBot.Modules.Gambling await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } - //todo merge into internallDndRoll and internalRoll [NadekoCommand, Usage, Description, Aliases] [Priority(1)] public async Task Roll(string arg) { - + await InternalDndRoll(arg, RoleOrderType.Ordered).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] public async Task Rolluo(string arg) { - var ordered = false; - var rng = new NadekoRandom(); - Match match; - if ((match = dndRegex.Match(arg)).Length != 0) - { - int n1; - int n2; - if (int.TryParse(match.Groups["n1"].ToString(), out n1) && - int.TryParse(match.Groups["n2"].ToString(), out n2) && - n1 <= 50 && n2 <= 100000 && n1 > 0 && n2 > 0) - { - var add = 0; - var sub = 0; - int.TryParse(match.Groups["add"].Value, out add); - int.TryParse(match.Groups["sub"].Value, out sub); - - var arr = new int[n1]; - for (int i = 0; i < n1; i++) - { - arr[i] = rng.Next(1, n2 + 1) + add - sub; - } - var elemCnt = 0; - await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`.\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false); - } - } + await InternalDndRoll(arg, RoleOrderType.Unordered).ConfigureAwait(false); } private async Task InternalDndRoll(string arg, RoleOrderType ordType) From f0a40233b02aab7151afcd62d500860606e1cfda Mon Sep 17 00:00:00 2001 From: Kwoth Date: Wed, 21 Dec 2016 23:31:34 +0100 Subject: [PATCH 17/30] updated discord.net --- Discord.Net | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Discord.Net b/Discord.Net index c102f52b..afe76860 160000 --- a/Discord.Net +++ b/Discord.Net @@ -1 +1 @@ -Subproject commit c102f52bfa1a6fd6ffbbd7c7f65d07342e8b6851 +Subproject commit afe768601f4e1322f34915d5c162acf47d0f6350 From 99e3a91e46589e57be5acfcbf5a7de55132bb42e Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 31 Dec 2016 12:04:30 +0100 Subject: [PATCH 18/30] discord.net submodule added --- .gitmodules | 4 ++-- Discord.Net | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) create mode 160000 Discord.Net diff --git a/.gitmodules b/.gitmodules index 08cf3841..38614ef7 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,4 +1,4 @@ [submodule "Discord.Net"] path = Discord.Net - url = https://github.com/Kwoth/Discord.Net - branch = rogue-dev + url = https://github.com/RogueException/Discord.Net + branch = dev diff --git a/Discord.Net b/Discord.Net new file mode 160000 index 00000000..ae614b68 --- /dev/null +++ b/Discord.Net @@ -0,0 +1 @@ +Subproject commit ae614b68b336941bf780b5f3c74bf7f6ea505316 From 48fcc4c923aea529f27fc0727b0d08a515e55d47 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 31 Dec 2016 13:21:18 +0100 Subject: [PATCH 19/30] Fixed preconditions and some other stuff --- Discord.Net | 2 +- NadekoBot.sln | 26 ++-- .../Attributes/OwnerOnlyAttribute.cs | 2 +- .../Modules/Administration/Administration.cs | 7 +- .../Commands/AutoAssignRoleCommands.cs | 4 +- .../Administration/Commands/LogCommand.cs | 8 +- .../Commands/VoicePlusTextCommands.cs | 63 ++++---- .../CustomReactions/CustomReactions.cs | 1 + .../Gambling/Commands/DiceRollCommand.cs | 5 +- .../Games/Commands/CleverBotCommands.cs | 3 + .../Modules/Games/Commands/PollCommands.cs | 77 +++++----- src/NadekoBot/Modules/Music/Music.cs | 117 ++++++++------- .../Searches/Commands/OverwatchCommands.cs | 3 +- src/NadekoBot/Modules/Searches/Searches.cs | 16 +- src/NadekoBot/Modules/Utility/Utility.cs | 7 +- src/NadekoBot/Services/CommandHandler.cs | 140 ++++++++---------- src/NadekoBot/ShardedDiscordClient.cs | 30 ++-- .../TypeReaders/BotCommandTypeReader.cs | 2 +- src/NadekoBot/TypeReaders/GuildTypeReader.cs | 2 +- src/NadekoBot/TypeReaders/ModuleTypeReader.cs | 2 +- .../TypeReaders/PermissionActionTypeReader.cs | 2 +- src/NadekoBot/_Extensions/Extensions.cs | 15 +- src/NadekoBot/project.json | 1 + 23 files changed, 260 insertions(+), 275 deletions(-) diff --git a/Discord.Net b/Discord.Net index ae614b68..cfc82740 160000 --- a/Discord.Net +++ b/Discord.Net @@ -1 +1 @@ -Subproject commit ae614b68b336941bf780b5f3c74bf7f6ea505316 +Subproject commit cfc827404af535b1e09d725284671b111fe85b93 diff --git a/NadekoBot.sln b/NadekoBot.sln index b512fa21..e0ebea17 100644 --- a/NadekoBot.sln +++ b/NadekoBot.sln @@ -12,7 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "NadekoBot", "src\NadekoBot\NadekoBot.xproj", "{45EC1473-C678-4857-A544-07DFE0D0B478}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net", "discord.net\src\Discord.Net\Discord.Net.xproj", "{91E9E7BD-75C9-4E98-84AA-2C271922E5C2}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.API", "discord.net\src\Discord.Net.API\Discord.Net.API.xproj", "{834C70DF-1230-4AAA-9C13-48AB232E8D76}" EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Commands", "discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj", "{078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}" EndProject @@ -20,8 +20,6 @@ Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Core", "discord EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rest", "discord.net\src\Discord.Net.Rest\Discord.Net.Rest.xproj", "{63F5B5C8-56FE-4B53-8003-B58CEB451EF9}" EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.Rpc", "discord.net\src\Discord.Net.Rpc\Discord.Net.Rpc.xproj", "{0E741C78-869B-4E05-A300-0C5B32F07734}" -EndProject Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "Discord.Net.WebSocket", "discord.net\src\Discord.Net.WebSocket\Discord.Net.WebSocket.xproj", "{E9800F7A-3354-41B1-BDBB-2D59F8124EC9}" EndProject Global @@ -37,16 +35,16 @@ Global {45EC1473-C678-4857-A544-07DFE0D0B478}.GlobalNadeko|Any CPU.Build.0 = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.ActiveCfg = Release|Any CPU {45EC1473-C678-4857-A544-07DFE0D0B478}.Release|Any CPU.Build.0 = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.ActiveCfg = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.GlobalNadeko|Any CPU.Build.0 = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {91E9E7BD-75C9-4E98-84AA-2C271922E5C2}.Release|Any CPU.Build.0 = Release|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.Debug|Any CPU.Build.0 = Debug|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.Release|Any CPU.ActiveCfg = Release|Any CPU + {834C70DF-1230-4AAA-9C13-48AB232E8D76}.Release|Any CPU.Build.0 = Release|Any CPU {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.ActiveCfg = Release|Any CPU - {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.Build.0 = Release|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU + {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.ActiveCfg = Release|Any CPU {078DD7E6-943D-4D09-AFC2-D2BA58B76C9C}.Release|Any CPU.Build.0 = Release|Any CPU {E5F4786F-58F3-469E-8C87-1908A95436B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -61,12 +59,6 @@ Global {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU {63F5B5C8-56FE-4B53-8003-B58CEB451EF9}.Release|Any CPU.Build.0 = Release|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.GlobalNadeko|Any CPU.Build.0 = Debug|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0E741C78-869B-4E05-A300-0C5B32F07734}.Release|Any CPU.Build.0 = Release|Any CPU {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9800F7A-3354-41B1-BDBB-2D59F8124EC9}.GlobalNadeko|Any CPU.ActiveCfg = Debug|Any CPU diff --git a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs index 70432527..410a24af 100644 --- a/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs +++ b/src/NadekoBot/Attributes/OwnerOnlyAttribute.cs @@ -5,7 +5,7 @@ namespace NadekoBot.Attributes { public class OwnerOnlyAttribute : PreconditionAttribute { - public override Task CheckPermissions(CommandContext context, CommandInfo executingCommand,IDependencyMap depMap) => + public override Task CheckPermissions(ICommandContext context, CommandInfo executingCommand,IDependencyMap depMap) => Task.FromResult((NadekoBot.Credentials.IsOwner(context.User) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner"))); } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index ed2ba10e..18e7a7a7 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -63,6 +63,7 @@ namespace NadekoBot.Modules.Administration [RequireUserPermission(GuildPermission.Administrator)] public async Task ResetPermissions() { + var channel = (ITextChannel)Context.Channel; using (var uow = DbHandler.UnitOfWork()) { var config = uow.GuildConfigs.PermissionsFor(Context.Guild.Id); @@ -78,7 +79,7 @@ namespace NadekoBot.Modules.Administration await uow.CompleteAsync(); } - await Context.Channel.SendConfirmAsync($"{Context.Message.Author.Mention} ๐Ÿ†— **Permissions for this server are reset.**"); + await channel.SendConfirmAsync($"{Context.Message.Author.Mention} ๐Ÿ†— **Permissions for this server are reset.**"); } [NadekoCommand, Usage, Description, Aliases] @@ -619,9 +620,11 @@ namespace NadekoBot.Modules.Administration cnt -= 100; } var title = $"Chatlog-{Context.Guild.Name}/#{Context.Channel.Name}-{DateTime.Now}.txt"; + var grouping = msgs.GroupBy(x => $"{x.CreatedAt.Date:dd.MM.yyyy}") + .Select(g => new { date = g.Key, messages = g.OrderBy(x => x.CreatedAt).Select(s => $"ใ€{s.Timestamp:HH:mm:ss}ใ€‘{s.Author}:" + s.ToString()) }); await (Context.User as IGuildUser).SendFileAsync( await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream().ConfigureAwait(false), - title, title).ConfigureAwait(false); +title, title).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs index 224a4e8e..e3cb8380 100644 --- a/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/AutoAssignRoleCommands.cs @@ -64,12 +64,12 @@ namespace NadekoBot.Modules.Administration { conf.AutoAssignRoleId = 0; ulong throwaway; - AutoAssignedRoles.TryRemove(channel.Guild.Id, out throwaway); + AutoAssignedRoles.TryRemove(Context.Guild.Id, out throwaway); } else { conf.AutoAssignRoleId = role.Id; - AutoAssignedRoles.AddOrUpdate(channel.Guild.Id, role.Id, (key, val) => role.Id); + AutoAssignedRoles.AddOrUpdate(Context.Guild.Id, role.Id, (key, val) => role.Id); } await uow.CompleteAsync().ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 481f2f6e..ddea0a30 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -715,7 +715,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] public async Task LogServer(IUserMessage msg, PermissionAction action) { @@ -750,7 +750,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] public async Task LogIgnore(IUserMessage imsg) { @@ -779,7 +779,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] public async Task LogEvents(IUserMessage imsg) { @@ -788,7 +788,7 @@ namespace NadekoBot.Modules.Administration [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - [RequirePermission(GuildPermission.Administrator)] + [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] public async Task Log(IUserMessage imsg, LogType type) { diff --git a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs index 6fc10249..1d76b1e7 100644 --- a/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/VoicePlusTextCommands.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Administration _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); } - private static async void UserUpdatedEventHandler(SocketUser iuser, IVoiceState before, IVoiceState after) + private static async void UserUpdatedEventHandler(SocketUser iuser, SocketVoiceState before, SocketVoiceState after) { var user = (iuser as SocketGuildUser); var guild = user?.Guild; @@ -46,7 +46,7 @@ namespace NadekoBot.Modules.Administration try { - var botUserPerms = guild.GetCurrentUser().GuildPermissions; + var botUserPerms = guild.CurrentUser.GuildPermissions; if (before.VoiceChannel == after.VoiceChannel) return; @@ -72,38 +72,37 @@ namespace NadekoBot.Modules.Administration } - var beforeVch = before.VoiceChannel; - if (beforeVch != null) - { - var textChannel = (await guild.GetTextChannelsAsync()).Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault(); - if (textChannel != null) - await textChannel.AddPermissionOverwriteAsync(user, - new OverwritePermissions(readMessages: PermValue.Deny, - sendMessages: PermValue.Deny)).ConfigureAwait(false); - } - var afterVch = after.VoiceChannel; - if (afterVch != null && guild.AFKChannelId != afterVch.Id) - { - var textChannel = (await guild.GetTextChannelsAsync()) - .Where(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant()) - .FirstOrDefault(); - if (textChannel == null) - { - textChannel = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false)); - await textChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, - new OverwritePermissions(readMessages: PermValue.Deny, - sendMessages: PermValue.Deny)).ConfigureAwait(false); - } - await textChannel.AddPermissionOverwriteAsync(user, - new OverwritePermissions(readMessages: PermValue.Allow, - sendMessages: PermValue.Allow)).ConfigureAwait(false); - } - } - catch (Exception ex) + var beforeVch = before.VoiceChannel; + if (beforeVch != null) { - Console.WriteLine(ex); + var textChannel = (await guild.GetTextChannelsAsync()).Where(t => t.Name == GetChannelName(beforeVch.Name).ToLowerInvariant()).FirstOrDefault(); + if (textChannel != null) + await textChannel.AddPermissionOverwriteAsync(user, + new OverwritePermissions(readMessages: PermValue.Deny, + sendMessages: PermValue.Deny)).ConfigureAwait(false); } - }); + var afterVch = after.VoiceChannel; + if (afterVch != null && guild.AFKChannelId != afterVch.Id) + { + var textChannel = (await guild.GetTextChannelsAsync()) + .Where(t => t.Name == GetChannelName(afterVch.Name).ToLowerInvariant()) + .FirstOrDefault(); + if (textChannel == null) + { + textChannel = (await guild.CreateTextChannelAsync(GetChannelName(afterVch.Name).ToLowerInvariant()).ConfigureAwait(false)); + await textChannel.AddPermissionOverwriteAsync(guild.EveryoneRole, + new OverwritePermissions(readMessages: PermValue.Deny, + sendMessages: PermValue.Deny)).ConfigureAwait(false); + } + await textChannel.AddPermissionOverwriteAsync(user, + new OverwritePermissions(readMessages: PermValue.Allow, + sendMessages: PermValue.Allow)).ConfigureAwait(false); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } } private static string GetChannelName(string voiceName) => diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index d7beef2e..7b331bd7 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -9,6 +9,7 @@ using Discord; using NadekoBot.Extensions; using NLog; using System.Diagnostics; +using Discord.WebSocket; namespace NadekoBot.Modules.CustomReactions { diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index f1c3252a..4790c890 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; +using Image = ImageSharp.Image; namespace NadekoBot.Modules.Gambling { @@ -162,7 +163,7 @@ namespace NadekoBot.Modules.Gambling var embed = new EmbedBuilder().WithOkColor().WithDescription($"{umsg.Author.Mention} rolled {n1} fate {(n1 == 1 ? "die" : "dice")}.") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))))); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } else if ((match = dndRegex.Match(arg)).Length != 0) { @@ -185,7 +186,7 @@ namespace NadekoBot.Modules.Gambling var embed = new EmbedBuilder().WithOkColor().WithDescription($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString()))))); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } } } diff --git a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs index 50abf8b0..e730b4df 100644 --- a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs @@ -5,6 +5,7 @@ using NadekoBot.Extensions; using NadekoBot.Services; using NLog; using Services.CleverBotApi; +using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; @@ -92,6 +93,8 @@ namespace NadekoBot.Modules.Games [RequireUserPermission(ChannelPermission.ManageMessages)] public async Task Cleverbot() { + var channel = (ITextChannel)Context.Channel; + Lazy throwaway; if (CleverbotGuilds.TryRemove(channel.Guild.Id, out throwaway)) { diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index 59830413..4c2802d0 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -128,57 +128,58 @@ namespace NadekoBot.Modules.Games } } - private async void Vote(IMessage imsg) - { - try + private async void Vote(IMessage imsg) { - // has to be a user message - var msg = imsg as IUserMessage; - if (msg == null || msg.Author.IsBot) - return; - - // has to be an integer - int vote; - if (!int.TryParse(imsg.Content, out vote)) - return; - if (vote < 1 || vote > answers.Length) - return; - - IMessageChannel ch; - if (isPublic) + try { - //if public, channel must be the same the poll started in - if (originalMessage.Channel.Id != imsg.Channel.Id) - return; - ch = imsg.Channel; - } - else - { - //if private, channel must be dm channel - if ((ch = msg.Channel as IDMChannel) == null) + // has to be a user message + var msg = imsg as IUserMessage; + if (msg == null || msg.Author.IsBot) return; - // user must be a member of the guild this poll is in - var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); - if (!guildUsers.Any(u => u.Id == imsg.Author.Id)) + // has to be an integer + int vote; + if (!int.TryParse(imsg.Content, out vote)) + return; + if (vote < 1 || vote > answers.Length) return; - } - //user can vote only once - if (participants.TryAdd(msg.Author.Id, vote)) - { - if (!isPublic) + IMessageChannel ch; + if (isPublic) { - await ch.SendConfirmAsync($"Thanks for voting **{msg.Author.Username}**.").ConfigureAwait(false); + //if public, channel must be the same the poll started in + if (originalMessage.Channel.Id != imsg.Channel.Id) + return; + ch = imsg.Channel; } else { - var toDelete = await ch.SendConfirmAsync($"{msg.Author.Mention} cast their vote.").ConfigureAwait(false); - toDelete.DeleteAfter(5); + //if private, channel must be dm channel + if ((ch = msg.Channel as IDMChannel) == null) + return; + + // user must be a member of the guild this poll is in + var guildUsers = await guild.GetUsersAsync().ConfigureAwait(false); + if (!guildUsers.Any(u => u.Id == imsg.Author.Id)) + return; + } + + //user can vote only once + if (participants.TryAdd(msg.Author.Id, vote)) + { + if (!isPublic) + { + await ch.SendConfirmAsync($"Thanks for voting **{msg.Author.Username}**.").ConfigureAwait(false); + } + else + { + var toDelete = await ch.SendConfirmAsync($"{msg.Author.Mention} cast their vote.").ConfigureAwait(false); + toDelete.DeleteAfter(5); + } } } + catch { } } - catch { } } } } \ No newline at end of file diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index ac4a4325..b076033b 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -37,7 +37,7 @@ namespace NadekoBot.Modules.Music Directory.CreateDirectory(MusicDataPath); } - private async Task Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) + private async void Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) { var usr = iusr as SocketGuildUser; if (usr == null || @@ -47,16 +47,22 @@ namespace NadekoBot.Modules.Music MusicPlayer player; if (!MusicPlayers.TryGetValue(usr.Guild.Id, out player)) return; - - var users = await player.PlaybackVoiceChannel.GetUsersAsync().Flatten().ConfigureAwait(false); - if ((player.PlaybackVoiceChannel == newState.VoiceChannel && //if joined first, and player paused, unpause - player.Paused && - users.Count() == 2) || // keep in mind bot is in the channel (+1) - (player.PlaybackVoiceChannel == oldState.VoiceChannel && // if left last, and player unpaused, pause - !player.Paused && - users.Count() == 1)) + try { - player.TogglePause(); + var users = await player.PlaybackVoiceChannel.GetUsersAsync().Flatten().ConfigureAwait(false); + if ((player.PlaybackVoiceChannel == newState.VoiceChannel && //if joined first, and player paused, unpause + player.Paused && + users.Count() == 2) || // keep in mind bot is in the channel (+1) + (player.PlaybackVoiceChannel == oldState.VoiceChannel && // if left last, and player unpaused, pause + !player.Paused && + users.Count() == 1)) + { + player.TogglePause(); + } + } + catch (Exception ex) + { + _log.Warn(ex); } } @@ -98,8 +104,7 @@ namespace NadekoBot.Modules.Music [RequireContext(ContextType.Guild)] public async Task Destroy() { - var channel = (ITextChannel)umsg.Channel; - await channel.SendErrorAsync("This command is temporarily disabled.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("This command is temporarily disabled.").ConfigureAwait(false); /*MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return Task.CompletedTask; @@ -128,7 +133,7 @@ namespace NadekoBot.Modules.Music var channel = (ITextChannel)Context.Channel; MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; - if (((IGuildUser)umsg.Author).VoiceChannel != musicPlayer.PlaybackVoiceChannel) + if (((IGuildUser)Context.User).VoiceChannel != musicPlayer.PlaybackVoiceChannel) return; var val = musicPlayer.FairPlay = !musicPlayer.FairPlay; @@ -153,7 +158,7 @@ namespace NadekoBot.Modules.Music await QueueSong(((IGuildUser)Context.User), (ITextChannel)Context.Channel, ((IGuildUser)Context.User).VoiceChannel, query, musicType: MusicType.Soundcloud).ConfigureAwait(false); if ((await Context.Guild.GetCurrentUserAsync()).GetPermissions((IGuildChannel)Context.Channel).ManageMessages) { - umsg.DeleteAfter(10); + Context.Message.DeleteAfter(10); } } @@ -174,7 +179,7 @@ namespace NadekoBot.Modules.Music var currentSong = musicPlayer.CurrentSong; if (currentSong == null) { - await channel.SendErrorAsync("๐ŸŽต No active music player.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("๐ŸŽต No active music player.").ConfigureAwait(false); return; } @@ -195,7 +200,7 @@ namespace NadekoBot.Modules.Music .Select(v => $"`{++number}.` {v.PrettyFullName}"))) .WithFooter(ef => ef.WithText($"{musicPlayer.PrettyVolume} | {musicPlayer.Playlist.Count} " + $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {total.Minutes}m {total.Seconds}s | " + -(musicPlayer.FairPlay? "โœ”๏ธfairplay" : "โœ–๏ธfairplay") + $" | " + (maxPlaytime == 0 ? "unlimited" : $"{maxPlaytime}s limit"))) +(musicPlayer.FairPlay ? "โœ”๏ธfairplay" : "โœ–๏ธfairplay") + $" | " + (maxPlaytime == 0 ? "unlimited" : $"{maxPlaytime}s limit"))) .WithOkColor(); if (musicPlayer.RepeatSong) @@ -210,7 +215,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota { embed.WithTitle("๐ŸŽต Song queue is full!"); } - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -228,10 +233,10 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota var embed = new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Now Playing").WithMusicIcon()) .WithDescription(currentSong.PrettyName) - .WithThumbnail(tn => tn.Url = currentSong.Thumbnail) + .WithThumbnailUrl(currentSong.Thumbnail) .WithFooter(ef => ef.WithText(musicPlayer.PrettyVolume + " | " + currentSong.PrettyFullTime + $" | {currentSong.PrettyProvider} | {currentSong.QueuerName}")); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -315,11 +320,11 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota } var count = ids.Count(); - var msg = await channel.SendMessageAsync($"๐ŸŽต Attempting to queue **{count}** songs".SnPl(count) + "...").ConfigureAwait(false); + var msg = await Context.Channel.SendMessageAsync($"๐ŸŽต Attempting to queue **{count}** songs".SnPl(count) + "...").ConfigureAwait(false); var cancelSource = new CancellationTokenSource(); - var gusr = (IGuildUser)umsg.Author; + var gusr = (IGuildUser)Context.User; while (ids.Any() && !cancelSource.IsCancellationRequested) { @@ -329,7 +334,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota return; try { - await QueueSong(gusr, channel, gusr.VoiceChannel, id, true).ConfigureAwait(false); + await QueueSong(gusr, (ITextChannel)Context.Channel, gusr.VoiceChannel, id, true).ConfigureAwait(false); } catch (SongNotFoundException) { } catch { try { cancelSource.Cancel(); } catch { } } @@ -393,7 +398,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota var dir = new DirectoryInfo(arg); var fileEnum = dir.GetFiles("*", SearchOption.AllDirectories) .Where(x => !x.Attributes.HasFlag(FileAttributes.Hidden | FileAttributes.System)); - var gusr = (IGuildUser)umsg.Author; + var gusr = (IGuildUser)Context.User; foreach (var file in fileEnum) { try @@ -479,7 +484,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota .WithFooter(ef => ef.WithText($"{song.PrettyProvider} | {song.QueuerName}")) .WithErrorColor(); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -528,15 +533,15 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota playlist.Insert(n2 - 1, s); var nn1 = n2 < n1 ? n1 : n1 - 1; playlist.RemoveAt(nn1); - - var embed = new EmbedBuilder() - .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") - .WithUrl($"{s.SongInfo.Query}") - .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) - .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) - .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) - .WithColor(NadekoBot.OkColor); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + + var embed = new EmbedBuilder() + .WithTitle($"{s.SongInfo.Title.TrimTo(70)}") + .WithUrl($"{s.SongInfo.Query}") + .WithAuthor(eab => eab.WithName("Song Moved").WithIconUrl("https://cdn.discordapp.com/attachments/155726317222887425/258605269972549642/music1.png")) + .AddField(fb => fb.WithName("**From Position**").WithValue($"#{n1}").WithIsInline(true)) + .AddField(fb => fb.WithName("**To Position**").WithValue($"#{n2}").WithIsInline(true)) + .WithColor(NadekoBot.OkColor); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); //await channel.SendConfirmAsync($"๐ŸŽตMoved {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false); @@ -549,8 +554,8 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota { MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) - { return; + musicPlayer.MaxQueueSize = size; await Context.Channel.SendConfirmAsync($"๐ŸŽต Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}."); } @@ -567,7 +572,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota if (!MusicPlayers.TryGetValue(channel.Guild.Id, out musicPlayer)) return; musicPlayer.MaxPlaytimeSeconds = seconds; - if(seconds == 0) + if (seconds == 0) await channel.SendConfirmAsync($"๐ŸŽต Max playtime has no limit now."); else await channel.SendConfirmAsync($"๐ŸŽต Max playtime set to {seconds} seconds."); @@ -587,7 +592,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota var currentValue = musicPlayer.ToggleRepeatSong(); if (currentValue) - await channel.EmbedAsync(new EmbedBuilder() + await Context.Channel.EmbedAsync(new EmbedBuilder() .WithOkColor() .WithAuthor(eab => eab.WithMusicIcon().WithName("๐Ÿ”‚ Repeating track")) .WithDescription(currentSong.PrettyName) @@ -809,29 +814,27 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota } var mp = new MusicPlayer(voiceCh, vol); IUserMessage playingMessage = null; - IUserMessage lastFinishedMessage = null; + IUserMessage lastFinishedMessage = null; mp.OnCompleted += async (s, song) => { try { - if (finishedMessage != null) - finishedMessage.DeleteAfter(0); + if (lastFinishedMessage != null) + lastFinishedMessage.DeleteAfter(0); - finishedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() + lastFinishedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon()) .WithDescription(song.PrettyName) - .WithFooter(ef => ef.WithText(song.PrettyInfo)) - .Build()) - .ConfigureAwait(false); + .WithFooter(ef => ef.WithText(song.PrettyInfo))) + .ConfigureAwait(false); if (mp.Autoplay && mp.Playlist.Count == 0 && song.SongInfo.Provider == "YouTube") { - await QueueSong(queuer.Guild.GetCurrentUser(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); + await QueueSong(await queuer.Guild.GetCurrentUserAsync(), textCh, voiceCh, (await NadekoBot.Google.GetRelatedVideosAsync(song.SongInfo.Query, 4)).ToList().Shuffle().FirstOrDefault(), silent, musicType).ConfigureAwait(false); } } catch { } }; - IUserMessage playingMessage = null; mp.OnStarted += async (player, song) => { @@ -852,17 +855,17 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota } catch { } }; - mp.OnPauseChanged += async (paused) => - { - try - { - if (paused) - await textCh.SendConfirmAsync("๐ŸŽต Music playback **paused**.").ConfigureAwait(false); - else - await textCh.SendConfirmAsync("๐ŸŽต Music playback **resumed**.").ConfigureAwait(false); - } - catch { } - }; + mp.OnPauseChanged += async (paused) => + { + try + { + if (paused) + await textCh.SendConfirmAsync("๐ŸŽต Music playback **paused**.").ConfigureAwait(false); + else + await textCh.SendConfirmAsync("๐ŸŽต Music playback **resumed**.").ConfigureAwait(false); + } + catch { } + }; return mp; }); Song resolvedSong; @@ -889,7 +892,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota var queuedMessage = await textCh.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Queued Song #" + (musicPlayer.Playlist.Count + 1)).WithMusicIcon()) .WithDescription($"{resolvedSong.PrettyName}\nQueue ") - .WithThumbnail(tn => tn.Url = resolvedSong.Thumbnail) + .WithThumbnailUrl(resolvedSong.Thumbnail) .WithFooter(ef => ef.WithText(resolvedSong.PrettyProvider))) .ConfigureAwait(false); if (queuedMessage != null) diff --git a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs index cd57b66b..019f7f20 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OverwatchCommands.cs @@ -4,6 +4,7 @@ using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Searches.Models; using Newtonsoft.Json; +using NLog; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -27,7 +28,7 @@ namespace NadekoBot.Modules.Searches return; var battletag = Regex.Replace(query, "#", "-", RegexOptions.IgnoreCase); - await channel.TriggerTypingAsync().ConfigureAwait(false); + await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); try { await Context.Channel.TriggerTypingAsync().ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index f6cc29d7..bbb6db35 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -190,7 +190,7 @@ namespace NadekoBot.Modules.Searches await Context.Channel.SendErrorAsync("Failed to shorten that url.").ConfigureAwait(false); } - await msg.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) + await Context.Channel.EmbedAsync(new EmbedBuilder().WithColor(NadekoBot.OkColor) .AddField(efb => efb.WithName("Original Url") .WithValue($"<{arg}>")) .AddField(efb => efb.WithName("Short Url") @@ -244,7 +244,7 @@ namespace NadekoBot.Modules.Searches .WithAuthor(eab => eab.WithName("Search For: " + terms.TrimTo(50)) .WithUrl(fullQueryLink) .WithIconUrl("http://i.imgur.com/G46fm8J.png")) - .WithTitle(umsg.Author.Mention) + .WithTitle(Context.User.Mention) .WithFooter(efb => efb.WithText(totalResults)); var desc = await Task.WhenAll(results.Select(async res => @@ -612,12 +612,11 @@ namespace NadekoBot.Modules.Searches public async Task Avatar([Remainder] IUser usr = null) { if (usr == null) - usr = umsg.Author; + usr = Context.User; - await channel.EmbedAsync(new EmbedBuilder().WithOkColor() + await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithTitle($"{usr}'s Avatar") - .WithImageUrl(usr.AvatarUrl) - .Build()).ConfigureAwait(false); + .WithImageUrl(usr.AvatarUrl)).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -745,8 +744,7 @@ namespace NadekoBot.Modules.Searches await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription(umsg.Author.Mention + " " + tag) .WithImageUrl(url) - .WithFooter(efb => efb.WithText(type.ToString())) - .Build()).ConfigureAwait(false); + .WithFooter(efb => efb.WithText(type.ToString()))).ConfigureAwait(false); } public static async Task InternalDapiSearch(string tag, DapiSearchType type) @@ -793,7 +791,7 @@ namespace NadekoBot.Modules.Searches return null; } } - public static async Task ValidateQuery(ITextChannel ch, string query) + public static async Task ValidateQuery(IMessageChannel ch, string query) { if (!string.IsNullOrEmpty(query.Trim())) return true; await ch.SendErrorAsync("Please specify search parameters.").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index b4be0f7b..1570a09c 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -23,7 +23,6 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task WhosPlaying([Remainder] string game = null) public async Task TogetherTube(IUserMessage imsg) { Uri target; @@ -191,18 +190,16 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] public async Task Stats() { - var channel = Context.Channel; - var stats = NadekoBot.Stats; - await channel.EmbedAsync( + await Context.Channel.EmbedAsync( new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName($"NadekoBot v{StatsService.BotVersion}") .WithUrl("http://nadekobot.readthedocs.io/en/latest/") .WithIconUrl("https://cdn.discordapp.com/avatars/116275390695079945/b21045e778ef21c96d175400e779f0fb.jpg")) .AddField(efb => efb.WithName(Format.Bold("Author")).WithValue(stats.Author).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Library")).WithValue(stats.Library).WithIsInline(true)) - .AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.GetCurrentUser().Id.ToString()).WithIsInline(true)) + .AddField(efb => efb.WithName(Format.Bold("Bot ID")).WithValue(NadekoBot.Client.CurrentUser().Id.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Commands Ran")).WithValue(stats.CommandsRan.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Messages")).WithValue($"{stats.MessageCounter} ({stats.MessagesPerSecond:F2}/sec)").WithIsInline(true)) .AddField(efb => efb.WithName(Format.Bold("Memory")).WithValue($"{stats.Heap} MB").WithIsInline(true)) diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 463d257e..58a5bb50 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -58,9 +58,9 @@ namespace NadekoBot.Services _client.MessageReceived += MessageReceivedHandler; } - private async Task MessageReceivedHandler(SocketMessage msg) + private async void MessageReceivedHandler(SocketMessage msg) { - var usrMsg = msg as SocketUserMessage; + var usrMsg = msg as SocketUserMessage; if (usrMsg == null) return; @@ -135,87 +135,75 @@ namespace NadekoBot.Services catch { } string messageContent = usrMsg.Content; - //foreach (var k in NadekoBot.ModulePrefixes.Values) - //{ - // if (usrMsg.Content.ToLowerInvariant().StartsWith(k)) - // { - // messageContent = messageContent.Insert(k.Length, " "); - // break; - // } - //} + var sw = new Stopwatch(); + sw.Start(); - - var throwaway = Task.Run(async () => + try { - var sw = new Stopwatch(); - sw.Start(); - - try + var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best); + var command = exec.CommandInfo; + var permCache = exec.PermissionCache; + var result = exec.Result; + sw.Stop(); + var channel = (msg.Channel as ITextChannel); + if (result.IsSuccess) { - var exec = await ExecuteCommand(new CommandContext(_client.MainClient, usrMsg), messageContent, DependencyMap.Empty, MultiMatchHandling.Best); - var command = exec.CommandInfo; - var permCache = exec.PermissionCache; - var result = exec.Result; - sw.Stop(); - var channel = (msg.Channel as ITextChannel); - if (result.IsSuccess) + await CommandExecuted(usrMsg, command); + _log.Info("Command Executed after {4}s\n\t" + + "User: {0}\n\t" + + "Server: {1}\n\t" + + "Channel: {2}\n\t" + + "Message: {3}", + msg.Author + " [" + msg.Author.Id + "]", // {0} + (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} + (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} + usrMsg.Content, // {3} + sw.Elapsed.TotalSeconds // {4} + ); + } + else if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) + { + _log.Warn("Command Errored after {5}s\n\t" + + "User: {0}\n\t" + + "Server: {1}\n\t" + + "Channel: {2}\n\t" + + "Message: {3}\n\t" + + "Error: {4}", + msg.Author + " [" + msg.Author.Id + "]", // {0} + (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} + (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} + usrMsg.Content,// {3} + result.ErrorReason, // {4} + sw.Elapsed.TotalSeconds // {5} + ); + if (guild != null && command != null && result.Error == CommandError.Exception) { - await CommandExecuted(usrMsg, command); - _log.Info("Command Executed after {4}s\n\t" + - "User: {0}\n\t" + - "Server: {1}\n\t" + - "Channel: {2}\n\t" + - "Message: {3}", - msg.Author + " [" + msg.Author.Id + "]", // {0} - (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} - (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} - usrMsg.Content, // {3} - sw.Elapsed.TotalSeconds // {4} - ); - } - else if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) - { - _log.Warn("Command Errored after {5}s\n\t" + - "User: {0}\n\t" + - "Server: {1}\n\t" + - "Channel: {2}\n\t" + - "Message: {3}\n\t" + - "Error: {4}", - msg.Author + " [" + msg.Author.Id + "]", // {0} - (channel == null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]"), // {1} - (channel == null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]"), // {2} - usrMsg.Content,// {3} - result.ErrorReason, // {4} - sw.Elapsed.TotalSeconds // {5} - ); - if (guild != null && command != null && result.Error == CommandError.Exception) - { - if (permCache != null && permCache.Verbose) - try { await msg.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } - } - } - else - { - if (msg.Channel is IPrivateChannel) - { - //rofl, gotta do this to prevent this message from occuring on polls - int vote; - if (int.TryParse(msg.Content, out vote)) return; - - await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); - - await DMForwardCommands.HandleDMForwarding(msg, ownerChannels); - } + if (permCache != null && permCache.Verbose) + try { await msg.Channel.SendMessageAsync("โš ๏ธ " + result.ErrorReason).ConfigureAwait(false); } catch { } } } - catch (Exception ex) + else { - _log.Warn(ex, "Error in CommandHandler"); - if (ex.InnerException != null) - _log.Warn(ex.InnerException, "Inner Exception of the error in CommandHandler"); + if (msg.Channel is IPrivateChannel) + { + //rofl, gotta do this to prevent this message from occuring on polls + int vote; + if (int.TryParse(msg.Content, out vote)) return; + + await msg.Channel.SendMessageAsync(Help.DMHelpString).ConfigureAwait(false); + + await DMForwardCommands.HandleDMForwarding(msg, ownerChannels); + } } - }); + } + catch (Exception ex) + { + _log.Warn(ex, "Error in CommandHandler"); + if (ex.InnerException != null) + _log.Warn(ex.InnerException, "Inner Exception of the error in CommandHandler"); + } + return; } public Task ExecuteCommandAsync(CommandContext context, int argPos, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception) @@ -267,7 +255,7 @@ namespace NadekoBot.Services } } - var cmd = commands[i]; + var cmd = commands[i].Command; bool resetCommand = cmd.Name == "ResetPermissions"; PermissionCache pc; if (context.Guild != null) @@ -326,4 +314,4 @@ namespace NadekoBot.Services } } } -} +} \ No newline at end of file diff --git a/src/NadekoBot/ShardedDiscordClient.cs b/src/NadekoBot/ShardedDiscordClient.cs index d392cb8f..fcee8863 100644 --- a/src/NadekoBot/ShardedDiscordClient.cs +++ b/src/NadekoBot/ShardedDiscordClient.cs @@ -14,19 +14,19 @@ namespace NadekoBot private DiscordSocketConfig discordSocketConfig; private Logger _log { get; } - public event Action UserJoined = delegate { }; - public event Action MessageReceived = delegate { }; - public event Action UserLeft = delegate { }; - public event Action UserUpdated = delegate { }; - public event Action, IMessage> MessageUpdated = delegate { }; - public event Action> MessageDeleted = delegate { }; - public event Action UserBanned = delegate { }; - public event Action UserUnbanned = delegate { }; - public event Action UserPresenceUpdated = delegate { }; - public event Action UserVoiceStateUpdated = delegate { }; - public event Action ChannelCreated = delegate { }; - public event Action ChannelDestroyed = delegate { }; - public event Action ChannelUpdated = delegate { }; + public event Action UserJoined = delegate { }; + public event Action MessageReceived = delegate { }; + public event Action UserLeft = delegate { }; + public event Action UserUpdated = delegate { }; + public event Action, SocketMessage> MessageUpdated = delegate { }; + public event Action> MessageDeleted = delegate { }; + public event Action UserBanned = delegate { }; + public event Action UserUnbanned = delegate { }; + public event Action, SocketUser, SocketPresence, SocketPresence> UserPresenceUpdated = delegate { }; + public event Action UserVoiceStateUpdated = delegate { }; + public event Action ChannelCreated = delegate { }; + public event Action ChannelDestroyed = delegate { }; + public event Action ChannelUpdated = delegate { }; public event Action Disconnected = delegate { }; private uint _connectedCount = 0; @@ -58,7 +58,7 @@ namespace NadekoBot client.MessageDeleted += (arg1, arg2) => { MessageDeleted(arg1, arg2); return Task.CompletedTask; }; client.UserBanned += (arg1, arg2) => { UserBanned(arg1, arg2); return Task.CompletedTask; }; client.UserUnbanned += (arg1, arg2) => { UserUnbanned(arg1, arg2); return Task.CompletedTask; }; - client.UserPresenceUpdated += (arg1, arg2, arg3) => { UserPresenceUpdated(arg1, arg2, arg3); return Task.CompletedTask; }; + client.UserPresenceUpdated += (arg1, arg2, arg3, arg4) => { UserPresenceUpdated(arg1, arg2, arg3, arg4); return Task.CompletedTask; }; client.UserVoiceStateUpdated += (arg1, arg2, arg3) => { UserVoiceStateUpdated(arg1, arg2, arg3); return Task.CompletedTask; }; client.ChannelCreated += arg => { ChannelCreated(arg); return Task.CompletedTask; }; client.ChannelDestroyed += arg => { ChannelDestroyed(arg); return Task.CompletedTask; }; @@ -119,7 +119,7 @@ namespace NadekoBot var sw = Stopwatch.StartNew(); await c.DownloadAllUsersAsync().ConfigureAwait(false); sw.Stop(); - _log.Info($"Shard #{c.ShardId} downloaded {c.GetGuilds().Sum(g => g.GetUsers().Count)} users after {sw.Elapsed.TotalSeconds:F2}s ({++_downloadedCount}/{Clients.Count})."); + _log.Info($"Shard #{c.ShardId} downloaded {c.Guilds.Sum(g => g.Users.Count)} users after {sw.Elapsed.TotalSeconds:F2}s ({++_downloadedCount}/{Clients.Count})."); })); public Task SetGame(string game) => Task.WhenAll(Clients.Select(ms => ms.SetGame(game))); diff --git a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs index 389a2c8e..9b4e06c2 100644 --- a/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs +++ b/src/NadekoBot/TypeReaders/BotCommandTypeReader.cs @@ -6,7 +6,7 @@ namespace NadekoBot.TypeReaders { public class CommandTypeReader : TypeReader { - public override Task Read(CommandContext context, string input) + public override Task Read(ICommandContext context, string input) { input = input.ToUpperInvariant(); var cmd = NadekoBot.CommandService.Commands.FirstOrDefault(c => diff --git a/src/NadekoBot/TypeReaders/GuildTypeReader.cs b/src/NadekoBot/TypeReaders/GuildTypeReader.cs index 821a7327..ac017da3 100644 --- a/src/NadekoBot/TypeReaders/GuildTypeReader.cs +++ b/src/NadekoBot/TypeReaders/GuildTypeReader.cs @@ -6,7 +6,7 @@ namespace NadekoBot.TypeReaders { public class GuildTypeReader : TypeReader { - public override Task Read(CommandContext context, string input) + public override Task Read(ICommandContext context, string input) { input = input.Trim().ToLowerInvariant(); var guilds = NadekoBot.Client.GetGuilds(); diff --git a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs index 3363c83e..c1696d0f 100644 --- a/src/NadekoBot/TypeReaders/ModuleTypeReader.cs +++ b/src/NadekoBot/TypeReaders/ModuleTypeReader.cs @@ -7,7 +7,7 @@ namespace NadekoBot.TypeReaders { public class ModuleTypeReader : TypeReader { - public override Task Read(CommandContext context, string input) + public override Task Read(ICommandContext context, string input) { input = input.ToUpperInvariant(); var module = NadekoBot.CommandService.Modules.GroupBy(m => m.GetTopLevelModule()).FirstOrDefault(m => m.Key.Name.ToUpperInvariant() == input); diff --git a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs index fa44d17d..aa3510a6 100644 --- a/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs +++ b/src/NadekoBot/TypeReaders/PermissionActionTypeReader.cs @@ -9,7 +9,7 @@ namespace NadekoBot.TypeReaders /// public class PermissionActionTypeReader : TypeReader { - public override Task Read(CommandContext context, string input) + public override Task Read(ICommandContext context, string input) { input = input.ToUpperInvariant(); switch (input) diff --git a/src/NadekoBot/_Extensions/Extensions.cs b/src/NadekoBot/_Extensions/Extensions.cs index ebb4add6..f9a8157b 100644 --- a/src/NadekoBot/_Extensions/Extensions.cs +++ b/src/NadekoBot/_Extensions/Extensions.cs @@ -23,8 +23,7 @@ namespace NadekoBot.Extensions http.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } - public static EmbedBuilder WithImageUrl(this EmbedBuilder eb, string url) => - eb.WithImage(eib => eib.WithUrl(url)); + public static DateTime ToUnixTimestamp(this double number) => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(number); public static EmbedBuilder WithOkColor(this EmbedBuilder eb) => eb.WithColor(NadekoBot.OkColor); @@ -131,16 +130,16 @@ namespace NadekoBot.Extensions public static Task EmbedAsync(this IMessageChannel ch, EmbedBuilder embed, string msg = "") => ch.SendMessageAsync(msg, embed: embed); - public static Task SendErrorAsync(this IMessageChannel ch, string title, string error, string url = null, string error = null) + public static Task SendErrorAsync(this IMessageChannel ch, string title, string error, string url = null, string footer = null) => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.ErrorColor).WithDescription(error) - .WithTitle(title).WithUrl(url).WithFooter(efb => efb.WithText(error)); + .WithTitle(title).WithUrl(url).WithFooter(efb => efb.WithText(footer))); public static Task SendErrorAsync(this IMessageChannel ch, string error) => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(error)); public static Task SendConfirmAsync(this IMessageChannel ch, string title, string text, string url = null, string footer = null) => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text) - .WithTitle(title).WithUrl(url).WithFooter(efb => efb.WithText(footer)); + .WithTitle(title).WithUrl(url).WithFooter(efb => efb.WithText(footer))); public static Task SendConfirmAsync(this IMessageChannel ch, string text) => ch.SendMessageAsync("", embed: new EmbedBuilder().WithColor(NadekoBot.OkColor).WithDescription(text)); @@ -154,10 +153,8 @@ namespace NadekoBot.Extensions ```"); } - public static Task SendTableAsync(this IMessageChannel ch, IEnumerable items, Func howToPrint, int columns = 3) - { - return ch.SendTableAsync("", items, howToPrint, columns); - } + public static Task SendTableAsync(this IMessageChannel ch, IEnumerable items, Func howToPrint, int columns = 3) => + ch.SendTableAsync("", items, howToPrint, columns); /// /// returns an IEnumerable with randomized element order diff --git a/src/NadekoBot/project.json b/src/NadekoBot/project.json index 8060c31b..17dc48f1 100644 --- a/src/NadekoBot/project.json +++ b/src/NadekoBot/project.json @@ -17,6 +17,7 @@ "define": [] }, "dependencies": { + "AngleSharp": "0.9.9", "VideoLibrary": "1.3.4", "CoreCLR-NCalc": "2.1.2", "Google.Apis.Urlshortener.v1": "1.19.0.138", From 6e3ff9661678c28e5bbc1d915b28fcdad981ea83 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sat, 31 Dec 2016 17:34:21 +0100 Subject: [PATCH 20/30] Compiles and runs --- .../Commands/CrossServerTextChannel.cs | 2 +- .../Administration/Commands/LogCommand.cs | 87 +++++++++++-------- .../Administration/Commands/MuteCommands.cs | 6 +- .../Commands/RatelimitCommand.cs | 1 - .../Commands/ServerGreetCommands.cs | 2 - .../Modules/ClashOfClans/ClashOfClans.cs | 18 ---- .../Modules/Games/Commands/Acropobia.cs | 14 +-- .../Games/Commands/Hangman/HangmanGame.cs | 2 +- .../Games/Commands/PlantAndPickCommands.cs | 8 +- .../Games/Commands/SpeedTypingCommands.cs | 6 +- .../Games/Commands/Trivia/TriviaGame.cs | 7 +- src/NadekoBot/Modules/Help/Help.cs | 3 +- src/NadekoBot/Modules/NSFW/NSFW.cs | 9 +- .../Modules/Permissions/Permissions.cs | 2 + .../Searches/Commands/AnimeSearchCommands.cs | 2 +- .../Commands/StreamNotificationCommands.cs | 6 +- .../Modules/Searches/Commands/Translator.cs | 2 +- .../Modules/Utility/Commands/InfoCommands.cs | 3 +- src/NadekoBot/NadekoBot.cs | 5 +- src/NadekoBot/Services/CommandHandler.cs | 9 +- 20 files changed, 97 insertions(+), 97 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs index bab5090a..62af02da 100644 --- a/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs +++ b/src/NadekoBot/Modules/Administration/Commands/CrossServerTextChannel.cs @@ -31,7 +31,7 @@ namespace NadekoBot.Modules.Administration var channel = imsg.Channel as ITextChannel; if (channel == null) return; - if (msg.Author.Id == NadekoBot.Client.GetCurrentUser().Id) return; + if (msg.Author.Id == NadekoBot.Client.CurrentUser().Id) return; foreach (var subscriber in Subscribers) { var set = subscriber.Value; diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index ddea0a30..776071f8 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Administration MuteCommands.UserUnmuted += MuteCommands_UserUnmuted; } - private async void _client_UserVoiceStateUpdated_TTS(IUser iusr, IVoiceState before, IVoiceState after) + private async void _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { try { @@ -111,7 +111,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresenceTTS)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresenceTTS)) == null) return; string str = null; @@ -143,7 +143,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null) return; string mutes = ""; switch (muteType) @@ -173,7 +173,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) == null) return; string mutes = ""; @@ -206,7 +206,7 @@ namespace NadekoBot.Modules.Administration || (logSetting.LogOtherId == null)) return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(users.First().Guild, logSetting, LogType.Other)) == null) + if ((logChannel = await TryGetLogChannel(users.First().Guild, logSetting, LogType.Other)) == null) return; var punishment = ""; @@ -232,19 +232,27 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserUpdated(IGuildUser before, IGuildUser after) + private async void _client_UserUpdated(SocketUser uBefore, SocketUser uAfter) { try { + var before = uBefore as SocketGuildUser; + if (before == null) + return; + var after = uAfter as SocketGuildUser; + if (after == null) + return; + LogSetting logSetting; if (!GuildLogSettings.TryGetValue(before.Guild.Id, out logSetting) || (logSetting.UserUpdatedId == null)) return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)) == null) + if ((logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)) == null) return; string str = $"๐Ÿ•”`{prettyCurrentTime}`"; + if (before.Username != after.Username) //str += $"**Name Changed**`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Name Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`New:` **{after.ToString()}**"; @@ -254,19 +262,19 @@ namespace NadekoBot.Modules.Administration else if (before.AvatarUrl != after.AvatarUrl) //str += $"**Avatar Changed**๐Ÿ‘ค`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿ–ผ {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; - else if (!before.Roles.SequenceEqual(after.Roles)) + else if (!before.RoleIds.SequenceEqual(after.RoleIds)) { - if (before.Roles.Count() < after.Roles.Count()) + if (before.RoleIds.Count < after.RoleIds.Count) { - var diffRoles = after.Roles.Where(r => !before.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); + var diffRoles = after.RoleIds.Where(r => !before.RoleIds.Contains(r)).Select(r => "**" + before.Guild.GetRole(r).Name + "**"); //str += $"**User's Roles changed โš”โž•**๐Ÿ‘ค`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; - str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Added |** ๐Ÿ†” `{before.Id}`\n\tโœ… {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** โš”"; + str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Added |** ๐Ÿ†” `{before.Id}`\n\tโœ… {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; } - else if (before.Roles.Count() > after.Roles.Count()) + else if (before.RoleIds.Count > after.RoleIds.Count) { - var diffRoles = before.Roles.Where(r => !after.Roles.Contains(r)).Select(r => "**" + r.Name + "**"); + var diffRoles = before.RoleIds.Where(r => !after.RoleIds.Contains(r)).Select(r => "**" + before.Guild.GetRole(r).Name + "**"); //str += $"**User's Roles changed **`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; - str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Removed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿšฎ {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.Roles.Select(r => r.Name)).SanitizeMentions()}`** โš”"; + str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Removed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿšฎ {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; } } else @@ -292,7 +300,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(before.Guild, logSetting, LogType.ChannelUpdated)) == null) + if ((logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.ChannelUpdated)) == null) return; if (before.Name != after.Name) //await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Name Changed** `#{after.Name}` ({after.Id}) @@ -323,7 +331,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelDestroyed)) == null) + if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelDestroyed)) == null) return; await logChannel.SendMessageAsync($"๐Ÿ••`{prettyCurrentTime}`๐Ÿ—‘ **| {(ch is IVoiceChannel ? "Voice" : "Text")} Channel Deleted #โƒฃ {ch.Name}** `({ch.Id})`").ConfigureAwait(false); @@ -345,7 +353,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelCreated)) == null) + if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelCreated)) == null) return; await logChannel.SendMessageAsync($"๐Ÿ•“`{prettyCurrentTime}`๐Ÿ†• **| {(ch is IVoiceChannel ? "Voice" : "Text")} Channel Created: #โƒฃ {ch.Name}** `({ch.Id})`").ConfigureAwait(false); @@ -353,7 +361,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserVoiceStateUpdated(IUser iusr, IVoiceState before, IVoiceState after) => await Task.Run(() => + private async void _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { try { @@ -373,7 +381,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresence)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresence)) == null) return; string str = null; @@ -396,20 +404,25 @@ namespace NadekoBot.Modules.Administration { _log.Warn(ex); } - }); + } - private async void _client_UserPresenceUpdated(IGuildUser usr, IPresence before, IPresence after) => await Task.Run(() => + private async void _client_UserPresenceUpdated(Optional optGuild, SocketUser usr, SocketPresence before, SocketPresence after) { try { + var guild = optGuild.IsSpecified ? optGuild.Value : null; + + if (guild == null) + return; + LogSetting logSetting; - if (!GuildLogSettings.TryGetValue(usr.Guild.Id, out logSetting) + if (!GuildLogSettings.TryGetValue(guild.Id, out logSetting) || (logSetting.LogUserPresenceId == null) || before.Status == after.Status) return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.UserPresence)) == null) + if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserPresence)) == null) return; string str; if (before.Status != after.Status) @@ -420,7 +433,7 @@ namespace NadekoBot.Modules.Administration UserPresenceUpdates.AddOrUpdate(logChannel, new List() { str }, (id, list) => { list.Add(str); return list; }); } catch { } - }); + } private async void _client_UserLeft(IGuildUser usr) { @@ -432,7 +445,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.UserLeft)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserLeft)) == null) return; await logChannel.SendMessageAsync($"โ—๏ธ๐Ÿ•›`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โŒ **| USER LEFT |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } @@ -449,7 +462,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(usr.Guild, logSetting, LogType.UserJoined)) == null) + if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserJoined)) == null) return; await logChannel.SendMessageAsync($"โ•๐Ÿ•“`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โœ… **| USER JOINED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); @@ -467,7 +480,7 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)) == null) + if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)) == null) return; await logChannel.SendMessageAsync($"โ•๐Ÿ•˜`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__โ™ป๏ธ **| USER UN-BANNED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); @@ -485,14 +498,14 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(guild, logSetting, LogType.UserBanned)) == null) + if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserBanned)) == null) return; await logChannel.SendMessageAsync($"โ€ผ๏ธ๐Ÿ••`{prettyCurrentTime}`๐Ÿ‘ค__**{usr.Username}#{usr.Discriminator}**__๐Ÿšซ **| USER BANNED |** ๐Ÿ†” `{usr.Id}`").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } - private async void _client_MessageDeleted(ulong arg1, Optional imsg) + private async void _client_MessageDeleted(ulong arg1, Optional imsg) { try @@ -512,10 +525,10 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(channel.Guild, logSetting, LogType.MessageDeleted)) == null || logChannel.Id == msg.Id) + if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageDeleted)) == null || logChannel.Id == msg.Id) return; var str = $@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{msg.Author.Username}#{msg.Author.Discriminator}**__ **| Deleted Message |** ๐Ÿ†” `{msg.Author.Id}` #โƒฃ `{channel.Name}` -๐Ÿ—‘ {msg.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator)}"; +๐Ÿ—‘ {msg.Resolve(userHandling: TagHandling.FullName)}"; if (msg.Attachments.Any()) str += $"{Environment.NewLine}๐Ÿ“Ž {string.Join(", ", msg.Attachments.Select(a => a.ProxyUrl))}"; await logChannel.SendMessageAsync(str.SanitizeMentions()).ConfigureAwait(false); @@ -523,7 +536,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_MessageUpdated(Optional optmsg, IMessage imsg2) + private async void _client_MessageUpdated(Optional optmsg, SocketMessage imsg2) { try { @@ -549,11 +562,11 @@ namespace NadekoBot.Modules.Administration return; ITextChannel logChannel; - if ((logChannel = TryGetLogChannel(channel.Guild, logSetting, LogType.MessageUpdated)) == null || logChannel.Id == after.Channel.Id) + if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageUpdated)) == null || logChannel.Id == after.Channel.Id) return; await logChannel.SendMessageAsync($@"๐Ÿ•”`{prettyCurrentTime}`๐Ÿ‘ค__**{before.Author.Username}#{before.Author.Discriminator}**__ **| ๐Ÿ“ Edited Message |** ๐Ÿ†” `{before.Author.Id}` #โƒฃ `{channel.Name}` - `Old:` {before.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator).SanitizeMentions()} - **`New:`** {after.Resolve(userHandling: UserMentionHandling.NameAndDiscriminator).SanitizeMentions()}").ConfigureAwait(false); + `Old:` {before.Resolve(userHandling: TagHandling.FullName).SanitizeMentions()} + **`New:`** {after.Resolve(userHandling: TagHandling.FullName).SanitizeMentions()}").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } @@ -577,7 +590,7 @@ namespace NadekoBot.Modules.Administration UserMuted }; - private static ITextChannel TryGetLogChannel(IGuild guild, LogSetting logSetting, LogType logChannelType) + private static async Task TryGetLogChannel(IGuild guild, LogSetting logSetting, LogType logChannelType) { ulong? id = null; switch (logChannelType) @@ -636,7 +649,7 @@ namespace NadekoBot.Modules.Administration UnsetLogSetting(guild.Id, logChannelType); return null; } - var channel = guild.GetTextChannel(id.Value); + var channel = await guild.GetTextChannelAsync(id.Value).ConfigureAwait(false); if (channel == null) { diff --git a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs index d7db545c..b4993bf2 100644 --- a/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/MuteCommands.cs @@ -65,7 +65,7 @@ namespace NadekoBot.Modules.Administration if (muted == null || !muted.Contains(usr.Id)) return; else - await Mute(usr).ConfigureAwait(false); + await MuteUser(usr).ConfigureAwait(false); } catch (Exception ex) { @@ -215,7 +215,7 @@ namespace NadekoBot.Modules.Administration { try { - await user.AddRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); + await user.AddRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); UserMuted(user, MuteType.Chat); await Context.Channel.SendConfirmAsync($"โœ๏ธ๐Ÿšซ **{user}** has been **muted** from chatting.").ConfigureAwait(false); } @@ -232,7 +232,7 @@ namespace NadekoBot.Modules.Administration { try { - await user.RemoveRolesAsync(await GetMuteRole(channel.Guild).ConfigureAwait(false)).ConfigureAwait(false); + await user.RemoveRolesAsync(await GetMuteRole(Context.Guild).ConfigureAwait(false)).ConfigureAwait(false); UserUnmuted(user, MuteType.Chat); await Context.Channel.SendConfirmAsync($"โœ๏ธโœ… **{user}** has been **unmuted** from chatting.").ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs index 38ab1987..ccff187d 100644 --- a/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/RatelimitCommand.cs @@ -118,7 +118,6 @@ namespace NadekoBot.Modules.Administration MaxMessages = msg, PerSeconds = perSec, }; - if (RatelimitingChannels.TryAdd(channel.Id, toAdd)) if(RatelimitingChannels.TryAdd(Context.Channel.Id, toAdd)) { await Context.Channel.SendConfirmAsync("Slow mode initiated", diff --git a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs index e5130b56..80b8c394 100644 --- a/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/ServerGreetCommands.cs @@ -38,8 +38,6 @@ namespace NadekoBot.Modules.Administration if (!conf.SendChannelByeMessage) return; var channel = (await user.Guild.GetTextChannelsAsync()).SingleOrDefault(c => c.Id == conf.ByeMessageChannelId); - if (!conf.SendChannelByeMessage) return; - var channel = (await user.Guild.GetTextChannelsAsync()).FirstOrDefault(c => c.Id == conf.ByeMessageChannelId); if (channel == null) //maybe warn the server owner that the channel is missing return; diff --git a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs index ae012241..26b18995 100644 --- a/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs +++ b/src/NadekoBot/Modules/ClashOfClans/ClashOfClans.cs @@ -58,24 +58,6 @@ namespace NadekoBot.Modules.ClashOfClans } }, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); } - public ClashOfClans() : base() - { - - - checkWarTimer = new Timer(async _ => - { - foreach (var kvp in ClashWars) - { - foreach (var war in kvp.Value) - { - try { await CheckWar(TimeSpan.FromHours(2), war).ConfigureAwait(false); } catch { } - } - } - }, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)); - - sw.Stop(); - _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); - } private static async Task CheckWar(TimeSpan callExpire, ClashWar war) { diff --git a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs index 6d27ee78..dc727a6c 100644 --- a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs +++ b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs @@ -123,7 +123,7 @@ namespace NadekoBot.Modules.Games var embed = GetEmbed(); //SUBMISSIONS PHASE - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); try { await Task.Delay(time * 1000, source.Token).ConfigureAwait(false); @@ -144,13 +144,13 @@ namespace NadekoBot.Modules.Games { await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription($"{submissions.First().Value.Mention} is the winner for being the only user who made a submission!") - .WithFooter(efb => efb.WithText(submissions.First().Key.ToLowerInvariant().ToTitleCase())) - .Build()).ConfigureAwait(false); + .WithFooter(efb => efb.WithText(submissions.First().Key.ToLowerInvariant().ToTitleCase()))) + .ConfigureAwait(false); return; } var submissionClosedEmbed = GetEmbed(); - await channel.EmbedAsync(submissionClosedEmbed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(submissionClosedEmbed).ConfigureAwait(false); //VOTING PHASE this.phase = AcroPhase.Voting; @@ -186,7 +186,7 @@ namespace NadekoBot.Modules.Games if (spamCount > 10) { spamCount = 0; - try { await channel.EmbedAsync(GetEmbed().Build()).ConfigureAwait(false); } + try { await channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); } catch { } } //user didn't input something already @@ -226,7 +226,7 @@ namespace NadekoBot.Modules.Games if (spamCount > 10) { spamCount = 0; - try { await channel.EmbedAsync(GetEmbed().Build()).ConfigureAwait(false); } + try { await channel.EmbedAsync(GetEmbed()).ConfigureAwait(false); } catch { } } @@ -277,7 +277,7 @@ namespace NadekoBot.Modules.Games .WithDescription($"Winner is {submissions[winner.Key].Mention} with {winner.Value} points.\n") .WithFooter(efb => efb.WithText(winner.Key.ToLowerInvariant().ToTitleCase())); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } public void EnsureStopped() diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index cd41dc2e..27afb9f2 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -120,7 +120,7 @@ namespace NadekoBot.Modules.Games.Commands.Hangman var embed = new EmbedBuilder().WithTitle("Hangman Game") .WithDescription(toSend) .AddField(efb => efb.WithName("It was").WithValue(Term.Word)) - .WithImage(eib => eib.WithUrl(Term.ImageUrl)) + .WithImageUrl(Term.ImageUrl) .WithFooter(efb => efb.WithText(string.Join(" ", Guesses))); if (Errors >= MaxErrors) await GameChannel.EmbedAsync(embed.WithErrorColor()).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 8746b631..80ac37d5 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -107,7 +107,7 @@ namespace NadekoBot.Modules.Games { var channel = (ITextChannel)Context.Channel; - if (!channel.Guild.GetCurrentUser().GetPermissions(channel).ManageMessages || !usersRecentlyPicked.Add(imsg.Author.Id)) + if (!(await channel.Guild.GetCurrentUserAsync()).GetPermissions(channel).ManageMessages || !usersRecentlyPicked.Add(Context.User.Id)) return; try @@ -121,14 +121,14 @@ namespace NadekoBot.Modules.Games await Task.WhenAll(msgs.Select(toDelete => toDelete.DeleteAsync())).ConfigureAwait(false); - await CurrencyHandler.AddCurrencyAsync((IGuildUser)imsg.Author, "Picked flower(s).", msgs.Count, false).ConfigureAwait(false); - var msg = await channel.SendConfirmAsync($"**{imsg.Author}** picked {msgs.Count}{Gambling.Gambling.CurrencySign}!").ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, "Picked flower(s).", msgs.Count, false).ConfigureAwait(false); + var msg = await channel.SendConfirmAsync($"**{Context.User}** picked {msgs.Count}{Gambling.Gambling.CurrencySign}!").ConfigureAwait(false); msg.DeleteAfter(10); } finally { await Task.Delay(60000); - usersRecentlyPicked.TryRemove(imsg.Author.Id); + usersRecentlyPicked.TryRemove(Context.User.Id); } } diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index d3a3da2b..ea69ab37 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -125,12 +125,12 @@ namespace NadekoBot.Modules.Games { var wpm = CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60; finishedUserIds.Add(msg.Author.Id); - await Extensions.Extensions.EmbedAsync(this.Channel, (Discord.API.Embed)new EmbedBuilder().WithColor((uint)NadekoBot.OkColor) + await this.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithTitle((string)$"{msg.Author} finished the race!") .AddField(efb => efb.WithName("Place").WithValue($"#{finishedUserIds.Count}").WithIsInline(true)) .AddField(efb => efb.WithName("WPM").WithValue($"{wpm:F2} *[{sw.Elapsed.Seconds.ToString()}sec]*").WithIsInline(true)) - .AddField(efb => efb.WithName((string)"Errors").WithValue((string)distance.ToString()).WithIsInline((bool)true)) - .Build()).ConfigureAwait(false); + .AddField(efb => efb.WithName((string)"Errors").WithValue((string)distance.ToString()).WithIsInline((bool)true))) + .ConfigureAwait(false); if (finishedUserIds.Count % 4 == 0) { await this.Channel.SendConfirmAsync($":exclamation: A lot of people finished, here is the text for those still typing:\n\n**{Format.Sanitize(CurrentSentence.Replace(" ", " \x200B")).SanitizeMentions()}**").ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs index 15d0b47f..00b3f9ec 100644 --- a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs @@ -70,7 +70,7 @@ namespace NadekoBot.Modules.Games.Trivia .AddField(eab => eab.WithName("Category").WithValue(CurrentQuestion.Category)) .AddField(eab => eab.WithName("Question").WithValue(CurrentQuestion.Question)); - questionMessage = await channel.EmbedAsync(questionEmbed.Build()).ConfigureAwait(false); + questionMessage = await channel.EmbedAsync(questionEmbed).ConfigureAwait(false); } catch (HttpException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound || ex.StatusCode == System.Net.HttpStatusCode.Forbidden) { @@ -97,7 +97,7 @@ namespace NadekoBot.Modules.Games.Trivia if (ShowHints) try { - await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(efb => efb.WithText(CurrentQuestion.GetHint())).Build()) + await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(efb => efb.WithText(CurrentQuestion.GetHint()))) .ConfigureAwait(false); } catch (HttpException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound || ex.StatusCode == System.Net.HttpStatusCode.Forbidden) @@ -130,8 +130,7 @@ namespace NadekoBot.Modules.Games.Trivia await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithAuthor(eab => eab.WithName("Trivia Game Ended")) .WithTitle("Final Results") - .WithDescription(GetLeaderboard()) - .Build()).ConfigureAwait(false); + .WithDescription(GetLeaderboard())).ConfigureAwait(false); } public async Task StopGame() diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index b892f19b..46b5fc78 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -41,8 +41,7 @@ namespace NadekoBot.Modules.Help { var embed = new EmbedBuilder().WithOkColor().WithFooter(efb => efb.WithText($" โ„น๏ธ Type `-cmds ModuleName` to get a list of commands in that module. eg `-cmds games`")) - .WithTitle("๐Ÿ“œ List Of Modules").WithDescription("\nโ€ข " + string.Join("\nโ€ข ", NadekoBot.CommandService.Modules.Select(m => m.Name).OrderBy(s=>s))) - .Build(); + .WithTitle("๐Ÿ“œ List Of Modules").WithDescription("\nโ€ข " + string.Join("\nโ€ข ", NadekoBot.CommandService.Modules.Select(m => m.Name).OrderBy(s=>s))); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 2268393f..e29a2fe4 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -61,8 +61,7 @@ namespace NadekoBot.Modules.NSFW else await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithImageUrl(link) - .WithDescription("Tag: " + tag) - .Build()).ConfigureAwait(false); + .WithDescription("Tag: " + tag)).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -148,8 +147,7 @@ namespace NadekoBot.Modules.NSFW await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription(umsg.Author.Mention + " " + tag) .WithImageUrl(url) - .WithFooter(efb => efb.WithText("Danbooru")) - .Build()).ConfigureAwait(false); + .WithFooter(efb => efb.WithText("Danbooru"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -188,8 +186,7 @@ namespace NadekoBot.Modules.NSFW await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription(umsg.Author.Mention + " " + tag) .WithImageUrl(url) - .WithFooter(efb => efb.WithText("e621")) - .Build()).ConfigureAwait(false); + .WithFooter(efb => efb.WithText("e621"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 28aa2fd8..505b55e1 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -9,6 +9,8 @@ using NadekoBot.Services.Database.Models; using System.Collections.Concurrent; using NadekoBot.Extensions; using Discord.WebSocket; +using System.Diagnostics; +using NLog; namespace NadekoBot.Modules.Permissions { diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index d93554df..aff6635e 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Searches .AddField(efb => efb.WithName("Status").WithValue(animeData.AiringStatus.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName("Genres").WithValue(String.Join(", ", animeData.Genres)).WithIsInline(true)) .WithFooter(efb => efb.WithText("Score: " + animeData.average_score + " / 100")); - await channel.EmbedAsync(embed.Build()).ConfigureAwait(false); + await channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index 4f739431..fc315327 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -103,12 +103,14 @@ namespace NadekoBot.Modules.Searches oldStatus.IsLive != newStatus.IsLive) { var server = NadekoBot.Client.GetGuild(fs.GuildId); - var channel = server?.GetTextChannelAsync(fs.ChannelId); + if (server == null) + return; + var channel = await server.GetTextChannelAsync(fs.ChannelId); if (channel == null) return; try { - var msg = await channel.EmbedAsync(fs.GetEmbed(newStatus).Build()).ConfigureAwait(false); + var msg = await channel.EmbedAsync(fs.GetEmbed(newStatus)).ConfigureAwait(false); if (!newStatus.IsLive) msg.DeleteAfter(60); } diff --git a/src/NadekoBot/Modules/Searches/Commands/Translator.cs b/src/NadekoBot/Modules/Searches/Commands/Translator.cs index adf5774b..3ee67e6c 100644 --- a/src/NadekoBot/Modules/Searches/Commands/Translator.cs +++ b/src/NadekoBot/Modules/Searches/Commands/Translator.cs @@ -47,7 +47,7 @@ namespace NadekoBot.Modules.Searches if (!UserLanguages.TryGetValue(key, out langs)) return; - var text = await TranslateInternal(langs, umsg.Resolve(UserMentionHandling.Ignore), true) + var text = await TranslateInternal(langs, umsg.Resolve(TagHandling.Ignore), true) .ConfigureAwait(false); if (autoDelete) try { await umsg.DeleteAsync().ConfigureAwait(false); } catch { } diff --git a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs index 26c8ea16..ca2ab738 100644 --- a/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs +++ b/src/NadekoBot/Modules/Utility/Commands/InfoCommands.cs @@ -122,8 +122,7 @@ namespace NadekoBot.Modules.Utility await imsg.Channel.EmbedAsync(new EmbedBuilder().WithTitle($"Activity Page #{page}") .WithOkColor() .WithFooter(efb => efb.WithText($"{NadekoBot.CommandHandler.UserMessagesSent.Count} users total.")) - .WithDescription(str.ToString()) - .Build()); + .WithDescription(str.ToString())); } } } \ No newline at end of file diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index eaeed098..a3a7a85b 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -67,7 +67,10 @@ namespace NadekoBot }); //initialize Services - CommandService = new CommandService(); + CommandService = new CommandService(new CommandServiceConfig() { + CaseSensitiveCommands = false, + SeparatorChar = '-' + }); Google = new GoogleApiService(); CommandHandler = new CommandHandler(Client, CommandService); Stats = new StatsService(Client, CommandHandler); diff --git a/src/NadekoBot/Services/CommandHandler.cs b/src/NadekoBot/Services/CommandHandler.cs index 58a5bb50..9b2e2f51 100644 --- a/src/NadekoBot/Services/CommandHandler.cs +++ b/src/NadekoBot/Services/CommandHandler.cs @@ -16,6 +16,7 @@ using NadekoBot.Modules.Help; using static NadekoBot.Modules.Administration.Administration; using NadekoBot.Modules.CustomReactions; using NadekoBot.Modules.Games; +using System.Collections.Concurrent; namespace NadekoBot.Services { @@ -35,6 +36,9 @@ namespace NadekoBot.Services public event Func CommandExecuted = delegate { return Task.CompletedTask; }; + //userid/msg count + public ConcurrentDictionary UserMessagesSent { get; } = new ConcurrentDictionary(); + public CommandHandler(ShardedDiscordClient client, CommandService commandService) { _client = client; @@ -64,6 +68,9 @@ namespace NadekoBot.Services if (usrMsg == null) return; + if (!usrMsg.IsAuthor()) + UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old); + if (msg.Author.IsBot || !NadekoBot.Ready) //no bots return; @@ -294,7 +301,7 @@ namespace NadekoBot.Services if (CmdCdsCommands.HasCooldown(cmd, context.Guild, context.User)) return new ExecuteCommandResult(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")); - return new ExecuteCommandResult(commands[i], null, await commands[i].Execute(context, parseResult, dependencyMap)); + return new ExecuteCommandResult(cmd, null, await commands[i].ExecuteAsync(context, parseResult, dependencyMap)); } return new ExecuteCommandResult(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")); From 479963bcc11fddde809a06888b5f64bdff5a5843 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 12:48:07 +0100 Subject: [PATCH 21/30] update to discord.net b2 finished possibly --- Discord.Net | 2 +- src/NadekoBot/Modules/Administration/Commands/LogCommand.cs | 2 +- src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs | 2 +- src/NadekoBot/Modules/Games/Commands/Acropobia.cs | 2 +- src/NadekoBot/Modules/Help/Help.cs | 4 ++-- src/NadekoBot/NadekoBot.cs | 3 +-- 6 files changed, 7 insertions(+), 8 deletions(-) diff --git a/Discord.Net b/Discord.Net index cfc82740..40fa35c8 160000 --- a/Discord.Net +++ b/Discord.Net @@ -1 +1 @@ -Subproject commit cfc827404af535b1e09d725284671b111fe85b93 +Subproject commit 40fa35c851076fb035fab06deb06f2b013281c15 diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 776071f8..a02daaeb 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Administration public partial class Administration { [Group] - public class LogCommands + public class LogCommands : ModuleBase { private static ShardedDiscordClient _client { get; } private static Logger _log { get; } diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index 4790c890..0359d9ec 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -17,7 +17,7 @@ namespace NadekoBot.Modules.Gambling public partial class Gambling { [Group] - public class DriceRollCommands + public class DriceRollCommands : ModuleBase { private Regex dndRegex { get; } = new Regex(@"^(?\d+)d(?\d+)(?:\+(?\d+))?(?:\-(?\d+))?$", RegexOptions.Compiled); private Regex fudgeRegex { get; } = new Regex(@"^(?\d+)d(?:F|f)$", RegexOptions.Compiled); diff --git a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs index dc727a6c..4c8057d6 100644 --- a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs +++ b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs @@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Games public partial class Games { [Group] - public class Acropobia + public class Acropobia : ModuleBase { //channelId, game public static ConcurrentDictionary AcrophobiaGames { get; } = new ConcurrentDictionary(); diff --git a/src/NadekoBot/Modules/Help/Help.cs b/src/NadekoBot/Modules/Help/Help.cs index 46b5fc78..3d32eaca 100644 --- a/src/NadekoBot/Modules/Help/Help.cs +++ b/src/NadekoBot/Modules/Help/Help.cs @@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Help { var embed = new EmbedBuilder().WithOkColor().WithFooter(efb => efb.WithText($" โ„น๏ธ Type `-cmds ModuleName` to get a list of commands in that module. eg `-cmds games`")) - .WithTitle("๐Ÿ“œ List Of Modules").WithDescription("\nโ€ข " + string.Join("\nโ€ข ", NadekoBot.CommandService.Modules.Select(m => m.Name).OrderBy(s=>s))); + .WithTitle("๐Ÿ“œ List Of Modules").WithDescription("\nโ€ข " + string.Join("\nโ€ข ", NadekoBot.CommandService.Modules.GroupBy(m => m.GetTopLevelModule()).Select(m => m.Key.Name).OrderBy(s => s))); await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } @@ -53,7 +53,7 @@ namespace NadekoBot.Modules.Help module = module?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(module)) return; - var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.Name.ToUpperInvariant().StartsWith(module)) + var cmds = NadekoBot.CommandService.Commands.Where(c => c.Module.GetTopLevelModule().Name.ToUpperInvariant().StartsWith(module)) .OrderBy(c => c.Aliases.First()) .Distinct(new CommandTextEqualityComparer()) .AsEnumerable(); diff --git a/src/NadekoBot/NadekoBot.cs b/src/NadekoBot/NadekoBot.cs index a3a7a85b..8b7bba44 100644 --- a/src/NadekoBot/NadekoBot.cs +++ b/src/NadekoBot/NadekoBot.cs @@ -68,8 +68,7 @@ namespace NadekoBot //initialize Services CommandService = new CommandService(new CommandServiceConfig() { - CaseSensitiveCommands = false, - SeparatorChar = '-' + CaseSensitiveCommands = false }); Google = new GoogleApiService(); CommandHandler = new CommandHandler(Client, CommandService); From c374052c5eeb1b2373e2fa985f55a871c5b41808 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 12:52:52 +0100 Subject: [PATCH 22/30] Fixed .totube and .whosplaying --- src/NadekoBot/Modules/Utility/Utility.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index 1570a09c..f9ef6a33 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -23,7 +23,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task TogetherTube(IUserMessage imsg) + public async Task TogetherTube() { Uri target; using (var http = new HttpClient()) @@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Utility [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task WhosPlaying(IUserMessage umsg, [Remainder] string game = null) + public async Task WhosPlaying([Remainder] string game = null) { game = game.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(game)) From 3930d1e7f64a87460c9ceb0aa6005c047eb1b796 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 12:54:02 +0100 Subject: [PATCH 23/30] Fixed log commands --- .../Modules/Administration/Commands/LogCommand.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index a02daaeb..e98d1c38 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -730,7 +730,7 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task LogServer(IUserMessage msg, PermissionAction action) + public async Task LogServer(PermissionAction action) { var channel = (ITextChannel)msg.Channel; LogSetting logSetting; @@ -765,7 +765,7 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task LogIgnore(IUserMessage imsg) + public async Task LogIgnore() { var channel = (ITextChannel)imsg.Channel; int removed; @@ -794,7 +794,7 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task LogEvents(IUserMessage imsg) + public async Task LogEvents() { await imsg.Channel.SendConfirmAsync("Log events you can subscribe to:", String.Join(", ", Enum.GetNames(typeof(LogType)).Cast())); } @@ -803,7 +803,7 @@ namespace NadekoBot.Modules.Administration [RequireContext(ContextType.Guild)] [RequireUserPermission(GuildPermission.Administrator)] [OwnerOnly] - public async Task Log(IUserMessage imsg, LogType type) + public async Task Log(LogType type) { var channel = (ITextChannel)imsg.Channel; ulong? channelId = null; From 221e707963b5f4367f0fe689926d1e757de75d73 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 12:54:44 +0100 Subject: [PATCH 24/30] Fixed log commands part 2 --- .../Modules/Administration/Commands/LogCommand.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index e98d1c38..2bcfb403 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -732,7 +732,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogServer(PermissionAction action) { - var channel = (ITextChannel)msg.Channel; + var channel = (ITextChannel)Context.Channel; LogSetting logSetting; using (var uow = DbHandler.UnitOfWork()) { @@ -767,7 +767,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogIgnore() { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; int removed; using (var uow = DbHandler.UnitOfWork()) { @@ -796,7 +796,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task LogEvents() { - await imsg.Channel.SendConfirmAsync("Log events you can subscribe to:", String.Join(", ", Enum.GetNames(typeof(LogType)).Cast())); + await Context.Channel.SendConfirmAsync("Log events you can subscribe to:", String.Join(", ", Enum.GetNames(typeof(LogType)).Cast())); } [NadekoCommand, Usage, Description, Aliases] @@ -805,7 +805,7 @@ namespace NadekoBot.Modules.Administration [OwnerOnly] public async Task Log(LogType type) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; ulong? channelId = null; using (var uow = DbHandler.UnitOfWork()) { From 755a2c40b3a08c4aa1225fcb31964eeef5ceee20 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 13:26:17 +0100 Subject: [PATCH 25/30] Fixes to some commands which had IUserMesasge leftover --- .../Modules/Gambling/Commands/AnimalRacing.cs | 4 +- .../Gambling/Commands/DiceRollCommand.cs | 42 +++++------ .../Modules/Games/Commands/Acropobia.cs | 7 +- .../Games/Commands/CleverBotCommands.cs | 3 +- .../Games/Commands/Hangman/HangmanGame.cs | 5 +- .../Games/Commands/PlantAndPickCommands.cs | 5 +- .../Modules/Games/Commands/PollCommands.cs | 4 +- .../Games/Commands/SpeedTypingCommands.cs | 5 +- .../Games/Commands/Trivia/TriviaGame.cs | 5 +- .../Modules/Games/Commands/TriviaCommands.cs | 6 +- src/NadekoBot/Modules/Music/Music.cs | 4 +- src/NadekoBot/Modules/NSFW/NSFW.cs | 75 +++++++++---------- src/NadekoBot/Modules/Searches/Searches.cs | 4 +- 13 files changed, 85 insertions(+), 84 deletions(-) diff --git a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs index 250ae679..9acd88e4 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/AnimalRacing.cs @@ -207,9 +207,9 @@ namespace NadekoBot.Modules.Gambling } - private void Client_MessageReceived(IMessage imsg) + private void Client_MessageReceived(SocketMessage imsg) { - var msg = imsg as IUserMessage; + var msg = imsg as SocketUserMessage; if (msg == null) return; if (msg.IsAuthor() || !(imsg.Channel is ITextChannel) || imsg.Channel != raceChannel) diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index 0359d9ec..dcc2c52f 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -26,9 +26,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Roll(IUserMessage umsg) + public async Task Roll() { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; var rng = new NadekoRandom(); @@ -48,7 +48,7 @@ namespace NadekoBot.Modules.Gambling catch { return new MemoryStream(); } }); - await channel.SendFileAsync(imageStream, "dice.png", $"{umsg.Author.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); + await channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } public enum RollOrderType @@ -60,39 +60,39 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Roll(IUserMessage umsg, int num) + public async Task Roll(int num) { - await InternalRoll(umsg, num, true).ConfigureAwait(false); + await InternalRoll(num, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(0)] - public async Task Rolluo(IUserMessage umsg, int num) + public async Task Rolluo(int num) { - await InternalRoll(umsg, num, false).ConfigureAwait(false); + await InternalRoll(num, false).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Roll(IUserMessage umsg, string arg) + public async Task Roll(string arg) { - await InternallDndRoll(umsg, arg, true).ConfigureAwait(false); + await InternallDndRoll(arg, true).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [Priority(1)] - public async Task Rolluo(IUserMessage umsg, string arg) + public async Task Rolluo(string arg) { - await InternallDndRoll(umsg, arg, false).ConfigureAwait(false); + await InternallDndRoll(arg, false).ConfigureAwait(false); } - private async Task InternalRoll(IUserMessage umsg, int num, bool ordered) + private async Task InternalRoll( int num, bool ordered) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -136,12 +136,12 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } - private async Task InternallDndRoll(IUserMessage umsg, string arg, bool ordered) + private async Task InternallDndRoll(string arg, bool ordered) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; if (channel == null) return; @@ -160,7 +160,7 @@ namespace NadekoBot.Modules.Gambling { rolls.Add(fateRolls[rng.Next(0, fateRolls.Length)]); } - var embed = new EmbedBuilder().WithOkColor().WithDescription($"{umsg.Author.Mention} rolled {n1} fate {(n1 == 1 ? "die" : "dice")}.") + var embed = new EmbedBuilder().WithOkColor().WithDescription($"{Context.User.Mention} rolled {n1} fate {(n1 == 1 ? "die" : "dice")}.") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))))); await channel.EmbedAsync(embed).ConfigureAwait(false); @@ -183,7 +183,7 @@ namespace NadekoBot.Modules.Gambling arr[i] = rng.Next(1, n2 + 1) + add - sub; } - var embed = new EmbedBuilder().WithOkColor().WithDescription($"{umsg.Author.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`") + var embed = new EmbedBuilder().WithOkColor().WithDescription($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString()))))); await channel.EmbedAsync(embed).ConfigureAwait(false); @@ -193,9 +193,9 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task NRoll(IUserMessage umsg, [Remainder] string range) + public async Task NRoll([Remainder] string range) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; try { @@ -215,7 +215,7 @@ namespace NadekoBot.Modules.Gambling rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } - await channel.SendConfirmAsync($"{umsg.Author.Mention} rolled **{rolled}**.").ConfigureAwait(false); + await channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { diff --git a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs index 4c8057d6..5ee97e98 100644 --- a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs +++ b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -25,7 +26,7 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Acro(IUserMessage imsg, int time = 60) + public async Task Acro(int time = 60) { var channel = (ITextChannel)imsg.Channel; @@ -167,11 +168,11 @@ namespace NadekoBot.Modules.Games await End().ConfigureAwait(false); } - private async void PotentialAcro(IMessage arg) + private async void PotentialAcro(SocketMessage arg) { try { - var msg = arg as IUserMessage; + var msg = arg as SocketUserMessage; if (msg == null || msg.Author.IsBot || msg.Channel.Id != channel.Id) return; diff --git a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs index e730b4df..9ec59147 100644 --- a/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/CleverBotCommands.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Services; @@ -46,7 +47,7 @@ namespace NadekoBot.Modules.Games _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); } - public static async Task TryAsk(IUserMessage msg) + public static async Task TryAsk(SocketUserMessage msg) { var channel = msg.Channel as ITextChannel; diff --git a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs index 27afb9f2..d096b452 100644 --- a/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Hangman/HangmanGame.cs @@ -1,4 +1,5 @@ ๏ปฟusing Discord; +using Discord.WebSocket; using NadekoBot.Extensions; using NadekoBot.Services; using Newtonsoft.Json; @@ -128,11 +129,11 @@ namespace NadekoBot.Modules.Games.Commands.Hangman await GameChannel.EmbedAsync(embed.WithOkColor()).ConfigureAwait(false); } - private async void PotentialGuess(IMessage msg) + private async void PotentialGuess(SocketMessage msg) { try { - if (!(msg is IUserMessage)) + if (!(msg is SocketUserMessage)) return; if (msg.Channel != GameChannel) diff --git a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs index 80ac37d5..d7fb96cc 100644 --- a/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PlantAndPickCommands.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using Microsoft.EntityFrameworkCore; using NadekoBot.Attributes; using NadekoBot.Extensions; @@ -62,11 +63,11 @@ namespace NadekoBot.Modules.Games _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); } - private static async void PotentialFlowerGeneration(IMessage imsg) + private static async void PotentialFlowerGeneration(SocketMessage imsg) { try { - var msg = imsg as IUserMessage; + var msg = imsg as SocketUserMessage; if (msg == null || msg.IsAuthor() || msg.Author.IsBot) return; diff --git a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs index 4c2802d0..f7321a72 100644 --- a/src/NadekoBot/Modules/Games/Commands/PollCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/PollCommands.cs @@ -128,12 +128,12 @@ namespace NadekoBot.Modules.Games } } - private async void Vote(IMessage imsg) + private async void Vote(SocketMessage imsg) { try { // has to be a user message - var msg = imsg as IUserMessage; + var msg = imsg as SocketUserMessage; if (msg == null || msg.Author.IsBot) return; diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index ea69ab37..6ca731c7 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Commands; +using Discord.WebSocket; using NadekoBot.Attributes; using NadekoBot.Extensions; using NadekoBot.Modules.Games.Commands.Models; @@ -105,13 +106,13 @@ namespace NadekoBot.Modules.Games NadekoBot.Client.MessageReceived += AnswerReceived; } - private async void AnswerReceived(IMessage imsg) + private async void AnswerReceived(SocketMessage imsg) { try { if (imsg.Author.IsBot) return; - var msg = imsg as IUserMessage; + var msg = imsg as SocketUserMessage; if (msg == null) return; diff --git a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs index 00b3f9ec..83b71e1d 100644 --- a/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs +++ b/src/NadekoBot/Modules/Games/Commands/Trivia/TriviaGame.cs @@ -1,5 +1,6 @@ ๏ปฟusing Discord; using Discord.Net; +using Discord.WebSocket; using NadekoBot.Extensions; using NLog; using System; @@ -141,14 +142,14 @@ namespace NadekoBot.Modules.Games.Trivia try { await channel.SendConfirmAsync("Trivia Game", "Stopping after this question.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } - private async void PotentialGuess(IMessage imsg) + private async void PotentialGuess(SocketMessage imsg) { try { if (imsg.Author.IsBot) return; - var umsg = imsg as IUserMessage; + var umsg = imsg as SocketUserMessage; if (umsg == null) return; diff --git a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs index 7118a2f9..6f43ff83 100644 --- a/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/TriviaCommands.cs @@ -21,13 +21,13 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public Task Trivia([Remainder] string additionalArgs = "") - => Trivia(Context.Message, 10, additionalArgs); + => Trivia(10, additionalArgs); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Trivia(IUserMessage umsg, int winReq = 10, [Remainder] string additionalArgs = "") + public async Task Trivia(int winReq = 10, [Remainder] string additionalArgs = "") { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; var showHints = !additionalArgs.Contains("nohint"); diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index b076033b..a6dbc9ae 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -580,7 +580,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task ReptCurSong(IUserMessage umsg) + public async Task ReptCurSong() { MusicPlayer musicPlayer; @@ -782,7 +782,7 @@ $"{("tracks".SnPl(musicPlayer.Playlist.Count))} | {(int)total.TotalHours}h {tota [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Autoplay(IUserMessage umsg) + public async Task Autoplay() { MusicPlayer musicPlayer; if (!MusicPlayers.TryGetValue(Context.Guild.Id, out musicPlayer)) diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index e29a2fe4..860b4828 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -28,9 +28,9 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Hentai(IUserMessage umsg, [Remainder] string tag = null) + public async Task Hentai([Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; @@ -66,16 +66,16 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task AutoHentai(IUserMessage umsg, int interval = 0, string tags = null) + public async Task AutoHentai(int interval = 0, string tags = null) { Timer t; if (interval == 0) { - if (AutoHentaiTimers.TryRemove(umsg.Channel.Id, out t)) + if (AutoHentaiTimers.TryRemove(Context.Channel.Id, out t)) { t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer - await umsg.Channel.SendConfirmAsync("Autohentai stopped.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("Autohentai stopped.").ConfigureAwait(false); } return; } @@ -90,28 +90,28 @@ namespace NadekoBot.Modules.NSFW try { if (tagsArr == null || tagsArr.Length == 0) - await Hentai(umsg, null).ConfigureAwait(false); + await Hentai(null).ConfigureAwait(false); else - await Hentai(umsg, tagsArr[new NadekoRandom().Next(0, tagsArr.Length)]); + await Hentai(tagsArr[new NadekoRandom().Next(0, tagsArr.Length)]); } catch { } }, null, interval * 1000, interval * 1000); - AutoHentaiTimers.AddOrUpdate(umsg.Channel.Id, t, (key, old) => + AutoHentaiTimers.AddOrUpdate(Context.Channel.Id, t, (key, old) => { old.Change(Timeout.Infinite, Timeout.Infinite); return t; }); - await umsg.Channel.SendConfirmAsync($"Autohentai started. Reposting every {interval}s with one of the following tags:\n{string.Join(", ", tagsArr)}").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"Autohentai started. Reposting every {interval}s with one of the following tags:\n{string.Join(", ", tagsArr)}").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task HentaiBomb(IUserMessage umsg, [Remainder] string tag = null) + public async Task HentaiBomb([Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; tag = "rating%3Aexplicit+" + tag; @@ -133,76 +133,73 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Danbooru(IUserMessage umsg, [Remainder] string tag = null) + public async Task Danbooru([Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var url = await GetDanbooruImageLink(tag).ConfigureAwait(false); if (url == null) - await channel.SendErrorAsync(umsg.Author.Mention + " No results."); + await channel.SendErrorAsync(Context.User.Mention + " No results."); else await channel.EmbedAsync(new EmbedBuilder().WithOkColor() - .WithDescription(umsg.Author.Mention + " " + tag) + .WithDescription(Context.User.Mention + " " + tag) .WithImageUrl(url) .WithFooter(efb => efb.WithText("Danbooru"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Yandere(IUserMessage umsg, [Remainder] string tag = null) - => Searches.Searches.InternalDapiCommand(umsg, tag, Searches.Searches.DapiSearchType.Yandere); + public Task Yandere([Remainder] string tag = null) + => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Yandere); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Konachan(IUserMessage umsg, [Remainder] string tag = null) - => Searches.Searches.InternalDapiCommand(umsg, tag, Searches.Searches.DapiSearchType.Konachan); + public Task Konachan([Remainder] string tag = null) + => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Konachan); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Gelbooru(IUserMessage umsg, [Remainder] string tag = null) - => Searches.Searches.InternalDapiCommand(umsg, tag, Searches.Searches.DapiSearchType.Gelbooru); + public Task Gelbooru([Remainder] string tag = null) + => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Gelbooru); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Rule34(IUserMessage umsg, [Remainder] string tag = null) - => Searches.Searches.InternalDapiCommand(umsg, tag, Searches.Searches.DapiSearchType.Rule34); + public Task Rule34([Remainder] string tag = null) + => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Rule34); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task E621(IUserMessage umsg, [Remainder] string tag = null) + public async Task E621([Remainder] string tag = null) { - var channel = (ITextChannel)umsg.Channel; + var channel = (ITextChannel)Context.Channel; tag = tag?.Trim() ?? ""; var url = await GetE621ImageLink(tag).ConfigureAwait(false); if (url == null) - await channel.SendErrorAsync(umsg.Author.Mention + " No results."); + await channel.SendErrorAsync(Context.User.Mention + " No results."); else await channel.EmbedAsync(new EmbedBuilder().WithOkColor() - .WithDescription(umsg.Author.Mention + " " + tag) + .WithDescription(Context.User.Mention + " " + tag) .WithImageUrl(url) .WithFooter(efb => efb.WithText("e621"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Cp(IUserMessage umsg) + public async Task Cp() { - var channel = (ITextChannel)umsg.Channel; - - await channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); + await Context.Channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Boobs(IUserMessage umsg) + public async Task Boobs() { - var channel = (ITextChannel)umsg.Channel; try { JToken obj; @@ -210,20 +207,18 @@ namespace NadekoBot.Modules.NSFW { obj = JArray.Parse(await http.GetStringAsync($"http://api.oboobs.ru/boobs/{ new NadekoRandom().Next(0, 10229) }").ConfigureAwait(false))[0]; } - await channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"http://media.oboobs.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync(ex.Message).ConfigureAwait(false); + await Context.Channel.SendErrorAsync(ex.Message).ConfigureAwait(false); } } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Butts(IUserMessage umsg) + public async Task Butts() { - var channel = (ITextChannel)umsg.Channel; - try { JToken obj; @@ -231,11 +226,11 @@ namespace NadekoBot.Modules.NSFW { obj = JArray.Parse(await http.GetStringAsync($"http://api.obutts.ru/butts/{ new NadekoRandom().Next(0, 4222) }").ConfigureAwait(false))[0]; } - await channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); + await Context.Channel.SendMessageAsync($"http://media.obutts.ru/{ obj["preview"].ToString() }").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync(ex.Message).ConfigureAwait(false); + await Context.Channel.SendErrorAsync(ex.Message).ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index bbb6db35..85a8f858 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -475,7 +475,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public async Task Hashtag(IUserMessage umsg, [Remainder] string query = null) + public async Task Hashtag([Remainder] string query = null) { var arg = query; if (string.IsNullOrWhiteSpace(arg)) @@ -551,7 +551,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] - public Task Safebooru(IUserMessage umsg, [Remainder] string tag = null) + public Task Safebooru([Remainder] string tag = null) => InternalDapiCommand(umsg, tag, DapiSearchType.Safebooru); [NadekoCommand, Usage, Description, Aliases] From d0e7a0c404d87a50c851111c86d364678d59c15e Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 13:28:35 +0100 Subject: [PATCH 26/30] compiles and runs --- src/NadekoBot/Modules/Games/Commands/Acropobia.cs | 2 +- src/NadekoBot/Modules/Searches/Searches.cs | 2 +- src/NadekoBot/Modules/Utility/Utility.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs index 5ee97e98..4160754b 100644 --- a/src/NadekoBot/Modules/Games/Commands/Acropobia.cs +++ b/src/NadekoBot/Modules/Games/Commands/Acropobia.cs @@ -28,7 +28,7 @@ namespace NadekoBot.Modules.Games [RequireContext(ContextType.Guild)] public async Task Acro(int time = 60) { - var channel = (ITextChannel)imsg.Channel; + var channel = (ITextChannel)Context.Channel; var game = new AcrophobiaGame(channel, time); if (AcrophobiaGames.TryAdd(channel.Id, game)) diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 85a8f858..7ac8f63e 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -552,7 +552,7 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public Task Safebooru([Remainder] string tag = null) - => InternalDapiCommand(umsg, tag, DapiSearchType.Safebooru); + => InternalDapiCommand(Context.Message, tag, DapiSearchType.Safebooru); [NadekoCommand, Usage, Description, Aliases] public async Task Wiki([Remainder] string query = null) diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index f9ef6a33..d6dadc45 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -36,7 +36,7 @@ namespace NadekoBot.Modules.Utility .WithAuthor(eab => eab.WithIconUrl("https://togethertube.com/assets/img/favicons/favicon-32x32.png") .WithName("Together Tube") .WithUrl("https://togethertube.com/")) - .WithDescription($"{imsg.Author.Mention} Here is your room link:\n{target}")); + .WithDescription($"{Context.User.Mention} Here is your room link:\n{target}")); } [NadekoCommand, Usage, Description, Aliases] From 2d2a7f765fe521d280a81dac0f2fcb62375ddd61 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 13:57:38 +0100 Subject: [PATCH 27/30] A lot of fixes to constructors --- .../Modules/Administration/Administration.cs | 4 -- .../Administration/Commands/LogCommand.cs | 43 +++++++------------ .../Administration/Commands/Migration.cs | 4 +- .../Administration/Commands/SelfCommands.cs | 13 ++---- .../CustomReactions/CustomReactions.cs | 3 -- .../Modules/Gambling/Commands/DrawCommand.cs | 9 +--- .../Modules/Games/Commands/HangmanCommands.cs | 6 +-- .../Games/Commands/SpeedTypingCommands.cs | 8 +--- src/NadekoBot/Modules/Music/Music.cs | 9 ++-- src/NadekoBot/Modules/NSFW/NSFW.cs | 4 -- .../Modules/Permissions/Permissions.cs | 4 -- src/NadekoBot/Modules/Pokemon/Pokemon.cs | 8 ++-- .../Searches/Commands/PlaceCommands.cs | 6 +-- .../Modules/Utility/Commands/Remind.cs | 10 ++--- .../Utility/Commands/UnitConversion.cs | 6 +-- src/NadekoBot/Modules/Utility/Utility.cs | 5 --- 16 files changed, 38 insertions(+), 104 deletions(-) diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 18e7a7a7..70aadf8a 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -29,10 +29,6 @@ namespace NadekoBot.Modules.Administration private new static Logger _log { get; } - public Administration() : base() - { - } - static Administration() { _log = LogManager.GetCurrentClassLogger(); diff --git a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs index 2bcfb403..04bde59b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs +++ b/src/NadekoBot/Modules/Administration/Commands/LogCommand.cs @@ -67,10 +67,7 @@ namespace NadekoBot.Modules.Administration sw.Stop(); _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); - } - public LogCommands() - { //_client.MessageReceived += _client_MessageReceived; _client.MessageUpdated += _client_MessageUpdated; _client.MessageDeleted += _client_MessageDeleted; @@ -91,7 +88,7 @@ namespace NadekoBot.Modules.Administration MuteCommands.UserUnmuted += MuteCommands_UserUnmuted; } - private async void _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) + private static async void _client_UserVoiceStateUpdated_TTS(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { try { @@ -133,7 +130,7 @@ namespace NadekoBot.Modules.Administration catch { } } - private async void MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType) + private static async void MuteCommands_UserMuted(IGuildUser usr, MuteCommands.MuteType muteType) { try { @@ -163,7 +160,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void MuteCommands_UserUnmuted(IGuildUser usr, MuteCommands.MuteType muteType) + private static async void MuteCommands_UserUnmuted(IGuildUser usr, MuteCommands.MuteType muteType) { try { @@ -226,13 +223,12 @@ namespace NadekoBot.Modules.Administration //punishment = "BANNED"; } await logChannel.SendMessageAsync(String.Join("\n", users.Select(user => $"โ€ผ๏ธ {Format.Bold(user.ToString())} got **{punishment}** due to __**{protection}**__ protection on **{user.Guild.Name}** server."))) - //await logChannel.SendMessageAsync(String.Join("\n",users.Select(user=>$"{Format.Bold(user.ToString())} was **{punishment}** due to `{protection}` protection on **{user.Guild.Name}** server."))) .ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserUpdated(SocketUser uBefore, SocketUser uAfter) + private static async void _client_UserUpdated(SocketUser uBefore, SocketUser uAfter) { try { @@ -254,26 +250,21 @@ namespace NadekoBot.Modules.Administration string str = $"๐Ÿ•”`{prettyCurrentTime}`"; if (before.Username != after.Username) - //str += $"**Name Changed**`{before.Username}#{before.Discriminator}`\n\t\t`New:`{after.ToString()}`"; str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Name Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`New:` **{after.ToString()}**"; else if (before.Nickname != after.Nickname) str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Nickname Changed |** ๐Ÿ†” `{before.Id}`\n\t\t`Old:` **{before.Nickname}#{before.Discriminator}**\n\t\t`New:` **{after.Nickname}#{after.Discriminator}**"; - //str += $"**Nickname Changed**`{before.Username}#{before.Discriminator}`\n\t\t`Old:` {before.Nickname}#{before.Discriminator}\n\t\t`New:` {after.Nickname}#{after.Discriminator}"; else if (before.AvatarUrl != after.AvatarUrl) - //str += $"**Avatar Changed**๐Ÿ‘ค`{before.Username}#{before.Discriminator}`\n\t {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; - str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿ–ผ {await _google.ShortenUrl(before.AvatarUrl)} `=>` {await _google.ShortenUrl(after.AvatarUrl)}"; + str += $"๐Ÿ‘ค__**{before.Username}#{before.Discriminator}**__ **| Avatar Changed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿ–ผ {await NadekoBot.Google.ShortenUrl(before.AvatarUrl)} `=>` {await NadekoBot.Google.ShortenUrl(after.AvatarUrl)}"; else if (!before.RoleIds.SequenceEqual(after.RoleIds)) { if (before.RoleIds.Count < after.RoleIds.Count) { var diffRoles = after.RoleIds.Where(r => !before.RoleIds.Contains(r)).Select(r => "**" + before.Guild.GetRole(r).Name + "**"); - //str += $"**User's Roles changed โš”โž•**๐Ÿ‘ค`{before.ToString()}`\n\tNow has {string.Join(", ", diffRoles)} role."; str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Added |** ๐Ÿ†” `{before.Id}`\n\tโœ… {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; } else if (before.RoleIds.Count > after.RoleIds.Count) { var diffRoles = before.RoleIds.Where(r => !after.RoleIds.Contains(r)).Select(r => "**" + before.Guild.GetRole(r).Name + "**"); - //str += $"**User's Roles changed **`{before.ToString()}`\n\tNo longer has {string.Join(", ", diffRoles)} role."; str += $"๐Ÿ‘ค__**{before.ToString()}**__ **| User's Role Removed |** ๐Ÿ†” `{before.Id}`\n\t๐Ÿšฎ {string.Join(", ", diffRoles).SanitizeMentions()}\n\t\tโš” **`{string.Join(", ", after.GetRoles().Select(r => r.Name)).SanitizeMentions()}`** โš”"; } } @@ -284,7 +275,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_ChannelUpdated(IChannel cbefore, IChannel cafter) + private static async void _client_ChannelUpdated(IChannel cbefore, IChannel cafter) { try { @@ -303,12 +294,10 @@ namespace NadekoBot.Modules.Administration if ((logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.ChannelUpdated)) == null) return; if (before.Name != after.Name) - //await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Name Changed** `#{after.Name}` ({after.Id}) await logChannel.SendMessageAsync($@"๐Ÿ•“`{prettyCurrentTime}`โ„น๏ธ **| Channel Name Changed |** #โƒฃ `{after.Name} ({after.Id})` `Old:` {before.Name} **`New:`** {after.Name}").ConfigureAwait(false); else if ((before as ITextChannel).Topic != (after as ITextChannel).Topic) - //await logChannel.SendMessageAsync($@"`{prettyCurrentTime}` **Channel Topic Changed** `#{after.Name}` ({after.Id}) await logChannel.SendMessageAsync($@"๐Ÿ•˜`{prettyCurrentTime}`โ„น๏ธ **| Channel Topic Changed |** #โƒฃ `{after.Name} ({after.Id})` `Old:` {((ITextChannel)before).Topic} **`New:`** {((ITextChannel)after).Topic}").ConfigureAwait(false); @@ -316,7 +305,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_ChannelDestroyed(IChannel ich) + private static async void _client_ChannelDestroyed(IChannel ich) { try { @@ -339,7 +328,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_ChannelCreated(IChannel ich) + private static async void _client_ChannelCreated(IChannel ich) { try { @@ -361,7 +350,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) + private static async void _client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState before, SocketVoiceState after) { try { @@ -406,7 +395,7 @@ namespace NadekoBot.Modules.Administration } } - private async void _client_UserPresenceUpdated(Optional optGuild, SocketUser usr, SocketPresence before, SocketPresence after) + private static async void _client_UserPresenceUpdated(Optional optGuild, SocketUser usr, SocketPresence before, SocketPresence after) { try { @@ -435,7 +424,7 @@ namespace NadekoBot.Modules.Administration catch { } } - private async void _client_UserLeft(IGuildUser usr) + private static async void _client_UserLeft(IGuildUser usr) { try { @@ -452,7 +441,7 @@ namespace NadekoBot.Modules.Administration catch { } } - private async void _client_UserJoined(IGuildUser usr) + private static async void _client_UserJoined(IGuildUser usr) { try { @@ -470,7 +459,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserUnbanned(IUser usr, IGuild guild) + private static async void _client_UserUnbanned(IUser usr, IGuild guild) { try { @@ -488,7 +477,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_UserBanned(IUser usr, IGuild guild) + private static async void _client_UserBanned(IUser usr, IGuild guild) { try { @@ -505,7 +494,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_MessageDeleted(ulong arg1, Optional imsg) + private static async void _client_MessageDeleted(ulong arg1, Optional imsg) { try @@ -536,7 +525,7 @@ namespace NadekoBot.Modules.Administration catch (Exception ex) { _log.Warn(ex); } } - private async void _client_MessageUpdated(Optional optmsg, SocketMessage imsg2) + private static async void _client_MessageUpdated(Optional optmsg, SocketMessage imsg2) { try { diff --git a/src/NadekoBot/Modules/Administration/Commands/Migration.cs b/src/NadekoBot/Modules/Administration/Commands/Migration.cs index 4e7bf469..433cfc7b 100644 --- a/src/NadekoBot/Modules/Administration/Commands/Migration.cs +++ b/src/NadekoBot/Modules/Administration/Commands/Migration.cs @@ -24,9 +24,9 @@ namespace NadekoBot.Modules.Administration { private const int CURRENT_VERSION = 1; - private Logger _log { get; } + private static Logger _log { get; } - public Migration() + static Migration() { _log = LogManager.GetCurrentClassLogger(); } diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index 04d9f61c..6e76fd1a 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -11,28 +11,21 @@ namespace NadekoBot.Modules.Administration [Group] class SelfCommands : ModuleBase { - private ShardedDiscordClient _client; - - public SelfCommands() - { - this._client = NadekoBot.Client; - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] public async Task Leave([Remainder] string guildStr) { guildStr = guildStr.Trim().ToUpperInvariant(); - var server = _client.GetGuilds().FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == guildStr) ?? - _client.GetGuilds().FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == guildStr); + var server = NadekoBot.Client.GetGuilds().FirstOrDefault(g => g.Id.ToString().Trim().ToUpperInvariant() == guildStr) ?? + NadekoBot.Client.GetGuilds().FirstOrDefault(g => g.Name.Trim().ToUpperInvariant() == guildStr); if (server == null) { await Context.Channel.SendErrorAsync("โš ๏ธ Cannot find that server").ConfigureAwait(false); return; } - if (server.OwnerId != _client.CurrentUser().Id) + if (server.OwnerId != NadekoBot.Client.CurrentUser().Id) { await server.LeaveAsync().ConfigureAwait(false); await Context.Channel.SendConfirmAsync("โœ… Left server " + server.Name).ConfigureAwait(false); diff --git a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs index 7b331bd7..26a1b902 100644 --- a/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs +++ b/src/NadekoBot/Modules/CustomReactions/CustomReactions.cs @@ -36,9 +36,6 @@ namespace NadekoBot.Modules.CustomReactions sw.Stop(); _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); } - public CustomReactions() : base() - { - } public void ClearStats() => ReactionStats.Clear(); diff --git a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs index a57a4872..adbe4913 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DrawCommand.cs @@ -21,14 +21,7 @@ namespace NadekoBot.Modules.Gambling { private static readonly ConcurrentDictionary AllDecks = new ConcurrentDictionary(); - - public DrawCommands() - { - _log = LogManager.GetCurrentClassLogger(); - } - private const string cardsPath = "data/images/cards"; - private Logger _log { get; } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] @@ -42,7 +35,7 @@ namespace NadekoBot.Modules.Gambling { if (cards.CardPool.Count == 0 && i != 0) { - try { await Context.Channel.SendErrorAsync("No more cards in a deck.").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + try { await Context.Channel.SendErrorAsync("No more cards in a deck.").ConfigureAwait(false); } catch { } break; } var currentCard = cards.DrawACard(); diff --git a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs index db631ec5..eba11193 100644 --- a/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/HangmanCommands.cs @@ -18,15 +18,11 @@ namespace NadekoBot.Modules.Games //channelId, game public static ConcurrentDictionary HangmanGames { get; } = new ConcurrentDictionary(); + private static string typesStr { get; } = ""; static HangmanCommands() { _log = LogManager.GetCurrentClassLogger(); - } - - string typesStr { get; } = ""; - public HangmanCommands() - { typesStr = $"`List of \"{NadekoBot.ModulePrefixes[typeof(Games).Name]}hangman\" term types:`\n" + String.Join(", ", Enum.GetNames(typeof(HangmanTermPool.HangmanTermType))); } diff --git a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs index 6ca731c7..bb69063f 100644 --- a/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/SpeedTypingCommands.cs @@ -148,7 +148,6 @@ namespace NadekoBot.Modules.Games [Group] public class SpeedTypingCommands : ModuleBase { - public static List TypingArticles { get; } = new List(); const string typingArticlesPath = "data/typing_articles.json"; @@ -157,12 +156,7 @@ namespace NadekoBot.Modules.Games { try { TypingArticles = JsonConvert.DeserializeObject>(File.ReadAllText(typingArticlesPath)); } catch { } } - public static ConcurrentDictionary RunningContests; - - public SpeedTypingCommands() - { - RunningContests = new ConcurrentDictionary(); - } + public static ConcurrentDictionary RunningContests = new ConcurrentDictionary(); [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] diff --git a/src/NadekoBot/Modules/Music/Music.cs b/src/NadekoBot/Modules/Music/Music.cs index a6dbc9ae..89ca9451 100644 --- a/src/NadekoBot/Modules/Music/Music.cs +++ b/src/NadekoBot/Modules/Music/Music.cs @@ -27,7 +27,7 @@ namespace NadekoBot.Modules.Music public const string MusicDataPath = "data/musicdata"; - public Music() : base() + static Music() { //it can fail if its currenctly opened or doesn't exist. Either way i don't care try { Directory.Delete(MusicDataPath, true); } catch { } @@ -37,7 +37,7 @@ namespace NadekoBot.Modules.Music Directory.CreateDirectory(MusicDataPath); } - private async void Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) + private static async void Client_UserVoiceStateUpdated(SocketUser iusr, SocketVoiceState oldState, SocketVoiceState newState) { var usr = iusr as SocketGuildUser; if (usr == null || @@ -60,10 +60,7 @@ namespace NadekoBot.Modules.Music player.TogglePause(); } } - catch (Exception ex) - { - _log.Warn(ex); - } + catch { } } [NadekoCommand, Usage, Description, Aliases] diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 860b4828..641c3514 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -22,10 +22,6 @@ namespace NadekoBot.Modules.NSFW //ulong/cancel private static ConcurrentDictionary AutoHentaiTimers { get; } = new ConcurrentDictionary(); - public NSFW() : base() - { - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Hentai([Remainder] string tag = null) diff --git a/src/NadekoBot/Modules/Permissions/Permissions.cs b/src/NadekoBot/Modules/Permissions/Permissions.cs index 505b55e1..d2b282aa 100644 --- a/src/NadekoBot/Modules/Permissions/Permissions.cs +++ b/src/NadekoBot/Modules/Permissions/Permissions.cs @@ -49,10 +49,6 @@ namespace NadekoBot.Modules.Permissions _log.Debug($"Loaded in {sw.Elapsed.TotalSeconds:F2}s"); } - public Permissions() : base() - { - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Verbose(PermissionAction action) diff --git a/src/NadekoBot/Modules/Pokemon/Pokemon.cs b/src/NadekoBot/Modules/Pokemon/Pokemon.cs index 51a4f1af..7f51deb0 100644 --- a/src/NadekoBot/Modules/Pokemon/Pokemon.cs +++ b/src/NadekoBot/Modules/Pokemon/Pokemon.cs @@ -24,18 +24,18 @@ namespace NadekoBot.Modules.Pokemon public const string PokemonTypesFile = "data/pokemon_types.json"; - private Logger _pokelog { get; } + private static new Logger _log { get; } - public Pokemon() : base() + static Pokemon() { - _pokelog = LogManager.GetCurrentClassLogger(); + _log = LogManager.GetCurrentClassLogger(); if (File.Exists(PokemonTypesFile)) { PokemonTypes = JsonConvert.DeserializeObject>(File.ReadAllText(PokemonTypesFile)); } else { - _pokelog.Warn(PokemonTypesFile + " is missing. Pokemon types not loaded."); + _log.Warn(PokemonTypesFile + " is missing. Pokemon types not loaded."); } } diff --git a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs index df53ae32..af8a1fb3 100644 --- a/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/PlaceCommands.cs @@ -12,11 +12,7 @@ namespace NadekoBot.Modules.Searches [Group] public class PlaceCommands : ModuleBase { - string typesStr { get; } = ""; - public PlaceCommands() - { - typesStr = $"`List of \"{NadekoBot.ModulePrefixes[typeof(Searches).Name]}place\" tags:`\n" + String.Join(", ", Enum.GetNames(typeof(PlaceType))); - } + private static string typesStr { get; } = $"`List of \"{NadekoBot.ModulePrefixes[typeof(Searches).Name]}place\" tags:`\n" + String.Join(", ", Enum.GetNames(typeof(PlaceType))); public enum PlaceType { diff --git a/src/NadekoBot/Modules/Utility/Commands/Remind.cs b/src/NadekoBot/Modules/Utility/Commands/Remind.cs index 92bbb3fb..6cb3965f 100644 --- a/src/NadekoBot/Modules/Utility/Commands/Remind.cs +++ b/src/NadekoBot/Modules/Utility/Commands/Remind.cs @@ -22,17 +22,17 @@ namespace NadekoBot.Modules.Utility Regex regex = new Regex(@"^(?:(?\d)mo)?(?:(?\d)w)?(?:(?\d{1,2})d)?(?:(?\d{1,2})h)?(?:(?\d{1,2})m)?$", RegexOptions.Compiled | RegexOptions.Multiline); - private string RemindMessageFormat { get; } + private static string RemindMessageFormat { get; } - IDictionary> replacements = new Dictionary> + private static IDictionary> replacements = new Dictionary> { { "%message%" , (r) => r.Message }, { "%user%", (r) => $"<@!{r.UserId}>" }, { "%target%", (r) => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>"} }; - private Logger _log { get; } + private static Logger _log { get; } - public RemindCommands() + static RemindCommands() { _log = LogManager.GetCurrentClassLogger(); List reminders; @@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Utility } } - private async Task StartReminder(Reminder r) + private static async Task StartReminder(Reminder r) { var now = DateTime.Now; var twoMins = new TimeSpan(0, 2, 0); diff --git a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs index 97beb8c3..41ca8133 100644 --- a/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs +++ b/src/NadekoBot/Modules/Utility/Commands/UnitConversion.cs @@ -54,15 +54,11 @@ namespace NadekoBot.Modules.Utility { _log.Warn("Could not load units: " + e.Message); } - } - public UnitConverterCommands() - { _timer = new Timer(async (obj) => await UpdateCurrency(), null, (int)updateInterval.TotalMilliseconds, (int)updateInterval.TotalMilliseconds); - } - public async Task UpdateCurrency() + public static async Task UpdateCurrency() { try { diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index d6dadc45..d98d13d0 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -16,11 +16,6 @@ namespace NadekoBot.Modules.Utility [NadekoModule("Utility", ".")] public partial class Utility : DiscordModule { - public Utility() : base() - { - - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task TogetherTube() From cc6798496c0f09618f20f3a84587683b330039f3 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 14:06:32 +0100 Subject: [PATCH 28/30] Autohentai no longer posts errors --- src/NadekoBot/Modules/NSFW/NSFW.cs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index 641c3514..f3300b7e 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -19,15 +19,10 @@ namespace NadekoBot.Modules.NSFW [NadekoModule("NSFW", "~")] public class NSFW : DiscordModule { - //ulong/cancel private static ConcurrentDictionary AutoHentaiTimers { get; } = new ConcurrentDictionary(); - [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] - public async Task Hentai([Remainder] string tag = null) + private async Task InternalHentai(IMessageChannel channel, string tag, bool noError) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; tag = "rating%3Aexplicit+" + tag; @@ -54,12 +49,17 @@ namespace NadekoBot.Modules.NSFW var link = await provider.ConfigureAwait(false); if (string.IsNullOrWhiteSpace(link)) await channel.SendErrorAsync("No results found.").ConfigureAwait(false); - else + else if (!noError) await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithImageUrl(link) .WithDescription("Tag: " + tag)).ConfigureAwait(false); } + [NadekoCommand, Usage, Description, Aliases] + [RequireContext(ContextType.Guild)] + public Task Hentai([Remainder] string tag = null) => + InternalHentai(Context.Channel, tag, false); + [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task AutoHentai(int interval = 0, string tags = null) @@ -86,9 +86,9 @@ namespace NadekoBot.Modules.NSFW try { if (tagsArr == null || tagsArr.Length == 0) - await Hentai(null).ConfigureAwait(false); + await InternalHentai(Context.Channel, null, true).ConfigureAwait(false); else - await Hentai(tagsArr[new NadekoRandom().Next(0, tagsArr.Length)]); + await InternalHentai(Context.Channel, tagsArr[new NadekoRandom().Next(0, tagsArr.Length)], true); } catch { } }, null, interval * 1000, interval * 1000); From 96e57d5dbf48faa85c7511d2ed24489f5f252af4 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 14:28:59 +0100 Subject: [PATCH 29/30] Changed my mind. offline stream notifs won't be deleted --- .../Modules/Searches/Commands/StreamNotificationCommands.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs index fc315327..36829953 100644 --- a/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/StreamNotificationCommands.cs @@ -111,8 +111,6 @@ namespace NadekoBot.Modules.Searches try { var msg = await channel.EmbedAsync(fs.GetEmbed(newStatus)).ConfigureAwait(false); - if (!newStatus.IsLive) - msg.DeleteAfter(60); } catch { } } From d9e3e2aefa35a1395d9d24762eb468b29fdd6a48 Mon Sep 17 00:00:00 2001 From: Kwoth Date: Sun, 1 Jan 2017 16:39:24 +0100 Subject: [PATCH 30/30] Commands for which it make sense to be able to be ran in DMs can now be ran in DMs --- .../Modules/Administration/Administration.cs | 122 --------------- .../Administration/Commands/SelfCommands.cs | 130 +++++++++++++++- .../Gambling/Commands/DiceRollCommand.cs | 33 +--- .../Gambling/Commands/FlipCoinCommand.cs | 9 +- src/NadekoBot/Modules/Gambling/Gambling.cs | 28 ++-- .../Modules/Games/Commands/LeetCommands.cs | 5 +- src/NadekoBot/Modules/Games/Games.cs | 4 - src/NadekoBot/Modules/NSFW/NSFW.cs | 18 +-- .../Searches/Commands/AnimeSearchCommands.cs | 9 +- .../Modules/Searches/Commands/OsuCommands.cs | 2 - src/NadekoBot/Modules/Searches/Searches.cs | 9 +- src/NadekoBot/Modules/Trello/Trello.cs | 145 ------------------ src/NadekoBot/Modules/Utility/Utility.cs | 10 +- src/NadekoBot/Services/CurrencyHandler.cs | 2 +- 14 files changed, 158 insertions(+), 368 deletions(-) delete mode 100644 src/NadekoBot/Modules/Trello/Trello.cs diff --git a/src/NadekoBot/Modules/Administration/Administration.cs b/src/NadekoBot/Modules/Administration/Administration.cs index 70aadf8a..91c952a6 100644 --- a/src/NadekoBot/Modules/Administration/Administration.cs +++ b/src/NadekoBot/Modules/Administration/Administration.cs @@ -469,128 +469,6 @@ namespace NadekoBot.Modules.Administration await Context.Channel.DeleteMessagesAsync(enumerable).ConfigureAwait(false); } - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task Die() - { - try { await Context.Channel.SendConfirmAsync("โ„น๏ธ **Shutting down.**").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } - await Task.Delay(2000).ConfigureAwait(false); - Environment.Exit(0); - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task SetName([Remainder] string newName) - { - if (string.IsNullOrWhiteSpace(newName)) - return; - - await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Username = newName).ConfigureAwait(false); - - await Context.Channel.SendConfirmAsync($"โ„น๏ธ Successfully changed name to **{newName}**").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task SetAvatar([Remainder] string img = null) - { - if (string.IsNullOrWhiteSpace(img)) - return; - - using (var http = new HttpClient()) - { - using (var sr = await http.GetStreamAsync(img)) - { - var imgStream = new MemoryStream(); - await sr.CopyToAsync(imgStream); - imgStream.Position = 0; - - await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); - } - } - - await Context.Channel.SendConfirmAsync("๐Ÿ†’ **New avatar set.**").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task SetGame([Remainder] string game = null) - { - game = game ?? ""; - - await NadekoBot.Client.SetGame(game).ConfigureAwait(false); - - await Context.Channel.SendConfirmAsync("๐Ÿ‘พ **New game set.**").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task SetStream(string url, [Remainder] string name = null) - { - name = name ?? ""; - - await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); - - await Context.Channel.SendConfirmAsync("โ„น๏ธ **New stream set.**").ConfigureAwait(false); - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task Send(string where, [Remainder] string msg = null) - { - if (string.IsNullOrWhiteSpace(msg)) - return; - - var ids = where.Split('|'); - if (ids.Length != 2) - return; - var sid = ulong.Parse(ids[0]); - var server = NadekoBot.Client.GetGuilds().Where(s => s.Id == sid).FirstOrDefault(); - - if (server == null) - return; - - if (ids[1].ToUpperInvariant().StartsWith("C:")) - { - var cid = ulong.Parse(ids[1].Substring(2)); - var ch = (await server.GetTextChannelsAsync()).Where(c => c.Id == cid).FirstOrDefault(); - if (ch == null) - { - return; - } - await ch.SendMessageAsync(msg).ConfigureAwait(false); - } - else if (ids[1].ToUpperInvariant().StartsWith("U:")) - { - var uid = ulong.Parse(ids[1].Substring(2)); - var user = server.Users.Where(u => u.Id == uid).FirstOrDefault(); - if (user == null) - { - return; - } - await user.SendMessageAsync(msg).ConfigureAwait(false); - } - else - { - await Context.Channel.SendErrorAsync("โš ๏ธ Invalid format.").ConfigureAwait(false); - } - } - - [NadekoCommand, Usage, Description, Aliases] - [OwnerOnly] - public async Task Announce([Remainder] string message) - { - var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g => - g.GetDefaultChannelAsync() - )).ConfigureAwait(false); - if (channels == null) - return; - await Task.WhenAll(channels.Where(c => c != null).Select(c => c.SendConfirmAsync($"๐Ÿ†• Message from {Context.User} `[Bot Owner]`:", message))) - .ConfigureAwait(false); - - await Context.Channel.SendConfirmAsync("๐Ÿ†—").ConfigureAwait(false); - } - [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] diff --git a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs index 6e76fd1a..589fa49a 100644 --- a/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs +++ b/src/NadekoBot/Modules/Administration/Commands/SelfCommands.cs @@ -1,7 +1,11 @@ -๏ปฟusing Discord.Commands; +๏ปฟusing Discord; +using Discord.Commands; using NadekoBot.Attributes; using NadekoBot.Extensions; +using System; +using System.IO; using System.Linq; +using System.Net.Http; using System.Threading.Tasks; namespace NadekoBot.Modules.Administration @@ -12,7 +16,6 @@ namespace NadekoBot.Modules.Administration class SelfCommands : ModuleBase { [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [OwnerOnly] public async Task Leave([Remainder] string guildStr) { @@ -36,6 +39,129 @@ namespace NadekoBot.Modules.Administration await Context.Channel.SendConfirmAsync("Deleted server " + server.Name).ConfigureAwait(false); } } + + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task Die() + { + try { await Context.Channel.SendConfirmAsync("โ„น๏ธ **Shutting down.**").ConfigureAwait(false); } catch (Exception ex) { _log.Warn(ex); } + await Task.Delay(2000).ConfigureAwait(false); + Environment.Exit(0); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task SetName([Remainder] string newName) + { + if (string.IsNullOrWhiteSpace(newName)) + return; + + await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Username = newName).ConfigureAwait(false); + + await Context.Channel.SendConfirmAsync($"โ„น๏ธ Successfully changed name to **{newName}**").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task SetAvatar([Remainder] string img = null) + { + if (string.IsNullOrWhiteSpace(img)) + return; + + using (var http = new HttpClient()) + { + using (var sr = await http.GetStreamAsync(img)) + { + var imgStream = new MemoryStream(); + await sr.CopyToAsync(imgStream); + imgStream.Position = 0; + + await NadekoBot.Client.CurrentUser().ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false); + } + } + + await Context.Channel.SendConfirmAsync("๐Ÿ†’ **New avatar set.**").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task SetGame([Remainder] string game = null) + { + game = game ?? ""; + + await NadekoBot.Client.SetGame(game).ConfigureAwait(false); + + await Context.Channel.SendConfirmAsync("๐Ÿ‘พ **New game set.**").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task SetStream(string url, [Remainder] string name = null) + { + name = name ?? ""; + + await NadekoBot.Client.SetStream(name, url).ConfigureAwait(false); + + await Context.Channel.SendConfirmAsync("โ„น๏ธ **New stream set.**").ConfigureAwait(false); + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task Send(string where, [Remainder] string msg = null) + { + if (string.IsNullOrWhiteSpace(msg)) + return; + + var ids = where.Split('|'); + if (ids.Length != 2) + return; + var sid = ulong.Parse(ids[0]); + var server = NadekoBot.Client.GetGuilds().Where(s => s.Id == sid).FirstOrDefault(); + + if (server == null) + return; + + if (ids[1].ToUpperInvariant().StartsWith("C:")) + { + var cid = ulong.Parse(ids[1].Substring(2)); + var ch = (await server.GetTextChannelsAsync()).Where(c => c.Id == cid).FirstOrDefault(); + if (ch == null) + { + return; + } + await ch.SendMessageAsync(msg).ConfigureAwait(false); + } + else if (ids[1].ToUpperInvariant().StartsWith("U:")) + { + var uid = ulong.Parse(ids[1].Substring(2)); + var user = server.Users.Where(u => u.Id == uid).FirstOrDefault(); + if (user == null) + { + return; + } + await user.SendMessageAsync(msg).ConfigureAwait(false); + } + else + { + await Context.Channel.SendErrorAsync("โš ๏ธ Invalid format.").ConfigureAwait(false); + } + } + + [NadekoCommand, Usage, Description, Aliases] + [OwnerOnly] + public async Task Announce([Remainder] string message) + { + var channels = await Task.WhenAll(NadekoBot.Client.GetGuilds().Select(g => + g.GetDefaultChannelAsync() + )).ConfigureAwait(false); + if (channels == null) + return; + await Task.WhenAll(channels.Where(c => c != null).Select(c => c.SendConfirmAsync($"๐Ÿ†• Message from {Context.User} `[Bot Owner]`:", message))) + .ConfigureAwait(false); + + await Context.Channel.SendConfirmAsync("๐Ÿ†—").ConfigureAwait(false); + } } } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs index dcc2c52f..90c54e2d 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/DiceRollCommand.cs @@ -25,12 +25,8 @@ namespace NadekoBot.Modules.Gambling private readonly char[] fateRolls = new[] { '-', ' ', '+' }; [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Roll() { - var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; var rng = new NadekoRandom(); var gen = rng.Next(1, 101); @@ -48,7 +44,7 @@ namespace NadekoBot.Modules.Gambling catch { return new MemoryStream(); } }); - await channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); + await Context.Channel.SendFileAsync(imageStream, "dice.png", $"{Context.User.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); } public enum RollOrderType @@ -58,7 +54,6 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(0)] public async Task Roll(int num) { @@ -67,7 +62,6 @@ namespace NadekoBot.Modules.Gambling [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(0)] public async Task Rolluo(int num) { @@ -75,7 +69,6 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(1)] public async Task Roll(string arg) { @@ -83,7 +76,6 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [Priority(1)] public async Task Rolluo(string arg) { @@ -92,13 +84,9 @@ namespace NadekoBot.Modules.Gambling private async Task InternalRoll( int num, bool ordered) { - var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - if (num < 1 || num > 30) { - await channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } @@ -136,15 +124,11 @@ namespace NadekoBot.Modules.Gambling var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; - await channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); + await Context.Channel.SendFileAsync(ms, "dice.png", $"{Context.User.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); } private async Task InternallDndRoll(string arg, bool ordered) { - var channel = (ITextChannel)Context.Channel; - if (channel == null) - return; - Match match; int n1; int n2; @@ -163,7 +147,7 @@ namespace NadekoBot.Modules.Gambling var embed = new EmbedBuilder().WithOkColor().WithDescription($"{Context.User.Mention} rolled {n1} fate {(n1 == 1 ? "die" : "dice")}.") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))))); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } else if ((match = dndRegex.Match(arg)).Length != 0) { @@ -186,17 +170,14 @@ namespace NadekoBot.Modules.Gambling var embed = new EmbedBuilder().WithOkColor().WithDescription($"{Context.User.Mention} rolled {n1} {(n1 == 1 ? "die" : "dice")} `1 to {n2}` +`{add}` -`{sub}`") .AddField(efb => efb.WithName(Format.Bold("Result")) .WithValue(string.Join(" ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => Format.Code(x.ToString()))))); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } } } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task NRoll([Remainder] string range) { - var channel = (ITextChannel)Context.Channel; - try { int rolled; @@ -215,11 +196,11 @@ namespace NadekoBot.Modules.Gambling rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } - await channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { - await channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); } } diff --git a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs index 19604e58..3e8c01a5 100644 --- a/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs +++ b/src/NadekoBot/Modules/Gambling/Commands/FlipCoinCommand.cs @@ -21,10 +21,8 @@ namespace NadekoBot.Modules.Gambling private const string tailsPath = "data/images/coins/tails.png"; [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Flip(int count = 1) { - //var channel = (ITextChannel)Context.Channel; if (count == 1) { if (rng.Next(0, 2) == 1) @@ -49,11 +47,8 @@ namespace NadekoBot.Modules.Gambling } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Betflip(int amount, string guess) { - //var channel = (ITextChannel)Context.Channel; - var guildUser = (IGuildUser)Context.User; var guessStr = guess.Trim().ToUpperInvariant(); if (guessStr != "H" && guessStr != "T" && guessStr != "HEADS" && guessStr != "TAILS") return; @@ -64,7 +59,7 @@ namespace NadekoBot.Modules.Gambling .ConfigureAwait(false); return; } - var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)Context.User, "Betflip Gamble", amount, false).ConfigureAwait(false); + var removed = await CurrencyHandler.RemoveCurrencyAsync(Context.User, "Betflip Gamble", amount, false).ConfigureAwait(false); if (!removed) { await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}.").ConfigureAwait(false); @@ -91,7 +86,7 @@ namespace NadekoBot.Modules.Gambling { var toWin = (int)Math.Round(amount * 1.8); str = $"{Context.User.Mention}`You guessed it!` You won {toWin}{Gambling.CurrencySign}"; - await CurrencyHandler.AddCurrencyAsync((IGuildUser)Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(Context.User, "Betflip Gamble", toWin, false).ConfigureAwait(false); } else { diff --git a/src/NadekoBot/Modules/Gambling/Gambling.cs b/src/NadekoBot/Modules/Gambling/Gambling.cs index 636c9cd6..b3bbe1bd 100644 --- a/src/NadekoBot/Modules/Gambling/Gambling.cs +++ b/src/NadekoBot/Modules/Gambling/Gambling.cs @@ -17,7 +17,7 @@ namespace NadekoBot.Modules.Gambling public static string CurrencyName { get; set; } public static string CurrencyPluralName { get; set; } public static string CurrencySign { get; set; } - + static Gambling() { using (var uow = DbHandler.UnitOfWork()) @@ -90,7 +90,6 @@ namespace NadekoBot.Modules.Gambling Award(amount, usr.Id); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [OwnerOnly] [Priority(1)] public async Task Award(int amount, ulong usrId) @@ -122,7 +121,7 @@ namespace NadekoBot.Modules.Gambling .ConfigureAwait(false); } - + [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] [OwnerOnly] @@ -131,36 +130,32 @@ namespace NadekoBot.Modules.Gambling if (amount <= 0) return; - if(await CurrencyHandler.RemoveCurrencyAsync(user, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount, true).ConfigureAwait(false)) - await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); + if (await CurrencyHandler.RemoveCurrencyAsync(user, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount, true).ConfigureAwait(false)) + await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user}!").ConfigureAwait(false); else await Context.Channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from {user} because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [OwnerOnly] public async Task Take(long amount, [Remainder] ulong usrId) { if (amount <= 0) return; - if(await CurrencyHandler.RemoveCurrencyAsync(usrId, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false)) + if (await CurrencyHandler.RemoveCurrencyAsync(usrId, $"Taken by bot owner.({Context.User.Username}/{Context.User.Id})", amount).ConfigureAwait(false)) await Context.Channel.SendConfirmAsync($"{Context.User.Mention} successfully took {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from <@{usrId}>!").ConfigureAwait(false); else await Context.Channel.SendErrorAsync($"{Context.User.Mention} was unable to take {amount} {(amount == 1 ? Gambling.CurrencyName : Gambling.CurrencyPluralName)} from `{usrId}` because the user doesn't have that much {Gambling.CurrencyPluralName}!").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task BetRoll(long amount) { if (amount < 1) return; - var guildUser = (IGuildUser)Context.User; - long userFlowers; using (var uow = DbHandler.UnitOfWork()) { @@ -169,14 +164,14 @@ namespace NadekoBot.Modules.Gambling if (userFlowers < amount) { - await Context.Channel.SendErrorAsync($"{guildUser.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync($"{Context.User.Mention} You don't have enough {Gambling.CurrencyPluralName}. You only have {userFlowers}{Gambling.CurrencySign}.").ConfigureAwait(false); return; } - await CurrencyHandler.RemoveCurrencyAsync(guildUser, "Betroll Gamble", amount, false).ConfigureAwait(false); + await CurrencyHandler.RemoveCurrencyAsync(Context.User, "Betroll Gamble", amount, false).ConfigureAwait(false); var rng = new NadekoRandom().Next(0, 101); - var str = $"{guildUser.Mention} `You rolled {rng}.` "; + var str = $"{Context.User.Mention} `You rolled {rng}.` "; if (rng < 67) { str += "Better luck next time."; @@ -184,24 +179,23 @@ namespace NadekoBot.Modules.Gambling else if (rng < 91) { str += $"Congratulations! You won {amount * 2}{Gambling.CurrencySign} for rolling above 66"; - await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 2, false).ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 2, false).ConfigureAwait(false); } else if (rng < 100) { str += $"Congratulations! You won {amount * 3}{Gambling.CurrencySign} for rolling above 90."; - await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 3, false).ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 3, false).ConfigureAwait(false); } else { str += $"๐Ÿ‘‘ Congratulations! You won {amount * 10}{Gambling.CurrencySign} for rolling **100**. ๐Ÿ‘‘"; - await CurrencyHandler.AddCurrencyAsync(guildUser, "Betroll Gamble", amount * 10, false).ConfigureAwait(false); + await CurrencyHandler.AddCurrencyAsync(Context.User, "Betroll Gamble", amount * 10, false).ConfigureAwait(false); } await Context.Channel.SendConfirmAsync(str).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Leaderboard() { IEnumerable richest = new List(); diff --git a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs index 72ef1929..62d2930e 100644 --- a/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs +++ b/src/NadekoBot/Modules/Games/Commands/LeetCommands.cs @@ -13,15 +13,12 @@ namespace NadekoBot.Modules.Games public partial class Games { [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Leet(int level, [Remainder] string text = null) { - var channel = (ITextChannel)Context.Channel; - text = text.Trim(); if (string.IsNullOrWhiteSpace(text)) return; - await channel.SendConfirmAsync("L33t", ToLeet(text, level).SanitizeMentions()).ConfigureAwait(false); + await Context.Channel.SendConfirmAsync("L33t", ToLeet(text, level).SanitizeMentions()).ConfigureAwait(false); } diff --git a/src/NadekoBot/Modules/Games/Games.cs b/src/NadekoBot/Modules/Games/Games.cs index 3d322090..3278518e 100644 --- a/src/NadekoBot/Modules/Games/Games.cs +++ b/src/NadekoBot/Modules/Games/Games.cs @@ -24,7 +24,6 @@ namespace NadekoBot.Modules.Games [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Choose([Remainder] string list = null) { if (string.IsNullOrWhiteSpace(list)) @@ -37,7 +36,6 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task _8Ball([Remainder] string question = null) { if (string.IsNullOrWhiteSpace(question)) @@ -50,7 +48,6 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Rps(string input) { Func GetRPSPick = (p) => @@ -98,7 +95,6 @@ namespace NadekoBot.Modules.Games } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Linux(string guhnoo, string loonix) { await Context.Channel.SendConfirmAsync( diff --git a/src/NadekoBot/Modules/NSFW/NSFW.cs b/src/NadekoBot/Modules/NSFW/NSFW.cs index f3300b7e..4c4ce138 100644 --- a/src/NadekoBot/Modules/NSFW/NSFW.cs +++ b/src/NadekoBot/Modules/NSFW/NSFW.cs @@ -56,12 +56,10 @@ namespace NadekoBot.Modules.NSFW } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Hentai([Remainder] string tag = null) => InternalHentai(Context.Channel, tag, false); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task AutoHentai(int interval = 0, string tags = null) { Timer t; @@ -104,7 +102,6 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task HentaiBomb([Remainder] string tag = null) { var channel = (ITextChannel)Context.Channel; @@ -128,7 +125,6 @@ namespace NadekoBot.Modules.NSFW [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Danbooru([Remainder] string tag = null) { var channel = (ITextChannel)Context.Channel; @@ -147,53 +143,44 @@ namespace NadekoBot.Modules.NSFW } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Yandere([Remainder] string tag = null) => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Yandere); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Konachan([Remainder] string tag = null) => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Konachan); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Gelbooru([Remainder] string tag = null) => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Gelbooru); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Rule34([Remainder] string tag = null) => Searches.Searches.InternalDapiCommand(Context.Message, tag, Searches.Searches.DapiSearchType.Rule34); [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task E621([Remainder] string tag = null) { - var channel = (ITextChannel)Context.Channel; - tag = tag?.Trim() ?? ""; var url = await GetE621ImageLink(tag).ConfigureAwait(false); if (url == null) - await channel.SendErrorAsync(Context.User.Mention + " No results."); + await Context.Channel.SendErrorAsync(Context.User.Mention + " No results."); else - await channel.EmbedAsync(new EmbedBuilder().WithOkColor() + await Context.Channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithDescription(Context.User.Mention + " " + tag) .WithImageUrl(url) .WithFooter(efb => efb.WithText("e621"))).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Cp() { await Context.Channel.SendMessageAsync("http://i.imgur.com/MZkY1md.jpg").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Boobs() { try @@ -212,7 +199,6 @@ namespace NadekoBot.Modules.NSFW } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Butts() { try diff --git a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs index aff6635e..ed6c058b 100644 --- a/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/AnimeSearchCommands.cs @@ -53,11 +53,8 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Anime([Remainder] string query) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(query)) return; @@ -78,15 +75,13 @@ namespace NadekoBot.Modules.Searches .AddField(efb => efb.WithName("Status").WithValue(animeData.AiringStatus.ToString()).WithIsInline(true)) .AddField(efb => efb.WithName("Genres").WithValue(String.Join(", ", animeData.Genres)).WithIsInline(true)) .WithFooter(efb => efb.WithText("Score: " + animeData.average_score + " / 100")); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] [RequireContext(ContextType.Guild)] public async Task Manga([Remainder] string query) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(query)) return; @@ -108,7 +103,7 @@ namespace NadekoBot.Modules.Searches .AddField(efb => efb.WithName("Genres").WithValue(String.Join(", ", mangaData.Genres)).WithIsInline(true)) .WithFooter(efb => efb.WithText("Score: " + mangaData.average_score + " / 100")); - await channel.EmbedAsync(embed).ConfigureAwait(false); + await Context.Channel.EmbedAsync(embed).ConfigureAwait(false); } private async Task GetAnimeData(string query) diff --git a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs index 8d507d2f..f7f83361 100644 --- a/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs +++ b/src/NadekoBot/Modules/Searches/Commands/OsuCommands.cs @@ -25,7 +25,6 @@ namespace NadekoBot.Modules.Searches _log = LogManager.GetCurrentClassLogger(); } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Osu(string usr, [Remainder] string mode = null) { if (string.IsNullOrWhiteSpace(usr)) @@ -57,7 +56,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Osub([Remainder] string map) { if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.OsuApiKey)) diff --git a/src/NadekoBot/Modules/Searches/Searches.cs b/src/NadekoBot/Modules/Searches/Searches.cs index 7ac8f63e..b919335c 100644 --- a/src/NadekoBot/Modules/Searches/Searches.cs +++ b/src/NadekoBot/Modules/Searches/Searches.cs @@ -31,7 +31,6 @@ namespace NadekoBot.Modules.Searches public partial class Searches : DiscordModule { [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Weather([Remainder] string query) { if (string.IsNullOrWhiteSpace(query)) @@ -398,8 +397,6 @@ namespace NadekoBot.Modules.Searches [NadekoCommand, Usage, Description, Aliases] public async Task UrbanDict([Remainder] string query = null) { - var channel = (ITextChannel)Context.Channel; - if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.MashapeKey)) { await Context.Channel.SendErrorAsync("Bot owner didn't specify MashapeApiKey. You can't use this functionality.").ConfigureAwait(false); @@ -439,10 +436,8 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Define([Remainder] string word) { - if (string.IsNullOrWhiteSpace(word)) return; @@ -474,7 +469,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task Hashtag([Remainder] string query = null) { var arg = query; @@ -550,7 +544,6 @@ namespace NadekoBot.Modules.Searches } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public Task Safebooru([Remainder] string tag = null) => InternalDapiCommand(Context.Message, tag, DapiSearchType.Safebooru); @@ -732,7 +725,7 @@ namespace NadekoBot.Modules.Searches public static async Task InternalDapiCommand(IUserMessage umsg, string tag, DapiSearchType type) { - var channel = (ITextChannel)umsg.Channel; + var channel = umsg.Channel; tag = tag?.Trim() ?? ""; diff --git a/src/NadekoBot/Modules/Trello/Trello.cs b/src/NadekoBot/Modules/Trello/Trello.cs deleted file mode 100644 index c3a7863f..00000000 --- a/src/NadekoBot/Modules/Trello/Trello.cs +++ /dev/null @@ -1,145 +0,0 @@ -๏ปฟ//using Discord.Modules; -//using Manatee.Trello; -//using Manatee.Trello.ManateeJson; -//using NadekoBot.Extensions; -//using NadekoBot.Modules.Permissions.Classes; -//using System; -//using System.Collections.Generic; -//using System.Linq; -//using System.Timers; -//using Action = Manatee.Trello.Action; -////todo rewrite -//namespace NadekoBot.Modules.Trello -//{ -// public class Trello : DiscordModule -// { -// private readonly Timer t = new Timer { Interval = 2000 }; -// public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.Trello; - -// public override void Install(ModuleManager manager) -// { - -// var client = manager.Client; - -// var serializer = new ManateeSerializer(); -// TrelloConfiguration.Serializer = serializer; -// TrelloConfiguration.Deserializer = serializer; -// TrelloConfiguration.JsonFactory = new ManateeFactory(); -// TrelloConfiguration.RestClientProvider = new Manatee.Trello.WebApi.WebApiClientProvider(); -// TrelloAuthorization.Default.AppKey = NadekoBot.Credentials.TrelloAppKey; -// //TrelloAuthorization.Default.UserToken = "[your user token]"; - -// Discord.Channel bound = null; -// Board board = null; - -// List last5ActionIDs = null; -// t.Elapsed += async (s, e) => -// { -// try -// { -// if (board == null || bound == null) -// return; //do nothing if there is no bound board - -// board.Refresh(); -// var cur5Actions = board.Actions.Take(board.Actions.Count() < 5 ? board.Actions.Count() : 5); -// var cur5ActionsArray = cur5Actions as Action[] ?? cur5Actions.ToArray(); - -// if (last5ActionIDs == null) -// { -// last5ActionIDs = cur5ActionsArray.Select(a => a.Id).ToList(); -// return; -// } - -// foreach (var a in cur5ActionsArray.Where(ca => !last5ActionIDs.Contains(ca.Id))) -// { -// await bound.Send("**--TRELLO NOTIFICATION--**\n" + a.ToString()).ConfigureAwait(false); -// } -// last5ActionIDs.Clear(); -// last5ActionIDs.AddRange(cur5ActionsArray.Select(a => a.Id)); -// } -// catch (Exception ex) -// { -// Console.WriteLine("Timer failed " + ex.ToString()); -// } -// }; - -// manager.CreateCommands("", cgb => -// { - -// cgb.AddCheck(PermissionChecker.Instance); - -// cgb.CreateCommand(Prefix + "bind") -// .Description("Bind a trello bot to a single channel. " + -// "You will receive notifications from your board when something is added or edited." + -// $" **Bot Owner Only!**| `{Prefix}bind [board_id]`") -// .Parameter("board_id", Discord.Commands.ParameterType.Required) -// .Do(async e => -// { -// if (!NadekoBot.IsOwner(Context.User.Id)) return; -// if (bound != null) return; -// try -// { -// bound = e.Channel; -// board = new Board(board_id.Trim()); -// board.Refresh(); -// await channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name); -// t.Start(); -// } -// catch (Exception ex) -// { -// Console.WriteLine("Failed to join the board. " + ex.ToString()); -// } -// }); - -// cgb.CreateCommand(Prefix + "unbind") -// .Description($"Unbinds a bot from the channel and board. **Bot Owner Only!**| `{Prefix}unbind`") -// .Do(async e => -// { -// if (!NadekoBot.IsOwner(Context.User.Id)) return; -// if (bound == null || bound != e.Channel) return; -// t.Stop(); -// bound = null; -// board = null; -// await channel.SendMessageAsync("Successfully unbound trello from this channel.").ConfigureAwait(false); - -// }); - -// cgb.CreateCommand(Prefix + "lists") -// .Alias(Prefix + "list") -// .Description($"Lists all lists, yo ;) **Bot Owner Only!**| `{Prefix}list`") -// .Do(async e => -// { -// if (!NadekoBot.IsOwner(Context.User.Id)) return; -// if (bound == null || board == null || bound != e.Channel) return; -// await channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**โ€ข " + l.ToString() + "**"))) -// .ConfigureAwait(false); -// }); - -// cgb.CreateCommand(Prefix + "cards") -// .Description($"Lists all cards from the supplied list. You can supply either a name or an index. **Bot Owner Only!**| `{Prefix}cards index`") -// .Parameter("list_name", Discord.Commands.ParameterType.Unparsed) -// .Do(async e => -// { -// if (!NadekoBot.IsOwner(Context.User.Id)) return; -// if (bound == null || board == null || bound != e.Channel || list_name == null) return; - -// int num; -// var success = int.TryParse(list_name, out num); -// List list = null; -// if (success && num <= board.Lists.Count() && num > 0) -// list = board.Lists[num - 1]; -// else -// list = board.Lists.FirstOrDefault(l => l.Name == list_name); - - -// if (list != null) -// await channel.SendMessageAsync("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**โ€ข " + c.ToString() + "**"))) -// .ConfigureAwait(false); -// else -// await channel.SendMessageAsync("No such list.") -// .ConfigureAwait(false); -// }); -// }); -// } -// } -//} diff --git a/src/NadekoBot/Modules/Utility/Utility.cs b/src/NadekoBot/Modules/Utility/Utility.cs index d98d13d0..27f8d25e 100644 --- a/src/NadekoBot/Modules/Utility/Utility.cs +++ b/src/NadekoBot/Modules/Utility/Utility.cs @@ -17,7 +17,6 @@ namespace NadekoBot.Modules.Utility public partial class Utility : DiscordModule { [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] public async Task TogetherTube() { Uri target; @@ -123,7 +122,7 @@ namespace NadekoBot.Modules.Utility [RequireContext(ContextType.Guild)] public async Task ServerId() { - await Context.Channel.SendConfirmAsync($"๐Ÿ†” of this server is `{((ITextChannel)Context.Channel).Guild.Id}`").ConfigureAwait(false); + await Context.Channel.SendConfirmAsync($"๐Ÿ†” of this server is `{Context.Guild.Id}`").ConfigureAwait(false); } [NadekoCommand, Usage, Description, Aliases] @@ -223,12 +222,9 @@ namespace NadekoBot.Modules.Utility } [NadekoCommand, Usage, Description, Aliases] - [RequireContext(ContextType.Guild)] [OwnerOnly] public async Task ListServers(int page = 1) { - var channel = (ITextChannel)Context.Channel; - page -= 1; if (page < 0) @@ -238,11 +234,11 @@ namespace NadekoBot.Modules.Utility if (!guilds.Any()) { - await channel.SendErrorAsync("No servers found on that page.").ConfigureAwait(false); + await Context.Channel.SendErrorAsync("No servers found on that page.").ConfigureAwait(false); return; } - await channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithOkColor(), + await Context.Channel.EmbedAsync(guilds.Aggregate(new EmbedBuilder().WithOkColor(), (embed, g) => embed.AddField(efb => efb.WithName(g.Name) .WithValue($"```css\nID: {g.Id}\nMembers: {g.Users.Count}\nOwnerID: {g.OwnerId} ```") .WithIsInline(false)))) diff --git a/src/NadekoBot/Services/CurrencyHandler.cs b/src/NadekoBot/Services/CurrencyHandler.cs index fb8d68a6..01e649a2 100644 --- a/src/NadekoBot/Services/CurrencyHandler.cs +++ b/src/NadekoBot/Services/CurrencyHandler.cs @@ -42,7 +42,7 @@ namespace NadekoBot.Services return true; } - public static async Task AddCurrencyAsync(IGuildUser author, string reason, long amount, bool sendMessage) + public static async Task AddCurrencyAsync(IUser author, string reason, long amount, bool sendMessage) { await AddCurrencyAsync(author.Id, reason, amount);