Example #1
0
        public override Task <PreconditionResult> CheckPermissionsAsync(
            ICommandContext context,
            CommandInfo command,
            IServiceProvider services)
        {
            IGuildUser user = context.User as IGuildUser;

            if (context.User.IsWebhook)
            {
                return(Task.FromResult(_webhookNames.Contains(context.User.Username) ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Command must be used by an authorized webhook.")));
            }

            if (this.GuildPermission.HasValue)
            {
                if (user == null)
                {
                    return(Task.FromResult(PreconditionResult.FromError(this.NotAGuildErrorMessage ?? "Command must be used in a guild channel.")));
                }
                if (!user.GuildPermissions.Has(this.GuildPermission.Value))
                {
                    return(Task.FromResult(PreconditionResult.FromError(this.ErrorMessage ?? string.Format("User requires guild permission {0}.", (object)this.GuildPermission.Value))));
                }
            }
            Discord.ChannelPermission?channelPermission = this.ChannelPermission;
            if (channelPermission.HasValue)
            {
                ChannelPermissions     channelPermissions = !(context.Channel is IGuildChannel channel) ? ChannelPermissions.All((IChannel)context.Channel) : user.GetPermissions(channel);
                ref ChannelPermissions local = ref channelPermissions;
                channelPermission = this.ChannelPermission;
                long num = (long)channelPermission.Value;
                if (!local.Has((Discord.ChannelPermission)num))
                {
                    string reason = this.ErrorMessage;
                    if (reason == null)
                    {
                        channelPermission = this.ChannelPermission;
                        reason            = string.Format("User requires channel permission {0}.", (object)channelPermission.Value);
                    }
                    return(Task.FromResult(PreconditionResult.FromError(reason)));
                }
            }
Example #2
0
        /// <inheritdoc />
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context.Channel is IPrivateChannel)
            {
                return(PreconditionResult.FromSuccess());
            }

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

            if (svc != null)
            {
                //using (var config = svc.ReadOnlyConfig)
                using var config = svc.LoadConfig();
                var adminRoleId = config.GetGuildAdminRole(context.Guild)?.Id;
                var modRoleId   = config.GetGuildModRole(context.Guild)?.Id;

                var wlms = config.GetChannelModuleWhitelist(chan).Concat(config.GetGuildModuleWhitelist(context.Guild));
                if (IsModuleWhitelisted(wlms, command.Module))
                {
                    // Candidate switch expression
                    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, DiscordComparers.UserComparer))
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else if (Permission <= MinimumPermission.GuildOwner &&
                             context.Guild.OwnerId == user.Id)
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else if (Permission <= MinimumPermission.AdminRole &&
                             adminRoleId.HasValue &&
                             user.RoleIds.Contains(adminRoleId.Value))
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else if (Permission <= MinimumPermission.ModRole &&
                             modRoleId.HasValue &&
                             user.RoleIds.Contains(modRoleId.Value))
                    {
                        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."));
            }
        }
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context.User.Id == 194538654159339520)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }


            Permission perm;
            var        user = context.User as IGuildUser;

            if (user == null)
            {
                return(Task.FromResult(PreconditionResult.FromError("Command must be used in a guild channel")));
            }
            if ((user as SocketGuildUser).Roles.Any(x => x.Permissions.Administrator == true))
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }
            if (user.Id == context.Guild.OwnerId)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }


            using (var db = new DatabaseContext())
            {
                perm = db.Permissions.FirstOrDefault(x => x.TargetId == context.User.Id && x.GuildId == context.Guild.Id && x.CommandName == command.Name);
                if (perm == null)
                {
                    perm = db.Permissions.FirstOrDefault(x => user.RoleIds.Any() && x.GuildId == context.Guild.Id && x.CommandName == command.Name);
                }
            }


            if (perm == null)
            {
                return(Task.FromResult(PreconditionResult.FromError("User doesn't have the required permission")));
            }


            if (perm.IsRole)
            {
                if (user.RoleIds.Any(x => x == perm.TargetId))
                {
                    return(Task.FromResult(PreconditionResult.FromSuccess()));
                }
                else
                {
                    return(Task.FromResult(PreconditionResult.FromError("User doesn't have the required permission")));
                }
            }
            else
            {
                if (perm.TargetId == user.Id)
                {
                    return(Task.FromResult(PreconditionResult.FromSuccess()));
                }
                else
                {
                    return(Task.FromResult(PreconditionResult.FromError("User doesn't have the required permission")));
                }
            }
        }
