Ejemplo n.º 1
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context is BotCommandContext bContext && bContext.Bot.Secret.Admins != null && bContext.Bot.Secret.Admins.Length > 0)
            {
                return(bContext.Bot.Secret.Admins.Contains(context.User.Id) ? Task.FromResult(PreconditionResult.FromSuccess()) : Task.FromResult(PreconditionResult.FromError("You must be an admin to run this command")));
            }

            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }
Ejemplo n.º 2
0
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider serviceProvider)
        {
            return(Task.Run(() =>
            {
                _serviceProvider = serviceProvider;
                _userRepo = _serviceProvider.GetService <UserRepository>();
                _moderationService = _serviceProvider.GetService <ModerationService>();
                _gameService = _serviceProvider.GetService <GameService>();

                Context deaContext = context as Context;

                var permLevel = _moderationService.GetPermLevel(deaContext.DbGuild, deaContext.GUser);
                var invData = _gameService.InventoryData(deaContext.DbUser);

                foreach (var attribute in _attributes)
                {
                    switch (attribute)
                    {
                    case Attributes.BotOwner:
                        if (!Data.Credentials.OwnerIds.Any(x => x == context.User.Id))
                        {
                            return PreconditionResult.FromError("Only an owner of this bot may use this command.");
                        }
                        break;

                    case Attributes.ServerOwner:
                        if (permLevel != 3)
                        {
                            return PreconditionResult.FromError("Only the owners of this server may use this command.");
                        }
                        break;

                    case Attributes.Admin:
                        if (permLevel < 2)
                        {
                            return PreconditionResult.FromError("The administrator permission is required to use this command.");
                        }
                        break;

                    case Attributes.Moderator:
                        if (permLevel == 0)
                        {
                            return PreconditionResult.FromError("Only a moderator may use this command.");
                        }
                        break;

                    case Attributes.InGang:
                        if (deaContext.Gang == null)
                        {
                            return PreconditionResult.FromError("You must be in a gang to use this command.");
                        }
                        break;

                    case Attributes.NoGang:
                        if (deaContext.Gang != null)
                        {
                            return PreconditionResult.FromError("You may not use this command while in a gang.");
                        }
                        break;

                    case Attributes.GangLeader:
                        if (deaContext.Gang == null || deaContext.Gang.LeaderId != context.User.Id)
                        {
                            return PreconditionResult.FromError("You must be the leader of a gang to use this command.");
                        }
                        break;

                    case Attributes.Jump:
                        if (deaContext.Cash < Config.JumpRequirement)
                        {
                            return PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {Config.JumpRequirement.USD()}.");
                        }
                        break;

                    case Attributes.Steal:
                        if (deaContext.Cash < Config.StealRequirement)
                        {
                            return PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {Config.StealRequirement.USD()}.");
                        }
                        break;

                    case Attributes.Rob:
                        if (deaContext.Cash < Config.RobRequirement)
                        {
                            return PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {Config.RobRequirement.USD()}.");
                        }
                        break;

                    case Attributes.Bully:
                        if (deaContext.Cash < Config.BullyRequirement)
                        {
                            return PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {Config.BullyRequirement.USD()}.");
                        }
                        break;

                    case Attributes.FiftyX2:
                        if (deaContext.Cash < Config.FiftyX2Requirement)
                        {
                            return PreconditionResult.FromError($"You do not have the permission to use this command.\nRequired cash: {Config.FiftyX2Requirement.USD()}.");
                        }
                        break;

                    default:
                        return PreconditionResult.FromError($"ERROR: The {attribute} attribute is not being handled!");
                    }
                }
                return PreconditionResult.FromSuccess();
            }));
        }
Ejemplo n.º 3
0
 public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return Task.FromResult((context.User as IGuildUser)?.VoiceChannel is null
         ? PreconditionResult.FromError("You must be in a voice channel before invoking this command")
         : PreconditionResult.FromSuccess());
 }
