Skip to content

Commit feed4fd

Browse files
Joe4evrfoxbot
authored andcommitted
docs: Replace obsolete Precondition sample with something new (#1230)
* Replace obsolete Precondition sample with something new * Feedback Whoops. 👌 Co-Authored-By: Joe4evr <[email protected]>
1 parent 65b8c09 commit feed4fd

File tree

3 files changed

+33
-29
lines changed

3 files changed

+33
-29
lines changed

docs/guides/commands/preconditions.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ necessary.
7676
7777
### Example - Creating a Custom Precondition
7878

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

8181
[CheckPermissionsAsync]: xref:Discord.Commands.PreconditionAttribute.CheckPermissionsAsync*
8282
[PreconditionResult.FromSuccess]: xref:Discord.Commands.PreconditionResult.FromSuccess*

docs/guides/commands/samples/preconditions/require_owner.cs

Lines changed: 0 additions & 28 deletions
This file was deleted.
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Discord.Commands;
4+
using Discord.WebSocket;
5+
6+
// Inherit from PreconditionAttribute
7+
public class RequireRoleAttribute : PreconditionAttribute
8+
{
9+
// Create a field to store the specified name
10+
private readonly string _name;
11+
12+
// Create a constructor so the name can be specified
13+
public RequireRoleAttribute(string name) => _name = name;
14+
15+
// Override the CheckPermissions method
16+
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
17+
{
18+
// Check if this user is a Guild User, which is the only context where roles exist
19+
if (context.User is SocketGuildUser gUser)
20+
{
21+
// If this command was executed by a user with the appropriate role, return a success
22+
if (gUser.Roles.Any(r => r.Name == _name))
23+
// Since no async work is done, the result has to be wrapped with `Task.FromResult` to avoid compiler errors
24+
return Task.FromResult(PreconditionResult.FromSuccess());
25+
// Since it wasn't, fail
26+
else
27+
return Task.FromResult(PreconditionResult.FromError($"You must have a role named {_name} to run this command."));
28+
}
29+
else
30+
return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command."));
31+
}
32+
}

0 commit comments

Comments
 (0)