Class PreconditionAttribute
Requires the module or class to pass the specified precondition before execution can begin.
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class PreconditionAttribute : Attribute
- Inheritance
-
PreconditionAttribute
- Derived
- Inherited Members
Examples
The following example creates a precondition to see if the user has sufficient role required to access the command.
public class RequireRoleAttribute : PreconditionAttribute
{
private readonly ulong _roleId;
public RequireRoleAttribute(ulong roleId)
{
_roleId = roleId;
}
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context,
CommandInfo command, IServiceProvider services)
{
var guildUser = context.User as IGuildUser;
if (guildUser == null)
return PreconditionResult.FromError("This command cannot be executed outside of a guild.");
var guild = guildUser.Guild;
if (guild.Roles.All(r => r.Id != _roleId))
return PreconditionResult.FromError(
$"The guild does not have the role ({_roleId}) required to access this command.");
return guildUser.RoleIds.Any(rId => rId == _roleId)
? PreconditionResult.FromSuccess()
: PreconditionResult.FromError("You do not have the sufficient role required to access this command.");
}
}
Remarks
This precondition attribute can be applied on module-level or method-level for a command.
A "precondition" in the command system is used to determine if a condition is met before entering the command task. Using a precondition may aid in keeping a well-organized command logic.
The most common use case being whether a user has sufficient permission to execute the command.
Properties
ErrorMessage
When overridden in a derived class, uses the supplied string as the error message if the precondition doesn't pass. Setting this for a class that doesn't override this property is a no-op.
public virtual string ErrorMessage { get; set; }
Property Value
Group
Specifies a group that this precondition belongs to.
public string Group { get; set; }
Property Value
Remarks
Discord.Preconditions of the same group require only one of the preconditions to pass in order to be successful (A || B). Specifying Group = null or not at all will require all preconditions to pass, just like normal (A && B).
Methods
CheckPermissionsAsync(ICommandContext, CommandInfo, IServiceProvider)
Checks if the command
has the sufficient permission to be executed.
public abstract Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
Parameters
context
ICommandContextThe context of the command.
command
CommandInfoThe command being executed.
services
IServiceProviderThe service collection used for dependency injection.