#Role Precondition

1 messages · Page 1 of 1 (latest)

woeful ocean
#
using Discord;
using Discord.Interactions;
using Microsoft.Extensions.DependencyInjection;
using Blink.Common.Entities;
using Blink.Common.Interfaces;

namespace Blink.Commands.PreConditions
{
    // Inherit from PreconditionAttribute
    public class RequireStaffAttribute : PreconditionAttribute
    {
        // Override the CheckPermissions method
        public override async Task<PreconditionResult> CheckRequirementsAsync(IInteractionContext context, ICommandInfo commandInfo, IServiceProvider services)
        {
            // Check if this user is a Guild User, which is the only context where roles exist
            if (context.User is not IGuildUser gUser)
                return PreconditionResult.FromError("You must be in a guild to run this command.");

            IGuildRepository guildRepository = services.GetService<IGuildRepository>();
            Guild guildConfig = await guildRepository.GetCachedByIdAsync(gUser.Guild.Id);

            if (guildConfig?.StaffRoleId == null)
                return PreconditionResult.FromError("This guild has not bee properly configured.  No Staff role defined.");

            // If this command was not executed by a user with the appropriate role, return an error
            if (!gUser.RoleIds.Any(r => r == (ulong)guildConfig.StaffRoleId))
                return PreconditionResult.FromError("You must be Staff to run this command.");

            // Since no async work is done, the result has to be wrapped with `Task.FromResult` to avoid compiler errors
            return PreconditionResult.FromSuccess();
        }
    }
}```
#

Something like this? You could pass the role ID as a parameter, here I'm getting it from a database

slender fog
#

okay, i will try ty

slender fog
#

thank you, i didnt get a respond from precondition if fails

slender fog
#

if precondition returning .FromError like here

return Task.FromResult(PreconditionResult.FromError(this.ErrorMessage ?? "You need guild role."));

I got application not responding

slender fog
#

It’s done with default interactionhandler

#

That is in sample