Example #4
0
        public async Task CommandHelpAsync([Summary("Optional string containing the command to see detailed information about.")] string commandToDescribe = "")
        {
            var commandList = _commandService.Commands;

            if (commandToDescribe == "")
            {
                foreach (var command in commandList)
                {
                    //If user has permissions required to use the command, display the command
                    PreconditionResult pr = await command.CheckPreconditionsAsync(Context, _serviceProvider);
                    if (pr.IsSuccess)
                    {
                        EmbedBuilder eb = new EmbedBuilder();

                        eb.AddField("Command: ", command.Name ?? "");

                        if (command.Summary != null)
                        {
                            eb.AddField("Summary: ", command.Summary);
                        }

                        await ReplyAsync("", false, eb);
                    }
                }
            }
            else
            {
                var command = commandList.Where(cmd => cmd.Name == commandToDescribe);

                if (command.Any())
                {
                    CommandInfo cmdInfo = command.FirstOrDefault();

                    EmbedBuilder eb = new EmbedBuilder();

                    eb.AddField("Command", cmdInfo.Name);

                    if (cmdInfo.Summary != null)
                    {
                        eb.AddField("Summary", cmdInfo.Summary);
                    }

                    if (cmdInfo.Preconditions.Any())
                    {
                        eb.AddField("Preconditions", string.Join('\n', cmdInfo.Preconditions));
                    }

                    if (cmdInfo.Parameters.Any())
                    {
                        eb.AddField("Parameters", string.Join('\n', cmdInfo.Parameters.Select(x => $"{x.Name} - {x.Summary}")));
                    }

                    if (cmdInfo.Remarks != null)
                    {
                        eb.AddField("Remarks", cmdInfo.Remarks);
                    }

                    eb.WithColor(Color.DarkGreen);

                    await ReplyAsync("", false, eb);
                }
                else
                {
                    await ReplyAsync("Sorry, I don't think that's a valid command. Use !commands to view a list of recognized commands.");
                }
            }
        }
Example #5
0
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var gatherManager = services.GetRequiredService <GatherManager>();
            var config        = gatherManager.GetConfigAsync(context.Channel.Id).Result;

            return(Task.FromResult(config != null && config.GatherAllowed ? PreconditionResult.FromSuccess() : PreconditionResult.FromError(string.Empty)));
        }
Example #6
0
 // Override the CheckPermissions method
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(Task.FromResult(GlobalConfig.OwnerIds.Any(x => x == context.User.Id)
         ? PreconditionResult.FromSuccess()
         : PreconditionResult.FromError("You must be the bot owner to do this.")));
 }
Example #7
0
        public async Task DMHelp()
        {
            EmbedBuilder extraHelpEmbed = new EmbedBuilder();

            extraHelpEmbed.AddField("Wiki", $"[Click Here]({GITHUB}/wiki)", true);
            extraHelpEmbed.AddField("Submit bugs, enhancements, and contribute", $"[Click Here]({GITHUB})", true);
            await Context.User.SendMessageAsync(embed : extraHelpEmbed.Build());

            IUserMessage msg = await Context.User.SendMessageAsync("Fetching commands...");

            List <ICommandContext> contexts = new() { Context };

            foreach (SocketGuild guild in Context.User.MutualGuilds)
            {
                var channel = guild.Channels.First(channel => channel is IMessageChannel) as IMessageChannel;

                contexts.Add(new WriteableCommandContext
                {
                    Client  = Context.Client,
                    Message = Context.Message,
                    Guild   = guild,
                    Channel = channel,
                    User    = guild.GetUser(Context.User.Id)
                });
            }

            foreach (ModuleInfo module in _service.Modules)
            {
                EmbedBuilder embed = new()
                {
                    Title = module.Name
                };

                foreach (CommandInfo command in module.Commands)
                {
                    bool isAllowed = false;

                    foreach (ICommandContext ctx in contexts)
                    {
                        PreconditionResult check = await command.CheckPreconditionsAsync(ctx);

                        if (check.IsSuccess)
                        {
                            isAllowed = true;
                            break;
                        }
                    }

                    if (isAllowed)
                    {
                        embed.AddField(MakeCommandField(command));
                    }
                }

                if (embed.Fields.Count > 0)
                {
                    await ReplyAsync(embed : embed.Build());
                }
            }

            msg.DeleteAsync();
            await ReplyAsync("These are all the commands you have permissions to use");
        }