Ejemplo n.º 4
0
 protected sealed override async Task <PreconditionResult> CheckPermissionsAsync(SocketCommandContext Context, SocketGuildUser target) =>
 Context.User is SocketGuildUser
         ? await VerifyUser.BotIsHigher(Context.Guild.CurrentUser, target)
             ? PreconditionResult.FromSuccess()
             : PreconditionResult.FromError($"We cannot {command} members with equal or higher authority than ourselves.")
         : PreconditionResult.FromError("You must be in a server to run this command.");
Ejemplo n.º 5
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext iContext, CommandInfo command, IServiceProvider services)
        {
            var context = iContext as KuuhakuCommandContext;

            if (context == default)
            {
                return(PreconditionResult.FromError("Failed to cast context"));
            }

            var appInfo = await context.Client.GetApplicationInfoAsync();

            if (context.IsPrivate)
            {
                if (this.Permissions == CommandPermissions.Everyone)
                {
                    return(PreconditionResult.FromSuccess());
                }
                if (this.Permissions <= CommandPermissions.BotOwner && context.User.Id == appInfo?.Owner?.Id)
                {
                    return(PreconditionResult.FromSuccess());
                }
                if (this.Permissions <= CommandPermissions.Developer && this.DeveloperIds.Contains(context.User.Id))
                {
                    return(PreconditionResult.FromSuccess());
                }
                return(PreconditionResult.FromError("Command requires higher permissions than vailable in a direct message"));
            }

            if (!(context.User is SocketGuildUser user))
            {
                return(PreconditionResult.FromError("Failed to get User as a Guild User"));
            }

            var repoistory     = services.GetRequiredService <PermissionsRepository>();
            var moderatorRoles = await repoistory.GetRolesAsync(context.Guild, CommandPermissions.Moderator.ToString());

            var adminRoles = await repoistory.GetRolesAsync(context.Guild, CommandPermissions.Admin.ToString());

            if (this.Permissions <= CommandPermissions.Developer && this.DeveloperIds.Contains(context.User.Id))
            {
                return(PreconditionResult.FromSuccess());
            }
            if (this.Permissions <= CommandPermissions.BotOwner && context.User.Id == appInfo?.Owner?.Id)
            {
                return(PreconditionResult.FromSuccess());
            }
            if (this.Permissions <= CommandPermissions.ServerOwner && user.Id == context.Guild.Owner.Id)
            {
                return(PreconditionResult.FromSuccess());
            }
            if (this.Permissions <= CommandPermissions.Admin && adminRoles.Intersect(user.Roles.Select(r => r.Id)).Any())
            {
                return(PreconditionResult.FromSuccess());
            }
            if (this.Permissions <= CommandPermissions.Moderator && moderatorRoles.Intersect(user.Roles.Select(r => r.Id)).Any())
            {
                return(PreconditionResult.FromSuccess());
            }
            if (this.Permissions == CommandPermissions.Everyone)
            {
                return(PreconditionResult.FromSuccess());
            }
            return(PreconditionResult.FromError("Insufficient Permissions"));
        }
Ejemplo n.º 6
0
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider service)
 {
     // Disabled commands can't execute.
     return(Task.FromResult(PreconditionResult.FromError("Command disabled.")));
 }
Ejemplo n.º 7
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            AccessLevel access = await GetPermissionAsync(context).ConfigureAwait(false); // Get the acccesslevel for this context

            return(access >= AccessLevel?PreconditionResult.FromSuccess() : PreconditionResult.FromError("Insufficient permissions"));
        }
Ejemplo n.º 8
0
 // Override the CheckPermissions method
 public override async Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     // If this command was executed by that user, return a success
     return(Whitelist.Contains(context.User.Id) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("You must be the owner of the bot to run this command."));
 }
        /// <summary>
        /// Checks the permission to use the command.
        /// </summary>
        /// <param name="context">The context of the command.</param>
        /// <param name="command">The command used.</param>
        /// <param name="map">The dependency map.</param>
        /// <returns></returns>
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider map)
        {
            if (!(map.GetService(typeof(BlacklistUserContext)) is BlacklistUserContext db) || context.Guild == null)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }

            return(db.BlacklistUserBindings.Any(b => b.GuildId == context.Guild.Id && b.UserId == context.User.Id) ? Task.FromResult(PreconditionResult.FromError("You are not allowed to use commands on this server.")) : Task.FromResult(PreconditionResult.FromSuccess()));
        }
