A lot of work on moving to b2

This commit is contained in:
Kwoth 2016-12-16 19:43:57 +01:00
parent 39f3ee0190
commit ac47621476
76 changed files with 1049 additions and 1230 deletions

View File

@ -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<string, string> 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)

View File

@ -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<PreconditionResult> CheckPermissions(IUserMessage context, Command executingCommand, object moduleInstance) =>
Task.FromResult((NadekoBot.Credentials.IsOwner(context.Author) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
public override Task<PreconditionResult> CheckPermissions(CommandContext context, CommandInfo executingCommand,IDependencyMap depMap) =>
Task.FromResult((NadekoBot.Credentials.IsOwner(context.User) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
}
}

View File

@ -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)
public async Task Prune()
{
var channel = (ITextChannel)umsg.Channel;
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<IMessage>(cnt);
while (cnt > 0)
{
var dlcnt = cnt < 100 ? cnt : 100;
IReadOnlyCollection<IMessage> dledMsgs;
IEnumerable<IMessage> 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<Donator> 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);
}
}
}

View File

@ -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;

View File

@ -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())

View File

@ -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<ITextChannel>();
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<ITextChannel> 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)
{

View File

@ -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 { }
}
}

View File

@ -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())
// {

View File

@ -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;

View File

@ -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);
}
}

View File

@ -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);

View File

@ -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);
}
}
}

View File

@ -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)
{

View File

@ -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<SelfAssignedRole> 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<SelfAssignedRole>();
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<SelfAssignedRole> roles;

View File

@ -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);

View File

@ -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);

View File

@ -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)

View File

@ -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<List<ClashWar>, int> GetWarInfo(IUserMessage umsg, int num)
{
var channel = (ITextChannel)umsg.Channel;
var channel = (ITextChannel)Context.Channel;
//check if there are any wars
List<ClashWar> wars = null;
ClashWars.TryGetValue(channel.Guild.Id, out wars);

View File

@ -33,9 +33,9 @@ namespace NadekoBot.Modules.CustomReactions
public void ClearStats() => ReactionStats.Clear();
public static async Task<bool> TryExecuteCustomReaction(IUserMessage umsg)
public static async Task<bool> 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<CustomReaction>());
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<CustomReaction> customReactions;
if (channel == null)
@ -167,7 +167,7 @@ namespace NadekoBot.Modules.CustomReactions
customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<CustomReaction>());
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<CustomReaction> customReactions;
@ -196,9 +196,9 @@ namespace NadekoBot.Modules.CustomReactions
customReactions = GuildReactions.GetOrAdd(channel.Guild.Id, new ConcurrentHashSet<CustomReaction>());
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<CustomReaction> 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);
}
}

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.CustomReactions
public static Dictionary<string, Func<IUserMessage, string>> placeholders = new Dictionary<string, Func<IUserMessage, string>>()
{
{"%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;

View File

@ -4,7 +4,7 @@ using NLog;
namespace NadekoBot.Modules
{
public class DiscordModule
public class DiscordModule : ModuleBase
{
protected Logger _log { get; }
protected string _prefix { get; }

View File

@ -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;

View File

@ -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)
{

View File

@ -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<Image>();
var cardObjects = new List<Cards.Card>();
@ -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(),

View File

@ -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);

View File

@ -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<Currency> richest = new List<Currency>();
using (var uow = DbHandler.UnitOfWork())

View File

@ -41,8 +41,8 @@ namespace NadekoBot.Modules.Games
}
}
public static async Task<bool> TryAsk(IUserMessage msg) {
var channel = msg.Channel as ITextChannel;
public static async Task<bool> 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);
}
}
}

View File

@ -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);
}

View File

@ -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);
}
}
}

View File

@ -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))

View File

@ -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())

View File

@ -16,22 +16,22 @@ namespace NadekoBot.Modules.Games
public static ConcurrentDictionary<IGuild, Poll> ActivePolls = new ConcurrentDictionary<IGuild, Poll>();
[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<string> 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);
}

View File

@ -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)

View File

@ -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);

View File

@ -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))

View File

@ -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<int,string> 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.

View File

@ -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: <https://patreon.com/nadekobot> or paypal: <https://www.paypal.me/Kwoth>\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**: <http://nadekobot.readthedocs.io/en/latest/Commands%20List/>
@ -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. <https://patreon.com/nadekobot> or

View File

