Esempio n. 1
0
        public async Task <ExecuteCommandResult> ExecuteCommand(CommandContext context, string input, IDependencyMap dependencyMap = null, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Exception)
        {
            dependencyMap = dependencyMap ?? DependencyMap.Empty;

            var searchResult = _commandService.Search(context, input);

            if (!searchResult.IsSuccess)
            {
                return(new ExecuteCommandResult(null, null, searchResult));
            }

            var commands = searchResult.Commands;

            for (int i = commands.Count - 1; i >= 0; i--)
            {
                var preconditionResult = await commands[i].CheckPreconditionsAsync(context).ConfigureAwait(false);
                if (!preconditionResult.IsSuccess)
                {
                    if (commands.Count == 1)
                    {
                        return(new ExecuteCommandResult(null, null, preconditionResult));
                    }
                    else
                    {
                        continue;
                    }
                }

                var parseResult = await commands[i].ParseAsync(context, searchResult, preconditionResult).ConfigureAwait(false);
                if (!parseResult.IsSuccess)
                {
                    if (parseResult.Error == CommandError.MultipleMatches)
                    {
                        TypeReaderValue[] argList, paramList;
                        switch (multiMatchHandling)
                        {
                        case MultiMatchHandling.Best:
                            argList     = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
                            paramList   = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
                            parseResult = ParseResult.FromSuccess(argList, paramList);
                            break;
                        }
                    }

                    if (!parseResult.IsSuccess)
                    {
                        if (commands.Count == 1)
                        {
                            return(new ExecuteCommandResult(null, null, parseResult));
                        }
                        else
                        {
                            continue;
                        }
                    }
                }

                var             cmd          = commands[i].Command;
                bool            resetCommand = cmd.Name == "resetperms";
                var             module       = cmd.Module.GetTopLevelModule();
                PermissionCache pc;
                if (context.Guild != null)
                {
                    pc = Permissions.Cache.GetOrAdd(context.Guild.Id, (id) =>
                    {
                        using (var uow = DbHandler.UnitOfWork())
                        {
                            var config = uow.GuildConfigs.PermissionsFor(context.Guild.Id);
                            return(new PermissionCache()
                            {
                                Verbose = config.VerbosePermissions,
                                RootPermission = config.RootPermission,
                                PermRole = config.PermissionRole.Trim().ToLowerInvariant(),
                            });
                        }
                    });
                    int index;
                    if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(context.Message, cmd.Aliases.First(), module.Name, out index))
                    {
                        var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand((SocketGuild)context.Guild)}** is preventing this action.";
                        return(new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)));
                    }


                    if (module.Name == typeof(Permissions).Name)
                    {
                        var guildUser = (IGuildUser)context.User;
                        if (!guildUser.GetRoles().Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant()) && guildUser.Id != guildUser.Guild.OwnerId)
                        {
                            return(new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")));
                        }
                    }

                    int price;
                    if (Permissions.CommandCostCommands.CommandCosts.TryGetValue(cmd.Aliases.First().Trim().ToLowerInvariant(), out price) && price > 0)
                    {
                        var success = await CurrencyHandler.RemoveCurrencyAsync(context.User.Id, $"Running {cmd.Name} command.", price).ConfigureAwait(false);

                        if (!success)
                        {
                            return(new ExecuteCommandResult(cmd, pc, SearchResult.FromError(CommandError.Exception, $"Insufficient funds. You need {price}{NadekoBot.BotConfig.CurrencySign} to run this command.")));
                        }
                    }
                }

                // Bot will ignore commands which are ran more often than what specified by
                // GlobalCommandsCooldown constant (miliseconds)
                if (!UsersOnShortCooldown.Add(context.Message.Author.Id))
                {
                    return(new ExecuteCommandResult(cmd, null, SearchResult.FromError(CommandError.Exception, $"You are on a global cooldown.")));
                }

                if (CmdCdsCommands.HasCooldown(cmd, context.Guild, context.User))
                {
                    return(new ExecuteCommandResult(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on a cooldown for you.")));
                }

                return(new ExecuteCommandResult(cmd, null, await commands[i].ExecuteAsync(context, parseResult, dependencyMap)));
            }

            return(new ExecuteCommandResult(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")));
        }
Esempio n. 2
0
        public async Task <Tuple <Command, PermissionCache, IResult> > ExecuteCommand(IUserMessage message, string input, IGuild guild, IUser user, MultiMatchHandling multiMatchHandling = MultiMatchHandling.Best)
        {
            var searchResult = _commandService.Search(message, input);

            if (!searchResult.IsSuccess)
            {
                return(new Tuple <Command, PermissionCache, IResult>(null, null, searchResult));
            }

            var commands = searchResult.Commands;

            for (int i = commands.Count - 1; i >= 0; i--)
            {
                var preconditionResult = await commands[i].CheckPreconditions(message);
                if (!preconditionResult.IsSuccess)
                {
                    if (commands.Count == 1)
                    {
                        return(new Tuple <Command, PermissionCache, IResult>(null, null, searchResult));
                    }
                    else
                    {
                        continue;
                    }
                }

                var parseResult = await commands[i].Parse(message, searchResult, preconditionResult);
                if (!parseResult.IsSuccess)
                {
                    if (parseResult.Error == CommandError.MultipleMatches)
                    {
                        TypeReaderValue[] argList, paramList;
                        switch (multiMatchHandling)
                        {
                        case MultiMatchHandling.Best:
                            argList     = parseResult.ArgValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
                            paramList   = parseResult.ParamValues.Select(x => x.Values.OrderByDescending(y => y.Score).First()).ToArray();
                            parseResult = ParseResult.FromSuccess(argList, paramList);
                            break;
                        }
                    }

                    if (!parseResult.IsSuccess)
                    {
                        if (commands.Count == 1)
                        {
                            return(new Tuple <Command, PermissionCache, IResult>(null, null, parseResult));
                        }
                        else
                        {
                            continue;
                        }
                    }
                }

                var             cmd          = commands[i];
                bool            resetCommand = cmd.Name == "ResetPermissions";
                PermissionCache pc;
                if (guild != null)
                {
                    pc = Permissions.Cache.GetOrAdd(guild.Id, (id) =>
                    {
                        using (var uow = DbHandler.UnitOfWork())
                        {
                            var config = uow.GuildConfigs.PermissionsFor(guild.Id);
                            return(new PermissionCache()
                            {
                                Verbose = config.VerbosePermissions,
                                RootPermission = config.RootPermission,
                                PermRole = config.PermissionRole.Trim().ToLowerInvariant(),
                            });
                        }
                    });
                    int index;
                    if (!resetCommand && !pc.RootPermission.AsEnumerable().CheckPermissions(message, cmd.Text, cmd.Module.Name, out index))
                    {
                        var returnMsg = $"Permission number #{index + 1} **{pc.RootPermission.GetAt(index).GetCommand(guild)}** is preventing this action.";
                        return(new Tuple <Command, PermissionCache, IResult>(cmd, pc, SearchResult.FromError(CommandError.Exception, returnMsg)));
                    }


                    if (cmd.Module.Source.Name == typeof(Permissions).Name) //permissions, you must have special role
                    {
                        if (!((IGuildUser)user).Roles.Any(r => r.Name.Trim().ToLowerInvariant() == pc.PermRole.Trim().ToLowerInvariant()))
                        {
                            return(new Tuple <Command, PermissionCache, IResult>(cmd, pc, SearchResult.FromError(CommandError.Exception, $"You need the **{pc.PermRole}** role in order to use permission commands.")));
                        }
                    }
                }


                if (CmdCdsCommands.HasCooldown(cmd, guild, user))
                {
                    return(new Tuple <Command, PermissionCache, IResult>(cmd, null, SearchResult.FromError(CommandError.Exception, $"That command is on cooldown for you.")));
                }

                return(new Tuple <Command, PermissionCache, IResult>(commands[i], null, await commands[i].Execute(message, parseResult)));
            }

            return(new Tuple <Command, PermissionCache, IResult>(null, null, SearchResult.FromError(CommandError.UnknownCommand, "This input does not match any overload.")));
        }