Exemplo n.º 1
0
        public async ValueTask <AdminCommandResult> GetCommandsAsync(Module module)
        {
            var commands = CommandUtilities.EnumerateAllCommands(module);
            var groups   = commands.GroupBy(x => x.FullAliases[0]).ToList();

            var pages = DefaultPaginator.GeneratePages(groups, 1024, group => new StringBuilder()
                                                       .Append(Markdown.Bold(FormatCommands(group)))
                                                       .AppendNewline(Localize($"info_command_{group.Key.Replace(' ', '_')}")).ToString(),
                                                       builderFunc: () => new LocalEmbedBuilder().WithSuccessColor()
                                                       .WithTitle(Localize("info_module_commands", Markdown.Code(module.Name))));

            /*
             * var pages = DefaultPaginator.GeneratePages(groups, 15, group => new EmbedFieldBuilder()
             *  //    .WithName(new StringBuilder(Config.DefaultPrefix)
             *  //        .AppendJoin($"\n{Config.DefaultPrefix}", group.First().FullAliases).Tag)
             *  .WithName(FormatCommands(group))
             *  .WithValue(Localize($"info_command_{group.Key.Replace(' ', '_')}")),
             *  embedFunc: builder => builder.WithSuccessColor()
             *      .WithTitle(Localize("info_module_commands", Format.Code(module.Name))));
             */

            if (pages.Count > 1)
            {
                await Pagination.SendPaginatorAsync(Context.Channel, new DefaultPaginator(pages, 0), pages[0]);

                return(CommandSuccess());
            }

            return(CommandSuccess(embed: pages[0].Embed));
        }
