Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace obsolete Precondition sample with something new #1230

Merged
merged 2 commits into from
Jan 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guides/commands/preconditions.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ necessary.

### Example - Creating a Custom Precondition

[!code-csharp[Custom Precondition](samples/preconditions/require_owner.cs)]
[!code-csharp[Custom Precondition](samples/preconditions/require_role.cs)]

[CheckPermissionsAsync]: xref:Discord.Commands.PreconditionAttribute.CheckPermissionsAsync*
[PreconditionResult.FromSuccess]: xref:Discord.Commands.PreconditionResult.FromSuccess*
Expand Down
28 changes: 0 additions & 28 deletions docs/guides/commands/samples/preconditions/require_owner.cs

This file was deleted.

32 changes: 32 additions & 0 deletions docs/guides/commands/samples/preconditions/require_role.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;

// Inherit from PreconditionAttribute
public class RequireRoleAttribute : PreconditionAttribute
{
// Create a field to store the specified name
private readonly string _name;

// Create a constructor so the name can be specified
public RequireRoleAttribute(string name) => _name = name;

// Override the CheckPermissions method
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
// Check if this user is a Guild User, which is the only context where roles exist
if (context.User is SocketGuildUser gUser)
{
// If this command was executed by a user with the appropriate role, return a success
if (gUser.Roles.Any(r => r.Name == _name))
// Since no async work is done, the result has to be wrapped with `Task.FromResult` to avoid compiler errors
return Task.FromResult(PreconditionResult.FromSuccess());
// Since it wasn't, fail
else
return Task.FromResult(PreconditionResult.FromError($"You must have a role named {_name} to run this command."));
}
else
return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command."));
}
}