Class ParameterPreconditionAttribute
Requires the parameter to pass the specified precondition before execution can begin.
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public abstract class ParameterPreconditionAttribute : Attribute
- Inheritance
-
ParameterPreconditionAttribute
- Derived
- Inherited Members
Examples
The following example creates a precondition on a parameter-level to see if the targeted user has a lower hierarchy than the user who executed the command.
public class RequireHierarchyAttribute : ParameterPreconditionAttribute
{
public override async Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context,
ParameterInfo parameter, object value, IServiceProvider services)
{
// Hierarchy is only available under the socket variant of the user.
if (!(context.User is SocketGuildUser guildUser))
return PreconditionResult.FromError("This command cannot be used outside of a guild.");
SocketGuildUser targetUser;
switch (value)
{
case SocketGuildUser targetGuildUser:
targetUser = targetGuildUser;
break;
case ulong userId:
targetUser = await context.Guild.GetUserAsync(userId).ConfigureAwait(false) as SocketGuildUser;
break;
default:
throw new ArgumentOutOfRangeException();
}
if (targetUser == null)
return PreconditionResult.FromError("Target user not found.");
if (guildUser.Hierarchy < targetUser.Hierarchy)
return PreconditionResult.FromError("You cannot target anyone else whose roles are higher than yours.");
var currentUser = await context.Guild.GetCurrentUserAsync().ConfigureAwait(false) as SocketGuildUser;
if (currentUser?.Hierarchy < targetUser.Hierarchy)
return PreconditionResult.FromError("The bot's role is lower than the targeted user.");
return PreconditionResult.FromSuccess();
}
}
Remarks
This precondition attribute can be applied on parameter-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.
Methods
CheckPermissionsAsync(ICommandContext, ParameterInfo, object, IServiceProvider)
Checks whether the condition is met before execution of the command.
public abstract Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider services)
Parameters
context
ICommandContextThe context of the command.
parameter
ParameterInfoThe parameter of the command being checked against.
value
objectThe raw value of the parameter.
services
IServiceProviderThe service collection used for dependency injection.