chaosbot/ChaosBot/Discord/PreConditions/CheckCommandPerm.cs

59 lines
2.5 KiB
C#

using System;
using System.Linq;
using System.Threading.Tasks;
using ChaosBot.Database.Repository;
using Discord.Commands;
using Discord.WebSocket;
using NLog;
namespace ChaosBot.Discord.PreConditions
{
public class CheckCommandPerm : PreconditionAttribute
{
private static ILogger _logger = Dependency.GetInstance<ILogger>();
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
{
// Debug information
_logger.Trace($"CheckCommandPerm.CheckPermissionsAsync|Checking permissions for command: {command.Name}");
// If user is not SocketGuildUser, then return error
if (!(context.User is SocketGuildUser gUser)) return Task.FromResult(PreconditionResult.FromError("You must be in a guild to run this command."));
// Get the possible permissions
var commandPermissions = CommandPermissionRepository.getPerm(command.Name, Convert.ToInt64(context.Guild.Id));
// If we can find a permission
if(commandPermissions != null)
{
// Loop through all permissions
foreach (var perm in commandPermissions)
{
string requiredGroup;
// Check if it's a role or group permission and fetch the right type
if (perm.type.ToLower() == "role")
{
// If it's a role, check the configuration for the role otherwise return the permission value
requiredGroup = ConfigurationRepository.GetValue<string>($"Role:{perm.value}", context.Guild.Id) ?? perm.value;
}
else
{
// Return the permission value
requiredGroup = perm.value;
}
// Check if any of the users roles are of the required group, if so, permission granted
if (gUser.Roles.Any(r => r.Name == requiredGroup))
return Task.FromResult(PreconditionResult.FromSuccess());
}
}
else
{
_logger.Info("CheckCommandperm.CheckPermissionsAsync|commandPermissions: Null Value");
}
// Permission denied
return Task.FromResult(PreconditionResult.FromError($"You do not have access to this command."));
}
}
}