Ejemplo n.º 10
0
        ParseResult kowalski_analysis(APIEndpoint cmd, Match rgxMatch)
        {
            context.Endpoint = cmd; // temporary for PathRegex
            int weight        = 0;
            var cnt           = System.Activator.CreateInstance(cmd.Module.Type, context);
            var commandBase   = (APIBase)cnt;
            var preconditions = new List <APIPrecondition>();
            var final         = new ParseResult(cmd);

            final.CommandBase = commandBase;

            var ORS      = new Dictionary <string, List <PreconditionResult> >();
            var ANDS     = new Dictionary <string, List <PreconditionResult> >();
            var building = new List <APIPrecondition>();

            building.AddRange(cmd.Preconditions);
            Type parent = commandBase.GetType();

            do
            {
                var attrs = parent.GetCustomAttributes <APIPrecondition>();
                building.AddRange(attrs);
                parent = parent.BaseType;
            } while (parent != null);
            building.Reverse();
            foreach (var nextThing in building)
            {
                var previousThing = preconditions.FirstOrDefault(x => x.TypeId == nextThing.TypeId);
                if (previousThing != null)
                {
                    if (!previousThing.CanChildOverride(nextThing))
                    {
                        continue;
                    }
                    preconditions.Remove(previousThing);
                }
                preconditions.Add(nextThing);
            }
            foreach (var pred in preconditions)
            {
                if (string.IsNullOrWhiteSpace(pred.OR))
                {
                    ANDS.TryAdd(pred.AND, new List <PreconditionResult>());
                }
                else
                {
                    ORS.TryAdd(pred.OR, new List <PreconditionResult>());
                    if (!string.IsNullOrWhiteSpace(pred.AND))
                    {
                        ANDS.TryAdd(pred.AND, new List <PreconditionResult>());
                    }
                }
            }

            bool requireExcessQueryMatch = true;

            foreach (var pred in preconditions)
            {
                if (pred is RequireNoExcessQuery rqp)
                {
                    requireExcessQueryMatch = rqp.Required;
                }
                PreconditionResult result = null;
                try
                {
                    result = pred.Check(context);
                }
                catch (HaltExecutionException e)
                {
                    final.WithException(e);
                    result = PreconditionResult.FromError(e.ToString());
                }
                if (ORS.TryGetValue(pred.OR, out var orls))
                {
                    orls.Add(result);
                }
                if ((string.IsNullOrWhiteSpace(pred.AND) && string.IsNullOrWhiteSpace(pred.OR)) ||
                    !string.IsNullOrWhiteSpace(pred.AND))
                {
                    if (ANDS.TryGetValue(pred.AND, out var andls))
                    {
                        andls.Add(result);
                    }
                }
            }

            foreach (var or in ORS.Keys)
            {
                var ls         = ORS[or];
                var anySuccess = ls.FirstOrDefault(x => x.IsSuccess);
                if (anySuccess == null)
                {
                    return(final.WithError($"{string.Join(",", ls.Where(x => !x.IsSuccess).Select(x => x.ErrorReason))}"));
                }
            }

            weight += 5;

            foreach (var and in ANDS.Keys)
            {
                var ls         = ANDS[and];
                var anyFailure = ls.FirstOrDefault(x => x.IsSuccess == false);
                if (anyFailure != null)
                {
                    return(final.WithError($"{string.Join(",", ls.Where(x => !x.IsSuccess).Select(x => x.ErrorReason))}"));
                }
            }

            weight += 5;

            var serverName = (RequireServerName)preconditions.Last(x => x is RequireServerName);

            if (serverName.Domain == context.Host)
            {
                weight += 5;
            }

            var args       = new List <object>();
            var paramaters = cmd.Function.GetParameters();

            foreach (var param in paramaters)
            {
                string value = null;
                if (cmd.Regexs.TryGetValue(param.Name, out var pattern))
                {
                    var match = rgxMatch.Groups[param.Name];
                    value = match.Value;
                }
                else
                {
                    value = context.GetQuery(param.Name);
                }
                if (value == null && param.IsOptional == false)
                {
                    return(final.WithError($"No argument specified for required item {param.Name}"));
                }
                if (value == null)
                {
                    args.Add(param.DefaultValue);
                    continue;
                }
                if (param.ParameterType == typeof(string))
                {
                    args.Add(Uri.UnescapeDataString(value));
                }
                else
                {
                    var typeResult = Program.AttemptParseInput(value, param.ParameterType);
                    if (typeResult.IsSuccess)
                    {
                        args.Add(typeResult.BestMatch);
                    }
                    else
                    {
                        return(final.WithError($"Could not parse value for {param.Name} as {param.ParameterType.Name}: {typeResult.ErrorReason}"));
                    }
                }
            }
            weight += args.Count;
            foreach (var key in context.GetAllKeys())
            {
                var para = paramaters.FirstOrDefault(x => x.Name == key);
                if (para == null && requireExcessQueryMatch)
                {
                    return(final.WithError($"Unknown argument specified: {key}"));
                }
            }
            weight         += 50;
            final.Arguments = args;
            return(final);
        }
