using System; using System.Threading.Tasks; namespace Discord.Commands { /// /// Requires the bot to have a specific permission in the channel a command is invoked in. /// [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class RequireBotPermissionAttribute : PreconditionAttribute { /// /// Gets the specified of the precondition. /// public GuildPermission? GuildPermission { get; } /// /// Gets the specified of the precondition. /// public ChannelPermission? ChannelPermission { get; } /// public override string ErrorMessage { get; set; } /// /// Gets or sets the error message if the precondition /// fails due to being run outside of a Guild channel. /// public string NotAGuildErrorMessage { get; set; } /// /// Requires the bot account to have a specific . /// /// /// This precondition will always fail if the command is being invoked in a . /// /// /// The that the bot must have. Multiple permissions can be specified /// by ORing the permissions together. /// public RequireBotPermissionAttribute(GuildPermission permission) { GuildPermission = permission; ChannelPermission = null; } /// /// Requires that the bot account to have a specific . /// /// /// The that the bot must have. Multiple permissions can be /// specified by ORing the permissions together. /// public RequireBotPermissionAttribute(ChannelPermission permission) { ChannelPermission = permission; GuildPermission = null; } /// public override async Task CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { IGuildUser guildUser = null; if (context.Guild != null) guildUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false); if (GuildPermission.HasValue) { if (guildUser == null) return PreconditionResult.FromError(NotAGuildErrorMessage ?? "Command must be used in a guild channel."); if (!guildUser.GuildPermissions.Has(GuildPermission.Value)) return PreconditionResult.FromError(ErrorMessage ?? $"Bot requires guild permission {GuildPermission.Value}."); } if (ChannelPermission.HasValue) { ChannelPermissions perms; if (context.Channel is IGuildChannel guildChannel) perms = guildUser.GetPermissions(guildChannel); else perms = ChannelPermissions.All(context.Channel); if (!perms.Has(ChannelPermission.Value)) return PreconditionResult.FromError(ErrorMessage ?? $"Bot requires channel permission {ChannelPermission.Value}."); } return PreconditionResult.FromSuccess(); } } }