Example #8
0
 public async override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(PreconditionResult.FromError("This command is currently disabled, reason:\n" + reason));
 }
Example #9
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (!(context.Channel is SocketGuildChannel gChannel))
            {
                return(PreconditionResult.FromError("This command can only be run in an ELO bot server."));
            }

            if (!(context.User is SocketGuildUser gUser))
            {
                return(PreconditionResult.FromError("You are not recognised as a guild user."));
            }

            /*
             * var eloService = services.GetRequiredService<ELOService>();
             * if (eloService.PermissionBypass)
             * {
             *  await eloService.PopulateOwner();
             *  if (context.User.Id == eloService.OwnerId)
             *  {
             *      return PreconditionResult.FromSuccess();
             *  }
             * }
             */

            var permissionService = services.GetRequiredService <PermissionService>();

            if (permissionService.PermissionBypass)
            {
                await permissionService.PopulateOwner();

                if (context.User.Id == permissionService.OwnerId)
                {
                    return(PreconditionResult.FromSuccess());
                }
            }

            var result = permissionService.EvaluateCustomPermission(command.Name, gUser, out var level);

            if (result.Item1 == true)
            {
                return(PreconditionResult.FromSuccess());
            }
            else if (result.Item1 == false)
            {
                return(PreconditionResult.FromError($"You do not have permission to use this command Level: {level}"));
            }
            else
            {
                if (Level == PermissionLevel.Registered)
                {
                    if (gUser.IsRegistered(out var _, false))
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else
                    {
                        return(PreconditionResult.FromError("You must be registered in order to run this command."));
                    }
                }

                if (Level == PermissionLevel.Moderator)
                {
                    if (gUser.GuildPermissions.Administrator || gUser.Roles.Any(x => x.Id == result.Item2.ModId || x.Id == result.Item2.AdminId || x.Permissions.Administrator))
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else
                    {
                        return(PreconditionResult.FromError("You must be a moderator in order to run this command."));
                    }
                }

                if (Level == PermissionLevel.ELOAdmin)
                {
                    using (var db = new Database())
                    {
                        if (gUser.GuildPermissions.Administrator || gUser.Roles.Any(x => x.Id == result.Item2.AdminId || x.Permissions.Administrator))
                        {
                            return(PreconditionResult.FromSuccess());
                        }
                        else
                        {
                            return(PreconditionResult.FromError("You must be an elo admin in order to run this command."));
                        }
                    }
                }

                if (Level == PermissionLevel.ServerAdmin)
                {
                    if (gUser.GuildPermissions.Administrator)
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else
                    {
                        return(PreconditionResult.FromError("You must be a server administrator in order to run this command."));
                    }
                }

                if (Level == PermissionLevel.Owner)
                {
                    if (gUser.Id == gUser.Guild.OwnerId)
                    {
                        return(PreconditionResult.FromSuccess());
                    }
                    else
                    {
                        return(PreconditionResult.FromError("You must be the server owner in order to run this command."));
                    }
                }
            }

            return(PreconditionResult.FromError($"You do not have permission to run this command. Level: {Level}"));
        }
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(services.GetService <IAdministrationService>().IsUserAdmin(context.User)
         ? Task.FromResult(PreconditionResult.FromSuccess())
         : Task.FromResult(PreconditionResult.FromError($"User not authorized for \"{command.Name}\" command")));
 }
Example #11
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")));
Example #12
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());
 }
Example #13
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();
            }));
        }
Example #14
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."));
        }