@ -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<SoundCloudVideo[]>();
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;

View File

@ -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
{

View File

@ -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())
{

View File

@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Permissions
}
[Group]
public class CmdCdsCommands
public class CmdCdsCommands : ModuleBase
{
public static ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>> commandCooldowns { get; }
private static ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> activeCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
@ -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<CommandCooldown>());
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<CommandCooldown>());
if (!localSet.Any())

View File

@ -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<string> filteredWords;
ServerFilteredWords.TryGetValue(channel.Guild.Id, out filteredWords);

View File

@ -10,7 +10,7 @@ namespace NadekoBot.Modules.Permissions
{
public static class PermissionExtensions
{
public static bool CheckPermissions(this IEnumerable<Permission> permsEnumerable, IUserMessage message, Command command)
public static bool CheckPermissions(this IEnumerable<Permission> permsEnumerable, IUserMessage message, CommandInfo command)
{
var perms = permsEnumerable as List<Permission> ?? 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:

View File

@ -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,

View File

@ -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))

View File

@ -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);
}

View File

@ -18,7 +18,7 @@ namespace NadekoBot.Modules.Searches
public partial class Searches
{
[Group]
public class JokeCommands
public class JokeCommands : ModuleBase
{
private static List<WoWJoke> wowJokes { get; } = new List<WoWJoke>();
private static List<MagicItem> magicItems { get; } = new List<MagicItem>();
@ -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);
}
}
}

View File

@ -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);
}
}
}

View File

@ -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<Dictionary<string, string>>(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);
}
}

View File

@ -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}

View File

@ -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);

View File

@ -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<OverwatchApiModel.OverwatchPlayer.Data> 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<OverwatchApiModel.OverwatchPlayer>(Url);
return model.data;
}
}
catch
{
return null;
}
}
public async Task<OverwatchApiModel.OverwatchPlayer.Data> 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<OverwatchApiModel.OverwatchPlayer>(Url);
return model.data;
}
}
catch
{
return null;
}
}
}
}
}
}

View File

@ -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);
}
}
}

View File

@ -15,7 +15,7 @@ namespace NadekoBot.Modules.Searches
public partial class Searches
{
[Group]
public class PokemonSearchCommands
public class PokemonSearchCommands : ModuleBase
{
private static Dictionary<string, SearchPokemon> pokemons { get; } = new Dictionary<string, SearchPokemon>();
private static Dictionary<string, SearchPokemonAbility> pokemonAbilities { get; } = new Dictionary<string, SearchPokemonAbility>();
@ -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.");
}
}
}

View File

@ -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<string, StreamStatus> oldCachedStatuses = new ConcurrentDictionary<string, StreamStatus>();
@ -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<FollowedStream> 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);
}
}
}

View File

@ -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<ulong, bool> TranslatedChannels { get; }
private static ConcurrentDictionary<UserChannelPair, string> 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);
}
}

View File

@ -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<XkcdComic>(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<XkcdComic>(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)));
}
}
}

View File

@ -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();

View File

@ -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;

View File

@ -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));
}
}

View File

@ -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);
}
}
}

View File

@ -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<Quote> 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.");
}
}
}

View File

@ -17,7 +17,7 @@ namespace NadekoBot.Modules.Utility
public partial class Utility
{
[Group]
public class RemindCommands
public class RemindCommands : ModuleBase
{
Regex regex = new Regex(@"^(?:(?<months>\d)mo)?(?:(?<weeks>\d)w)?(?:(?<days>\d{1,2})d)?(?:(?<hours>\d{1,2})h)?(?:(?<minutes>\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;

View File

@ -21,7 +21,7 @@ namespace NadekoBot.Modules.Utility
public partial class Utility
{
[Group]
public class UnitConverterCommands
public class UnitConverterCommands : ModuleBase
{
public static List<ConvertUnit> Units { get; set; } = new List<ConvertUnit>();
@ -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)));
}
}

View File

@ -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(@"<:(?<name>.+?):(?<id>\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);
}
}

View File