Ejemplo n.º 11
0
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(Task.FromResult(_ebans.Any(x => x == context.User.Id || context.User.Username.ToLower().Contains("eban"))
         ? PreconditionResult.FromError("User is an eban")
         : PreconditionResult.FromSuccess()));
 }
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 => context.Guild.OwnerId == context.User.Id ?
 Task.FromResult(PreconditionResult.FromSuccess()) :
 Task.FromResult(PreconditionResult.FromError("User is not owner of the current guild"));
Ejemplo n.º 13
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext iContext, CommandInfo command, IServiceProvider services)
        {
            var context = iContext as SocketCommandContext;

            if (context.Channel is IDMChannel)
            {
                return(Task.FromResult(PreconditionResult.FromError("This is a Guild command")));
            }

            try
            {
                var server = services.GetRequiredService <DatabaseHandler>().Execute <GuildModel>(DatabaseHandler.Operation.LOAD, null, context.Guild.Id.ToString());

                var originalLevel = defaultPermissionLevel;

                var resultInfo = new AccessResult();

                if (server.Settings.CustomCommandPermissions.CustomizedPermission.Any())
                {
                    // Check for a command match
                    var match = server.Settings.CustomCommandPermissions.CustomizedPermission.FirstOrDefault(x => x.IsCommand && x.Name.Equals(command.Name, StringComparison.OrdinalIgnoreCase));
                    if (match != null)
                    {
                        defaultPermissionLevel  = match.Setting;
                        resultInfo.IsCommand    = true;
                        resultInfo.IsOverridden = true;
                        resultInfo.MatchName    = match.Name;
                    }
                }

                if (defaultPermissionLevel == DefaultPermissionLevel.AllUsers)
                {
                    return(Task.FromResult(PreconditionResult.FromSuccess()));
                }

                if (defaultPermissionLevel == DefaultPermissionLevel.Registered)
                {
                    if (server.Users.Any(x => x.UserID == context.User.Id))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Moderators)
                {
                    if (context.User.CastToSocketGuildUser().IsModeratorOrHigher(server.Settings.Moderation, context.Client))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Administrators)
                {
                    if (context.User.CastToSocketGuildUser().IsAdminOrHigher(server.Settings.Moderation, context.Client))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.ServerOwner)
                {
                    if (context.User.Id == context.Guild.OwnerId ||
                        context.Client.GetApplicationInfoAsync().Result.Owner.Id == context.User.Id)
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.BotOwner)
                {
                    if (context.Client.GetApplicationInfoAsync().Result.Owner.Id == context.User.Id)
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }

                return(Task.FromResult(PreconditionResult.FromError($"You do not have the access level of {defaultPermissionLevel}, which is required to run this command\n" +
                                                                    $"Default: {originalLevel}\n" +
                                                                    $"New Level: {defaultPermissionLevel}\n" +
                                                                    $"IsCommand: {resultInfo.IsCommand}\n" +
                                                                    $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                                                    $"Match Name: {resultInfo.MatchName}\n" +
                                                                    $"Command Name: {command.Name}")));
            }
            catch (Exception e)
            {
                LogHandler.LogMessage(e.ToString(), LogSeverity.Critical);
                return(Task.FromResult(PreconditionResult.FromError($"Permissions Error, please report this to Passive")));
            }
        }