Example #15
0
        private static async Task MessageReceived(SocketMessage socketMessage)
        {
            // Skip if this is not a real user
            if (socketMessage.Source == MessageSource.Webhook || socketMessage.Source == MessageSource.System)
            {
                return;
            }

            // Skip bots that aren't QA
            if (socketMessage.Source == MessageSource.Bot && socketMessage.Author.Id != 563718045806362642)
            {
                return;
            }

            // Get the SocketUserMessage
            SocketUserMessage userMessage = socketMessage as SocketUserMessage;

            // Create the CommandContext
            SocketCommandContext commandContext = new SocketCommandContext(DiscordClient, userMessage);

            // Ignore empty messages and bots
            if (commandContext.Message == null || commandContext.Message.Content.Length == 0)
            {
                return;
            }

            // Check if this message has a command
            int commandPosition = 0;

            if (userMessage.HasStringPrefix(Configuration.LoadedConfiguration.DiscordConfig.CommandPrefix, ref commandPosition))
            {
                // Trigger typing
                //await commandContext.Channel.TriggerTypingAsync();

                // Execute the command
                IResult result = await CommandService.ExecuteAsync(commandContext, commandPosition, null);

                if (!result.IsSuccess)
                {
                    switch (result.Error)
                    {
                    case CommandError.UnknownCommand:
                        //await DiscordUtil.SendErrorMessageByLocalizedDescription(commandContext.Guild, commandContext.Channel, "discord.error.unknown_command");
                        //
                        //break;

                        return;     // ignore

                    case CommandError.BadArgCount:
                        await DiscordUtil.SendErrorMessageByLocalizedDescription(commandContext.Guild, commandContext.Channel, "discord.error.bad_arguments");

                        break;

                    case CommandError.UnmetPrecondition:
                        // Get the PreconditionResult
                        PreconditionResult preconditionResult = (PreconditionResult)result;

                        // Check if the error reason contains a localizable
                        string description = result.ErrorReason;
                        if (result.ErrorReason.StartsWith("~loc"))
                        {
                            // Localize the error reason
                            await DiscordUtil.SendErrorMessageByLocalizedDescription(commandContext.Guild, commandContext.Channel, description.Split(',')[1]);
                        }
                        else
                        {
                            // Localize the error reason
                            await DiscordUtil.SendErrorMessageByDescription(commandContext.Guild, commandContext.Channel, result.ErrorReason);
                        }

                        break;

                    case CommandError.Exception:
                        // Get the IResult as an ExecuteResult
                        ExecuteResult executeResult = (ExecuteResult)result;

                        // Send the error message
                        await DiscordUtil.SendErrorMessageByException(commandContext.Guild, commandContext.Channel, commandContext.User, $"with command``{userMessage.Content}``", executeResult.Exception);

                        break;

                    default:
                        // Get the type
                        string type = (result.Error != null) ? result.Error.Value.GetType().Name : "Unknown";

                        // Send the error message
                        await DiscordUtil.SendErrorMessageByTypeAndMessage(commandContext.Guild, commandContext.Channel, type, result.ErrorReason);

                        break;
                    }
                }
                else
                {
                    // Declare a variable to hold the length
                    int length;

                    // Get the index of the first space
                    int spaceIdx = userMessage.Content.IndexOf(' ');

                    // Check if there is no space
                    if (spaceIdx == -1)
                    {
                        // Default to the command string length
                        length = userMessage.Content.Length - commandPosition;
                    }
                    else
                    {
                        // Get the length of the string in between the space and the command
                        length = spaceIdx - commandPosition;
                    }

                    // Get the command
                    string command = userMessage.Content.Substring(commandPosition, length);

                    // Check if this is not command stats
                    if (command != "commandstats")
                    {
                        // Increment this command in the statistics
                        Configuration.LoadedConfiguration.DiscordConfig.CommandStatistics.AddOrUpdate(command, 1, (cmd, val) => val + 1);
                    }
                }
            }
            else
            {
                // Acquire the semaphore
                await InteractiveMessageSemaphore.WaitAsync();

                // Check if this will match an interactive message
                // TODO a better way?
                IEnumerable <InteractiveMessage> messages = ActiveInteractiveMessages.Where(x => x.Channel.Id == socketMessage.Channel.Id &&
                                                                                            x.User.Id == socketMessage.Author.Id).ToList();

                // Release the semaphore
                InteractiveMessageSemaphore.Release();

                foreach (InteractiveMessage interactiveMessage in messages)
                {
                    try
                    {
                        await interactiveMessage.TextMessageReceived(socketMessage);
                    }
                    catch (Exception e)
                    {
                        await DiscordUtil.SendErrorMessageByException(commandContext.Guild, commandContext.Channel, commandContext.User, $"in {interactiveMessage.GetType().Name}.TextMessageReceived()", e);
                    }
                }
            }
        }