@ -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<PermissionAction>(new PermissionActionTypeReader());
CommandService.AddTypeReader<Command>(new CommandTypeReader());
CommandService.AddTypeReader<CommandInfo>(new CommandTypeReader());
CommandService.AddTypeReader<Module>(new ModuleTypeReader());
CommandService.AddTypeReader<IGuild>(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<Music>().ConfigureAwait(false);
#endif
Ready = true;
Console.WriteLine(await Stats.Print().ConfigureAwait(false));

View File

@ -39,7 +39,7 @@ namespace NadekoBot.Services
private List<IDMChannel> ownerChannels { get; set; }
public event Func<IUserMessage,Command, Task> CommandExecuted = delegate { return Task.CompletedTask; };
public event Func<SocketUserMessage, CommandInfo, Task> 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<Tuple<Command, PermissionCache, IResult>> ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best) {
public async Task<Tuple<CommandInfo, PermissionCache, IResult>> 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<Command, PermissionCache, IResult>(null, null, searchResult);
return new Tuple<CommandInfo, PermissionCache, IResult>(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<Command, PermissionCache, IResult>(null, null, searchResult);
return new Tuple<CommandInfo, PermissionCache, IResult>(null, null, searchResult);
else
continue;
}
@ -248,7 +248,7 @@ namespace NadekoBot.Services
if (!parseResult.IsSuccess)
{
if (commands.Count == 1)
return new Tuple<Command, PermissionCache, IResult>(null, null, parseResult);
return new Tuple<CommandInfo, PermissionCache, IResult>(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<Command, PermissionCache, IResult>(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg));
return new Tuple<CommandInfo, PermissionCache, IResult>(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<Command, PermissionCache, IResult>(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands."));
return new Tuple<CommandInfo, PermissionCache, IResult>(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<Command, PermissionCache, IResult>(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you."));
return new Tuple<CommandInfo, PermissionCache, IResult>(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you."));
return new Tuple<Command, PermissionCache, IResult>(commands[i], null, await commands[i].Execute(message, parseResult));
return new Tuple<CommandInfo, PermissionCache, IResult>(commands[i], null, await commands[i].Execute(message, parseResult));
}
return new Tuple<Command, PermissionCache, IResult>(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload."));
return new Tuple<CommandInfo, PermissionCache, IResult>(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;

View File

@ -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))

View File

@ -67,7 +67,7 @@ namespace NadekoBot.Services.Impl
}
public async Task<string> Print()
{
var curUser = await client.GetCurrentUserAsync();
var curUser = await client.CurrentUser();
return $@"
Author: [{Author}] | Library: [{Library}]
Bot Version: [{BotVersion}]

View File

@ -13,19 +13,19 @@ namespace NadekoBot
private DiscordSocketConfig discordSocketConfig;
private Logger _log { get; }
public event Func<IGuildUser, Task> UserJoined = delegate { return Task.CompletedTask; };
public event Func<IMessage, Task> MessageReceived = delegate { return Task.CompletedTask; };
public event Func<IGuildUser, Task> UserLeft = delegate { return Task.CompletedTask; };
public event Func<IGuildUser, IGuildUser, Task> UserUpdated = delegate { return Task.CompletedTask; };
public event Func<Optional<IMessage>, IMessage, Task> MessageUpdated = delegate { return Task.CompletedTask; };
public event Func<ulong, Optional<IMessage>, Task> MessageDeleted = delegate { return Task.CompletedTask; };
public event Func<IUser, IGuild, Task> UserBanned = delegate { return Task.CompletedTask; };
public event Func<IUser, IGuild, Task> UserUnbanned = delegate { return Task.CompletedTask; };
public event Func<IGuildUser, IPresence, IPresence, Task> UserPresenceUpdated = delegate { return Task.CompletedTask; };
public event Func<IUser, IVoiceState, IVoiceState, Task> UserVoiceStateUpdated = delegate { return Task.CompletedTask; };
public event Func<IChannel, Task> ChannelCreated = delegate { return Task.CompletedTask; };
public event Func<IChannel, Task> ChannelDestroyed = delegate { return Task.CompletedTask; };
public event Func<IChannel, IChannel, Task> ChannelUpdated = delegate { return Task.CompletedTask; };
public event Func<SocketGuildUser, Task> UserJoined = delegate { return Task.CompletedTask; };
public event Func<SocketMessage, Task> MessageReceived = delegate { return Task.CompletedTask; };
public event Func<SocketGuildUser, Task> UserLeft = delegate { return Task.CompletedTask; };
public event Func<SocketUser, SocketUser, Task> UserUpdated = delegate { return Task.CompletedTask; };
public event Func<Optional<SocketMessage>, SocketMessage, Task> MessageUpdated = delegate { return Task.CompletedTask; };
public event Func<ulong, Optional<SocketMessage>, Task> MessageDeleted = delegate { return Task.CompletedTask; };
public event Func<SocketUser, SocketGuild, Task> UserBanned = delegate { return Task.CompletedTask; };
public event Func<SocketUser, SocketGuild, Task> UserUnbanned = delegate { return Task.CompletedTask; };
public event Func<Optional<SocketGuild>, SocketUser, SocketPresence, SocketPresence, Task> UserPresenceUpdated = delegate { return Task.CompletedTask; };
public event Func<SocketUser, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated = delegate { return Task.CompletedTask; };
public event Func<SocketChannel, Task> ChannelCreated = delegate { return Task.CompletedTask; };
public event Func<SocketChannel, Task> ChannelDestroyed = delegate { return Task.CompletedTask; };
public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated = delegate { return Task.CompletedTask; };
public event Func<Exception, Task> Disconnected = delegate { return Task.CompletedTask; };
private IReadOnlyList<DiscordSocketClient> 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<ISelfUser> GetCurrentUserAsync() =>
Clients[0].GetCurrentUserAsync();
public Task<ISelfUser[]> GetAllCurrentUsersAsync() =>
Task.WhenAll(Clients.Select(c => c.GetCurrentUserAsync()));
public ISelfUser[] GetAllCurrentUsers() =>
Clients.Select(c => c.CurrentUser).ToArray();
public IReadOnlyCollection<IGuild> 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)));
}
}

View File

@ -7,12 +7,11 @@ namespace NadekoBot.TypeReaders
{
public class CommandTypeReader : TypeReader
{
public override Task<TypeReaderResult> Read(IUserMessage context, string input)
public override Task<TypeReaderResult> 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."));

View File

@ -7,7 +7,7 @@ namespace NadekoBot.TypeReaders
{
public class GuildTypeReader : TypeReader
{
public override Task<TypeReaderResult> Read(IUserMessage context, string input)
public override Task<TypeReaderResult> Read(CommandContext context, string input)
{
input = input.Trim().ToLowerInvariant();
var guilds = NadekoBot.Client.GetGuilds();

View File

@ -7,7 +7,7 @@ namespace NadekoBot.TypeReaders
{
public class ModuleTypeReader : TypeReader
{
public override Task<TypeReaderResult> Read(IUserMessage context, string input)
public override Task<TypeReaderResult> Read(CommandContext context, string input)
{
input = input.ToUpperInvariant();
var module = NadekoBot.CommandService.Modules.FirstOrDefault(m => m.Name.ToUpperInvariant() == input);

View File

@ -10,7 +10,7 @@ namespace NadekoBot.TypeReaders
/// </summary>
public class PermissionActionTypeReader : TypeReader
{
public override Task<TypeReaderResult> Read(IUserMessage context, string input)
public override Task<TypeReaderResult> Read(CommandContext context, string input)
{
input = input.ToUpperInvariant();
switch (input)

View File

@ -69,16 +69,18 @@ namespace NadekoBot.Extensions
await (await user.CreateDMChannelAsync().ConfigureAwait(false)).SendMessageAsync(message, isTTS).ConfigureAwait(false);
public static async Task<IUserMessage> 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<IUserMessage> 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<IUserMessage> 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<IUserMessage> 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<IUserMessage> 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<IUser> Members(this IRole role) =>
NadekoBot.Client.GetGuild(role.GuildId)?.GetUsers().Where(u => u.Roles.Contains(role)) ?? Enumerable.Empty<IUser>();
role.Guild.GetUsersAsync().GetAwaiter().GetResult() ?? Enumerable.Empty<IUser>();
public static Task<IUserMessage> EmbedAsync(this IMessageChannel ch, Discord.API.Embed embed, string msg = "")
public static Task<IUserMessage> EmbedAsync(this IMessageChannel ch, EmbedBuilder embed, string msg = "")
=> ch.SendMessageAsync(msg, embed: embed);
public static Task<IUserMessage> 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<IUserMessage> 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<IUserMessage> 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<IUserMessage> 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<IUserMessage> SendTableAsync<T>(this IMessageChannel ch, string seed, IEnumerable<T> items, Func<T, string> 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<Image> images)
public static ImageSharp.Image Merge(this IEnumerable<ImageSharp.Image> 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);

View File

@ -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",