Ejemplo n.º 14
0
 public static void Set(ParameterInfo info, ref PreconditionResult result)
 {
     result = PreconditionResult.FromError($"{info.Name} must be a positive, nonzero number.");
 }
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var currentUserPermission = RequiredPermission.GuildMember;

            if (context.Message.Channel is SocketGuildChannel)
            {
                var guildUser = await context.Guild.GetUserAsync(context.Message.Author.Id).ConfigureAwait(false);

                // Guild Administrator
                if (guildUser.GuildPermissions.Administrator)
                {
                    currentUserPermission = RequiredPermission.GuildAdministrator;
                }
            }

            // Discord App Owner
            var botOwner = (await context.Client.GetApplicationInfoAsync()).Owner;

            if (context.Message.Author.Id == botOwner.Id)
            {
                currentUserPermission = RequiredPermission.DiscordAppOwner;
            }

            return(currentUserPermission >= RequiredPermission?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"This command require {RequiredPermission.ToString()} permission and above."));
        }
Ejemplo n.º 16
0
 public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo executingCommand, IDependencyMap depMap) =>
 Task.FromResult((NadekoBot.Credentials.IsOwner(context.User) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
        // Override the CheckPermissions method
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo executingCommand, IServiceProvider map)
        {
            var settings = map.GetService <BotSettings>();

            return(Task.FromResult(context.User.Id == settings.OwnerId ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("You must be the owner of the bot.")));
        }
        /// <inheritdoc />
        public override async Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider map)
        {
            if (context.Channel is IPrivateChannel)
            {
                return(PreconditionResult.FromSuccess());
            }

            var chan = context.Channel as ITextChannel;
            var user = context.User;
            var svc  = map.GetService <PermissionsService>();

            if (svc != null)
            {
                using (var config = svc.ConfigStore.Load())
                {
                    if (IsModuleWhitelisted(config.GetChannelModuleWhitelist(chan).Concat(config.GetGuildModuleWhitelist(context.Guild)), command.Module.Name))
                    {
                        if (Permission == MinimumPermission.BotOwner)
                        {
                            try
                            {
                                var ownerId = (await context.Client.GetApplicationInfoAsync().ConfigureAwait(false)).Owner.Id;
                                return(user.Id == ownerId
                                    ? PreconditionResult.FromSuccess()
                                    : PreconditionResult.FromError("Insufficient permission."));
                            }
                            catch (HttpException)
                            {
                                return(PreconditionResult.FromError("Not logged in as a bot."));
                            }
                        }
                        else if (Permission == MinimumPermission.Special &&
                                 config.GetSpecialPermissionUsersList(chan).Contains(user.Id))
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else if (Permission <= MinimumPermission.GuildOwner &&
                                 context.Guild?.OwnerId == user.Id)
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else if (Permission <= MinimumPermission.AdminRole &&
                                 (user as IGuildUser)?.RoleIds.Any(r => r == config.GetGuildAdminRole(context.Guild)) == true)
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else if (Permission <= MinimumPermission.ModRole &&
                                 (user as IGuildUser)?.RoleIds.Any(r => r == config.GetGuildModRole(context.Guild)) == true)
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else if (Permission == MinimumPermission.Everyone)
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else
                        {
                            return(PreconditionResult.FromError("Insufficient permission."));
                        }
                    }
                    else
                    {
                        return(PreconditionResult.FromError("Command not whitelisted"));
                    }
                }
            }
            else
            {
                return(PreconditionResult.FromError("PermissionService not found."));
            }
        }
Ejemplo n.º 19
0
 public override PreconditionResult Check(APIContext context)
 {
     return((context.User?.Id ?? 0) == 144462654201790464
         ? PreconditionResult.FromSuccess()
         : PreconditionResult.FromError("Only the bot's owner may access this"));
 }