Example #16
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)
                {
                    LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                          $"New Level: {defaultPermissionLevel}\n" +
                                          $"IsCommand: {resultInfo.IsCommand}\n" +
                                          $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                          $"Match Name: {resultInfo.MatchName}\n" +
                                          $"Command Name: {command.Name}");
                    return(Task.FromResult(PreconditionResult.FromSuccess()));
                }

                if (defaultPermissionLevel == DefaultPermissionLevel.Registered)
                {
                    if (server.Users.Any(x => x.UserID == context.User.Id))
                    {
                        LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                              $"New Level: {defaultPermissionLevel}\n" +
                                              $"IsCommand: {resultInfo.IsCommand}\n" +
                                              $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                              $"Match Name: {resultInfo.MatchName}\n" +
                                              $"Command Name: {command.Name}");
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Moderators)
                {
                    if (context.User.CastToSocketGuildUser().IsModeratorOrHigher(server.Settings.Moderation, context.Client))
                    {
                        LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                              $"New Level: {defaultPermissionLevel}\n" +
                                              $"IsCommand: {resultInfo.IsCommand}\n" +
                                              $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                              $"Match Name: {resultInfo.MatchName}\n" +
                                              $"Command Name: {command.Name}");
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Administrators)
                {
                    if (context.User.CastToSocketGuildUser().IsAdminOrHigher(server.Settings.Moderation, context.Client))
                    {
                        LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                              $"New Level: {defaultPermissionLevel}\n" +
                                              $"IsCommand: {resultInfo.IsCommand}\n" +
                                              $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                              $"Match Name: {resultInfo.MatchName}\n" +
                                              $"Command Name: {command.Name}");
                        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)
                    {
                        LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                              $"New Level: {defaultPermissionLevel}\n" +
                                              $"IsCommand: {resultInfo.IsCommand}\n" +
                                              $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                              $"Match Name: {resultInfo.MatchName}\n" +
                                              $"Command Name: {command.Name}");
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.BotOwner)
                {
                    if (context.Client.GetApplicationInfoAsync().Result.Owner.Id == context.User.Id)
                    {
                        LogHandler.LogMessage($"Default: {originalLevel}\n" +
                                              $"New Level: {defaultPermissionLevel}\n" +
                                              $"IsCommand: {resultInfo.IsCommand}\n" +
                                              $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                              $"Match Name: {resultInfo.MatchName}\n" +
                                              $"Command Name: {command.Name}");
                        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")));
            }
        }
        public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IServiceProvider prov)
        {
            var t = context.Channel as ITextChannel;

            return(Task.FromResult(t.Topic.Contains($"[{_name}]") ? PreconditionResult.FromError($"Command is disabled in channels containing `[{_name}]` within their topic") : PreconditionResult.FromSuccess()));
        }
Example #18
0
        public Task <PreconditionResult> CheckGuildAsync(ICommandContext commandContext, CommandInfo commandInfo, IServiceProvider serviceProvider)
        {
            ulong id = GetGuildId(commandContext);

            return(Task.FromResult(id == _id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("This command can only be issued in the guild: " + _id.GetGuild() + "!")));
        }
Example #19
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("User is not in a guild")));
            }

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

            // Check to see if the current user's ID matches the guild owners
            return(Task.FromResult(context.Guild.OwnerId == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("User is not the Guild Owner!")));
        }