Exemplo n.º 2
0
        public static string FormatModuleShort(Module module)
        {
            var firstAlias = module.FullAliases.FirstOrDefault();

            if (firstAlias is null)
            {
                return(null);
            }

            return(Format.Bold(Format.Code(firstAlias)));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Modifies the command.
        /// </summary>
        /// <param name="command">The command you want to modify.</param>
        /// <param name="builder">The modifications you want to make.</param>
        /// <param name="mBuilder">Modifications you want applied to the <see cref="ModuleBuilder"/> that command belongs.</param>
        public static void Modify(this Command command, Action <CommandBuilder> builder,
                                  Action <ModuleBuilder> mBuilder = null)
        {
            Type type = command.GetType();

            CommandService commands = command.Service;

            const string singatureName = "SignatureIdentifier";

            FieldInfo field = type.GetField(singatureName, Flags);

            if (field is null)
            {
                throw new QuahuRenamedException(singatureName);
            }

            (bool hasRemainder, string signature) = ((bool, string))field.GetValue(command);

            Module module = command.Module;

            commands.RemoveModule(module);
            commands.AddModule(module.Type, moduleBuilder => {
                mBuilder?.Invoke(moduleBuilder);

                (bool HasRemainder, string Signature)BuildSignature(CommandBuilder commandBuilder)
                {
                    var sb = new StringBuilder();
                    var f  = false;

                    for (var i = 0; i < commandBuilder.Parameters.Count; i++)
                    {
                        ParameterBuilder parameter = commandBuilder.Parameters[i];

                        if (parameter.IsRemainder)
                        {
                            f = true;
                        }

                        sb.Append(parameter.Type).Append(';');
                    }

                    return(f, sb.ToString());
                }
Exemplo n.º 4
0
 public static string SanitizeName(this Module m)
 => m.Name.Replace("Module", string.Empty);
Exemplo n.º 5
0
        private async Task HandleCommandErroredAsync(IResult result, FoxCommandContext ctx)
        {
            if (result is CommandNotFoundResult)
            {
                string cmdName;
                var    toLev = "";
                var    index = 0;
                var    split = ctx.Message.Content.Substring(ctx.Prefix.Length).Split(_commands.Separator, StringSplitOptions.RemoveEmptyEntries);

                do
                {
                    toLev += (index == 0 ? "" : _commands.Separator) + split[index];

                    cmdName = toLev.Levenshtein(_commands);
                    index++;
                } while (string.IsNullOrWhiteSpace(cmdName) && index < split.Length);

                if (string.IsNullOrWhiteSpace(cmdName))
                {
                    return;
                }

                string cmdParams = null;
                while (index < split.Length)
                {
                    cmdParams += " " + split[index++];
                }

                var tryResult = await _commands.ExecuteAsync(cmdName + cmdParams, ctx, _services);

                if (tryResult.IsSuccessful)
                {
                    return;
                }

                await HandleCommandErroredAsync(tryResult, ctx);
            }

            var str = new StringBuilder();

            Command command = null;
            Module  module  = null;

            switch (result)
            {
            case ChecksFailedResult err:
                command = err.Command;
                module  = err.Module;
                str.AppendLine("The following check(s) failed:");
                foreach ((var check, var error) in err.FailedChecks)
                {
                    str.AppendLine($"[`{((FoxCheckBaseAttribute)check).Name}`]: `{error}`");
                }
                break;

            case TypeParseFailedResult err:
                command = err.Parameter.Command;
                str.AppendLine(err.Reason);
                break;

            case ArgumentParseFailedResult err:
                command = err.Command;
                str.AppendLine($"The syntax of the command `{command.FullAliases[0]}` was wrong.");
                break;

            case OverloadsFailedResult err:
                command = err.FailedOverloads.First().Key;
                str.AppendLine($"I can't find any valid overload for the command `{command.Name}`.");
                foreach (var overload in err.FailedOverloads)
                {
                    str.AppendLine($" -> `{overload.Value.Reason}`");
                }
                break;

            case ParameterChecksFailedResult err:
                command = err.Parameter.Command;
                module  = err.Parameter.Command.Module;
                str.AppendLine("The following parameter check(s) failed:");
                foreach ((var check, var error) in err.FailedChecks)
                {
                    str.AppendLine($"[`{check.Parameter.Name}`]: `{error}`");
                }
                break;

            case ExecutionFailedResult _:     //this should be handled in the CommandErrored event or in the FoxResult case.
            case CommandNotFoundResult _:     //this is handled at the beginning of this method with levenshtein thing.
                break;

            case FoxResult err:
                command = err.Command;     //ctx.Command is not null because a FoxResult is returned in execution step.
                str.AppendLine(err.Message);
                break;

            case CommandOnCooldownResult err:
                command = err.Command;
                var remainingTime = err.Cooldowns.OrderByDescending(x => x.RetryAfter).FirstOrDefault();
                str.AppendLine($"You're being rate limited! Please retry after {remainingTime.RetryAfter.Humanize()}.");
                break;

            default:
                str.AppendLine($"Unknown error: {result}");
                break;
            }

            if (str.Length == 0)
            {
                return;
            }

            var embed = new DiscordEmbedBuilder
            {
                Color = ConfigurationService.EmbedColor,
                Title = "Something went wrong!"
            };

            embed.WithFooter($"Type '{ctx.Prefix}help {command?.FullAliases[0] ?? ctx.Command?.FullAliases[0] ?? ""}' for more information.");

            embed.AddField(Formatter.Underline("Command/Module"), command?.Name ?? ctx.Command?.Name ?? module?.Name ?? "Unknown command...", true);
            embed.AddField(Formatter.Underline("Author"), ctx.User.FormatUser(), true);
            embed.AddField(Formatter.Underline("Error(s)"), str.ToString());

            _logger.Print(LogLevel.Error, "Fox", $"{ctx.User.Id} - {ctx.Guild.Id} ::> Command errored: {command?.Name ?? "-unknown command-"}");
            await ctx.RespondAsync("", false, embed.Build());
        }
Exemplo n.º 6
0
 public static async ValueTask <bool> CanShowModuleAsync(VolteContext ctx, Module module) =>
 await module.RunChecksAsync(ctx) is SuccessfulResult;