Ejemplo n.º 20
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var config = (Configuration)services.GetService(typeof(Configuration));

            if (config.Owners.Contains(context.User.Id))
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }

            return(Task.FromResult(context.Channel.Id == 205878045859381257 ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("This must be ran in #bot-palace.")));
        }
Ejemplo n.º 21
0
        /// <summary>
        ///     This will check whether or not a user has permissions to use a command/module
        /// </summary>
        /// <param name="context">The Command Context</param>
        /// <param name="command">The command being invoked</param>
        /// <param name="services">The service provider</param>
        /// ///
        /// <returns>Success if the user is the owner of the current guild</returns>
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            // If the command is invoked in a DM channel we return an error
            if (context.Channel is IDMChannel)
            {
                return(Task.FromResult(PreconditionResult.FromError("This is a guild only command!")));
            }

            var database = services.GetRequiredService <DatabaseHandler>().Execute <GuildModel>(DatabaseHandler.Operation.LOAD, null, context.Guild.Id);

            // Check to see if the current user's ID matches the guild owners
            return(Task.FromResult(database?.Settings.Nsfw.Enabled == true ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("NSFW is disabled in this guild. This can be enabled in the general setup module.")));
        }
Ejemplo n.º 22
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context.Message.Channel is SocketDMChannel || context.Message.Channel is SocketGroupChannel)
            {
                return(PreconditionResult.FromError("This command requires to be in Guild context."));
            }

            var sqliteService = services.GetRequiredService <ISQLiteService>();

            var clientId   = context.Client.CurrentUser.Id.ToString();
            var guildId    = context.Guild.Id.ToString();
            var moduleName = command.Module.Name;

            var discordAppDetailTableId = await sqliteService.GetDiscordAppDetailTableIdAsync(context.Client.CurrentUser.Id.ToString());

            if (discordAppDetailTableId == null)
            {
                return(PreconditionResult.FromError("Missing DiscordAppDetail record from the database."));
            }

            return(discordGuildModuleModel?.Active ?? false?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"This command require {command.Module.Name} to be active in this guild."));
        }
Ejemplo n.º 23
0
 public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(Task.FromResult((context.Guild == null) ? PreconditionResult.FromError("This command needs to be typed in a guild.") : PreconditionResult.FromSuccess()));
 }
Ejemplo n.º 24
0
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var config = (Configuration)services.GetService(typeof(Configuration));

            return(Task.FromResult((config.NSFWChannels.Contains(context.Channel.Id) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("This doesn't work here."))));
        }