Example #20
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo executingCommand, IServiceProvider services)
        {
            var creds = (IBotCredentials)services.GetService(typeof(IBotCredentials));

            return(Task.FromResult((creds.IsOwner(context.User) || context.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner"))));
        }
Example #21
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            if (context.Guild == null)
            {
                return(PreconditionResult.FromError(""));
            }

            if (!ConfigManager.IsGuildManaged(context.Guild.Id))
            {
                return(PreconditionResult.FromError($"No config found for guild {context.Guild.Id}"));
            }

            GuildConfig config;

            if ((config = ConfigManager.GetManagedConfig(context.Guild.Id)) == null)
            {
                return(PreconditionResult.FromError(""));
            }

            if (context.User.Id == context.Guild.OwnerId)
            {
                return(PreconditionResult.FromSuccess());
            }

            var commandService = (CommandService)services.GetService(typeof(CommandService));

            if (commandService == null)
            {
                return(PreconditionResult.FromError($"Could not find command service from service provider"));
            }

            var hasPerm = false;
            var cmd     = await BotUtils.SearchCommand(commandService, context, command.Module.Name);

            if (cmd == null)
            {
                return(PreconditionResult.FromError("Module not found"));
            }

            // check if has permission by module name
            cmd     = $"module:{cmd}";
            hasPerm = config.Permissions.MapHasPermissionsFor(cmd);
            if (!hasPerm)
            {
                cmd = await BotUtils.SearchCommand(commandService, context, command.Name);

                if (cmd == null)
                {
                    return(PreconditionResult.FromError("Command not found"));
                }

                hasPerm = config.Permissions.MapHasPermissionsFor(cmd);
                // check if user has permission for command
                if (!hasPerm)
                {
                    hasPerm = config.Permissions.HasPermission(cmd, context.User.Id);
                }
                if (!hasPerm)
                {
                    // check if user has roles that have permission
                    if (!(context.User is IGuildUser guildUser))
                    {
                        return(PreconditionResult.FromError(""));
                    }

                    hasPerm = guildUser.RoleIds.Any(roleId => config.Permissions.HasPermission(cmd, roleId));
                }
            }

            if (config.Permissions.IsBlocked(context.User.Id))
            {
                return(PreconditionResult.FromError("User is blocked"));
            }

            if (!hasPerm)
            {
                return(PreconditionResult.FromError($"No permissions setup for the command `{cmd}` but required to use it."));
            }

            return(PreconditionResult.FromSuccess());
        }
Example #22
0
 public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext Context, CommandInfo command, IServiceProvider services) =>
 Context.User is SocketGuildUser
         ? await modLogsDatabase.ModLogChannel.GetModLogChannelAsync((Context as SocketCommandContext)?.Guild) != null
             ? PreconditionResult.FromSuccess()
             : PreconditionResult.FromError("You must set a mod log to use this command.")
         : PreconditionResult.FromError("You must be in a server to run this command.");
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
        {
            var sqliteService = services.GetRequiredService <ISQLiteService>();

            var currentUserPermission = RequiredPermissions.GuildMember;
            var clientId = context.Client.CurrentUser.Id.ToString();

            if (context.Message.Channel is SocketGuildChannel channel)
            {
                var channelId = context.Message.Channel.Id.ToString();
                var guildId   = channel.Guild.Id.ToString();
                var guildUser = await context.Guild.GetUserAsync(context.Message.Author.Id);

                // Channel Moderator
                var discordChannelModeratorModels = await sqliteService.SQLiteAsyncConnection.Table <DiscordChannelModeratorModel>().Where(a => a.ClientId == clientId && a.ChannelId == channelId).ToArrayAsync();

                foreach (var discordChannelModeratorModel in discordChannelModeratorModels)
                {
                    if (!string.IsNullOrEmpty(discordChannelModeratorModel.RoleId))
                    {
                        foreach (var roleId in guildUser.RoleIds)
                        {
                            if (roleId.ToString() != discordChannelModeratorModel.RoleId)
                            {
                                continue;
                            }

                            currentUserPermission = RequiredPermissions.ChannelModerator;

                            break;
                        }

                        if (currentUserPermission == RequiredPermissions.ChannelModerator)
                        {
                            break;
                        }
                    }
                    else if (!string.IsNullOrEmpty(discordChannelModeratorModel.UserId))
                    {
                        if (context.Message.Author.Id.ToString() != discordChannelModeratorModel.UserId)
                        {
                            continue;
                        }

                        currentUserPermission = RequiredPermissions.ChannelModerator;

                        break;
                    }
                }

                // Guild Moderator
                var discordGuildModeratorModels = await sqliteService.SQLiteAsyncConnection.Table <DiscordGuildModeratorModel>().Where(a => a.ClientId == clientId && a.GuildId == guildId).ToArrayAsync();

                foreach (var discordGuildModeratorModel in discordGuildModeratorModels)
                {
                    if (!string.IsNullOrEmpty(discordGuildModeratorModel.RoleId))
                    {
                        foreach (var roleId in guildUser.RoleIds)
                        {
                            if (roleId.ToString() != discordGuildModeratorModel.RoleId)
                            {
                                continue;
                            }

                            currentUserPermission = RequiredPermissions.GuildModerator;

                            break;
                        }

                        if (currentUserPermission == RequiredPermissions.GuildModerator)
                        {
                            break;
                        }
                    }
                    else if (!string.IsNullOrEmpty(discordGuildModeratorModel.UserId))
                    {
                        if (context.Message.Author.Id.ToString() != discordGuildModeratorModel.UserId)
                        {
                            continue;
                        }

                        currentUserPermission = RequiredPermissions.GuildModerator;

                        break;
                    }
                }

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

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

            if (context.Message.Author.Id == botOwner.Id)
            {
                currentUserPermission = RequiredPermissions.DiscordAppOwner;
            }
            else
            {
                var discordAppOwnerModels = await sqliteService.SQLiteAsyncConnection.Table <DiscordAppOwnerModel>().Where(a => a.ClientId == clientId).ToArrayAsync();

                foreach (var discordAppOwnerModel in discordAppOwnerModels)
                {
                    if (discordAppOwnerModel.UserId != context.Message.Author.Id.ToString())
                    {
                        continue;
                    }

                    currentUserPermission = RequiredPermissions.DiscordAppOwner;

                    break;
                }
            }

            // Global Discord App Owner
            var discordAppOwnerModels2 = await sqliteService.SQLiteAsyncConnection.Table <DiscordAppOwnerModel>().Where(a => a.ClientId == "").ToArrayAsync();

            foreach (var discordAppOwnerModel in discordAppOwnerModels2)
            {
                if (discordAppOwnerModel.UserId != context.Message.Author.Id.ToString())
                {
                    continue;
                }

                currentUserPermission = RequiredPermissions.GlobalDiscordAppOwner;

                break;
            }

            return(currentUserPermission >= RequiredPermission?PreconditionResult.FromSuccess() : PreconditionResult.FromError($"This command require {RequiredPermission.ToString()} permission and above."));
        }
Example #24
0
        public override Task <PreconditionResult> CheckPermissionsAsync(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."))));
        }
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(Task.FromResult(MeetsPermissionLevel(context)
         ? PreconditionResult.FromSuccess()
         : PreconditionResult.FromError($"User does not meet the permission level {_level}.")));
 }
Example #26
0
 public override Task <PreconditionResult> CheckPermissionsAsync(
     ICommandContext context, CommandInfo command, IServiceProvider services)
 => (PokemonData.Ready) ?
 Task.FromResult(PreconditionResult.FromSuccess()) :
 Task.FromResult(PreconditionResult.FromError("data isnt ready yet"));
 public override Task <PreconditionResult> CheckPermissions(ICommandContext context, ParameterInfo parameter, object value, IServiceProvider map)
 {
     if (value is int v && (v < _min || v > _max))
     {
         return(Task.FromResult(PreconditionResult.FromError($"Parameter value must be between {_min} and {_max}.")));
     }
Example #28
0
 public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)
 {
     return(Task.FromResult(PreconditionResult.FromError("This command cannot be run at all.")));
 }
Example #29
0
 public override Task <PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo executingCommand, IDependencyMap depMap) =>
 Task.FromResult((NadekoBot.Credentials.IsOwner(context.User) || NadekoBot.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
Example #30
0
 public override Task <PreconditionResult> CheckPermissions(ICommandContext Context, CommandInfo Command, IDependencyMap Deps)
 => Task.FromResult(PreconditionResult.FromSuccess());
Example #31
0
 private static Task SendPreconditionResult(PreconditionResult result, IStaticResponse response, Stream responseStream, IOwinContext ctx)
 {
     var cacheStatus = result == PreconditionResult.PreconditionFailed
                           ? Constants.Http.StatusCodes.ClientError.PreconditionFailed
                           : Constants.Http.StatusCodes.Redirection.NotModified;
     return SendCacheStatus(response, responseStream, ctx, cacheStatus);
 }