Ejemplo n.º 25
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var sqliteDatabaseService = services.GetRequiredService <SqliteDatabaseService>();

            var currentUserPermission = RequiredPermission.GuildMember;

            using (var databaseContext = sqliteDatabaseService.GetContext(true))
            {
                if (context.Message.Channel is SocketGuildChannel)
                {
                    //var discordChannelTable = await databaseContext.GetDiscordChannelTableAsync(context.Client.CurrentUser.Id, context.Guild.Id, context.Channel.Id, DiscordChannelTableIncludedEntities.DiscordGuildModeratorTable | DiscordChannelTableIncludedEntities.DiscordChannelModeratorTable).ConfigureAwait(false);

                    //var guildUser = await context.Guild.GetUserAsync(context.Message.Author.Id).ConfigureAwait(false);

                    //if (discordChannelTable != null)
                    //{
                    //    // Channel Moderator
                    //    if (discordChannelTable.DiscordChannelModerators.Any(a => a.Type == DiscordChannelModeratorType.Role && guildUser.RoleIds.Contains(a.Value) ||
                    //                                                              a.Type == DiscordChannelModeratorType.User && a.Value == context.User.Id))
                    //        currentUserPermission = RequiredPermission.ChannelModerator;

                    //    // Guild Moderator
                    //    if (discordChannelTable.DiscordGuild.DiscordGuildModerators.Any(a => a.Type == DiscordGuildModeratorType.Role && guildUser.RoleIds.Contains(a.Value) ||
                    //                                                                         a.Type == DiscordGuildModeratorType.User && a.Value == context.User.Id))
                    //        currentUserPermission = RequiredPermission.GuildModerator;

                    //    // Guild Administrator
                    //    if (guildUser.GuildPermissions.Administrator)
                    //        currentUserPermission = RequiredPermission.GuildAdministrator;
                    //}
                }

                // Discord App Owner
                var botOwner = (await context.Client.GetApplicationInfoAsync()).Owner;

                if (context.Message.Author.Id == botOwner.Id)
                {
                    currentUserPermission = RequiredPermission.DiscordAppOwner;
                }
                else
                {
                    //var isAnOwner = Enumerable.FirstOrDefault((await databaseContext.DiscordAppTable.Where(a => a.ClientId == context.Client.CurrentUser.Id)
                    //        .Select(a => new
                    //        {
                    //            discordAppOwner = a.DiscordAppOwners.Any(b => b.UserId == context.User.Id)
                    //        }).ToListAsync().ConfigureAwait(false))
                    //    .Select(a => a.discordAppOwner));

                    //if (isAnOwner)
                    //    currentUserPermission = RequiredPermission.DiscordAppOwner;
                }

                // Global Discord App Owner
                var isAGlobalOwner = await databaseContext.DiscordAppOwnerTable.Where(a => a.DiscordAppId == null && a.UserId == context.User.Id).AnyAsync().ConfigureAwait(false);

                if (isAGlobalOwner)
                {
                    currentUserPermission = RequiredPermission.GlobalDiscordAppOwner;
                }
            }

            return(currentUserPermission >= RequiredPermission?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"This command require {RequiredPermission.ToString()} permission and above."));
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     This will check whether or not a user has permissions to use a command/module
        /// </summary>
        /// <param name="context">The message context</param>
        /// <param name="command">The command being invoked</param>
        /// <param name="services">The service provider</param>
        /// ///
        /// <returns>
        ///     A precondition result dictating whether or not the command is allowed to run.
        /// </returns>
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context.Channel is IDMChannel)
            {
                return(Task.FromResult(PreconditionResult.FromError("Administrator permissions are only accessible through a guild.")));
            }

            // Check whether or not the user is the Bot owner.
            var own = context.Client.GetApplicationInfoAsync();

            if (own.Result.Owner.Id == context.User.Id)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }

            // If we have allow admin permissions toggled on we allow users who have the permissions in the server
            var guildUser = context.User as IGuildUser;
            var guild     = services.GetRequiredService <DatabaseHandler>().Execute <GuildModel>(DatabaseHandler.Operation.LOAD, null, context.Guild.Id);

            if (allowAdministrator && guildUser.GuildPermissions.Administrator)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }

            // check to see if the user has an admin role in the server
            // Return an error stating the user is not an admin
            return(Task.FromResult(guild.Moderation.AdminRoleIDs.Any(x => guildUser.RoleIds.Contains(x)) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("User is Not an Admin!")));
        }
Ejemplo n.º 27
0
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var config = (Configuration)services.GetService(typeof(Configuration));

            return(Task.FromResult((config.Owners.Contains(context.User.Id) || context.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("You must be a bot owner to run this command."))));
        }
Ejemplo n.º 28
0
        public override async Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var level = await GetLevel(context, services.GetService <MongoClient>()).ConfigureAwait(false);

            return(level >= _level?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"Insufficient permissions! Required level: {_level}"));
        }
Ejemplo n.º 29
0
 public override Task <PreconditionResult> CheckPermissions(IUserMessage context, Command executingCommand, object moduleInstance) =>
 Task.FromResult((FaultyBot.Credentials.IsOwner(context.Author) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
Ejemplo n.º 30
0
        // Override the CheckPermissions method
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var dbContext = services.GetService <BotDbContext>();
            var serverId  = context?.Guild?.Id;

            if (serverId == null)
            {
                Console.WriteLine("ServerId null");
                return(Task.FromResult(PreconditionResult.FromError("Not a whitelisted server")));
            }
            var result = dbContext.Leaderboards.Any(x => x.ServerId == serverId.ToString()) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not a whitelisted server");

            Console.WriteLine($"whitelited seerver requirements success - {result.IsSuccess}");
            return(Task.FromResult(result));
        }