Search in sources :

Example 1 with TextCommandInfo

use of com.freya02.botcommands.internal.prefixed.TextCommandInfo in project BotCommands by freya022.

the class TextCommandComparator method compare.

@Override
public int compare(TextCommandInfo o1, TextCommandInfo o2) {
    final Method o1CommandMethod = o1.getMethod();
    final Method o2CommandMethod = o2.getMethod();
    if (o1CommandMethod == o2CommandMethod)
        return 0;
    if (o1CommandMethod.getParameterTypes()[0] == BaseCommandEvent.class && o2CommandMethod.getParameterTypes()[0] == CommandEvent.class) {
        return -1;
    }
    final int order1 = o1.getOrder();
    final int order2 = o2.getOrder();
    if (order1 != 0 && order2 != 0) {
        if (order1 == order2) {
            LOGGER.warn("Method {} and {} have the same order ({})", Utils.formatMethodShort(o1.getMethod()), Utils.formatMethodShort(o2.getMethod()), order1);
        }
        return Integer.compare(order1, order2);
    }
    final List<? extends TextCommandParameter> o1Parameters = o1.getOptionParameters();
    final List<? extends TextCommandParameter> o2Parameters = o2.getOptionParameters();
    for (int i = 0; i < Math.min(o1Parameters.size(), o2Parameters.size()); i++) {
        if (o1Parameters.get(i).getBoxedType() == o2Parameters.get(i).getBoxedType()) {
            continue;
        }
        if (o1Parameters.get(i).getBoxedType() == String.class) {
            return 1;
        } else {
            return -1;
        }
    }
    return 1;
}
Also used : BaseCommandEvent(com.freya02.botcommands.api.prefixed.BaseCommandEvent) CommandEvent(com.freya02.botcommands.api.prefixed.CommandEvent) BaseCommandEvent(com.freya02.botcommands.api.prefixed.BaseCommandEvent) Method(java.lang.reflect.Method)

Example 2 with TextCommandInfo

use of com.freya02.botcommands.internal.prefixed.TextCommandInfo in project BotCommands by freya022.

the class Utils method generateCommandHelp.

public static EmbedBuilder generateCommandHelp(TextCommandCandidates candidates, BaseCommandEvent event) {
    final EmbedBuilder builder = event.getDefaultEmbed();
    final TextCommandInfo commandInfo = candidates.last();
    final String name = commandInfo.getPath().getFullPath().replace('/', ' ');
    final String description = Utils.getDescription(commandInfo);
    final String prefix = event.getContext().getPrefix();
    final MessageEmbed.AuthorInfo author = builder.isEmpty() ? null : event.getDefaultEmbed().build().getAuthor();
    if (author != null) {
        builder.setAuthor(author.getName() + " – '" + name + "' command", author.getUrl(), author.getIconUrl());
    } else {
        builder.setAuthor('\'' + name + "' command");
    }
    if (description != null) {
        builder.addField("Description", description, false);
    }
    final ArrayList<TextCommandInfo> reversedCandidates = new ArrayList<>(candidates);
    Collections.reverse(reversedCandidates);
    int i = 1;
    for (TextCommandInfo candidate : reversedCandidates) {
        final List<? extends TextCommandParameter> commandParameters = candidate.getOptionParameters();
        final StringBuilder syntax = new StringBuilder("**Syntax**: " + prefix + name + ' ');
        final StringBuilder example = new StringBuilder("**Example**: " + prefix + name + ' ');
        if (candidate.isRegexCommand()) {
            final boolean needsQuote = hasMultipleQuotable(commandParameters);
            for (TextCommandParameter commandParameter : commandParameters) {
                final Class<?> boxedType = commandParameter.getBoxedType();
                final String argName = getArgName(needsQuote, commandParameter, boxedType);
                final String argExample = getArgExample(needsQuote, commandParameter, boxedType);
                final boolean isOptional = commandParameter.isOptional();
                syntax.append(isOptional ? '[' : '`').append(argName).append(isOptional ? ']' : '`').append(' ');
                example.append(argExample).append(' ');
            }
        }
        final String effectiveCandidateDescription = !candidate.hasDescription() ? "" : ("**Description**: " + candidate.getDescription() + "\n");
        if (candidates.size() == 1) {
            builder.addField("Usage", effectiveCandidateDescription + syntax + "\n" + example, false);
        } else {
            builder.addField("Overload #" + i, effectiveCandidateDescription + syntax + "\n" + example, false);
        }
        i++;
    }
    final List<TextCommandCandidates> textSubcommands = event.getContext().findTextSubcommands(commandInfo.getPath());
    if (textSubcommands != null) {
        final String subcommandHelp = textSubcommands.stream().map(TreeSet::first).map(info -> "**" + info.getPath().getNameAt(info.getPath().getNameCount() - commandInfo.getPath().getNameCount()) + "** : " + Utils.getNonBlankDescription(info)).collect(Collectors.joining("\n - "));
        if (!subcommandHelp.isBlank()) {
            builder.addField("Subcommands", subcommandHelp, false);
        }
    }
    final Consumer<EmbedBuilder> descConsumer = commandInfo.getInstance().getDetailedDescription();
    if (descConsumer != null) {
        descConsumer.accept(builder);
    }
    return builder;
}
Also used : BaseCommandEvent(com.freya02.botcommands.api.prefixed.BaseCommandEvent) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) Logger(org.slf4j.Logger) Category(com.freya02.botcommands.api.prefixed.annotations.Category) Emoji(com.freya02.botcommands.api.entities.Emoji) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Logging(com.freya02.botcommands.api.Logging) Supplier(java.util.function.Supplier) Collectors(java.util.stream.Collectors) QuotableRegexParameterResolver(com.freya02.botcommands.api.parameters.QuotableRegexParameterResolver) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) Parameter(java.lang.reflect.Parameter) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) NotNull(org.jetbrains.annotations.NotNull) EmojiOrEmote(com.freya02.botcommands.api.entities.EmojiOrEmote) Description(com.freya02.botcommands.api.prefixed.annotations.Description) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder)

Example 3 with TextCommandInfo

use of com.freya02.botcommands.internal.prefixed.TextCommandInfo in project BotCommands by freya022.

the class BContextImpl method addTextCommand.

public void addTextCommand(TextCommandInfo commandInfo) {
    final CommandPath path = commandInfo.getPath();
    final List<CommandPath> aliases = commandInfo.getAliases();
    textCommandMap.compute(path, (k, v) -> {
        if (v == null)
            return new TextCommandCandidates(commandInfo);
        else
            v.add(commandInfo);
        return v;
    });
    final CommandPath parentPath = path.getParent();
    if (parentPath != null) {
        // Add subcommands to cache
        // If subcommands candidates exist, append, if not then create
        textSubcommandsMap.compute(parentPath, (x, candidates) -> (candidates == null) ? new TextSubcommandCandidates(commandInfo) : candidates.addSubcommand(commandInfo));
    }
    for (CommandPath alias : aliases) {
        textCommandMap.compute(alias, (k, v) -> {
            if (v == null)
                return new TextCommandCandidates(commandInfo);
            else
                v.add(commandInfo);
            return v;
        });
    }
}
Also used : TextSubcommandCandidates(com.freya02.botcommands.internal.prefixed.TextSubcommandCandidates) TextCommandCandidates(com.freya02.botcommands.internal.prefixed.TextCommandCandidates) CommandPath(com.freya02.botcommands.api.application.CommandPath)

Example 4 with TextCommandInfo

use of com.freya02.botcommands.internal.prefixed.TextCommandInfo in project BotCommands by freya022.

the class CommandsBuilderImpl method buildClasses.

private void buildClasses() throws Exception {
    classes.removeIf(c -> {
        try {
            return !ReflectionUtils.isInstantiable(c);
        } catch (IllegalAccessException | InvocationTargetException e) {
            LOGGER.error("An error occurred while trying to find if a class is instantiable", e);
            throw new RuntimeException("An error occurred while trying to find if a class is instantiable", e);
        }
    });
    for (Class<?> aClass : classes) {
        processClass(aClass);
    }
    if (!context.isHelpDisabled()) {
        processClass(HelpCommand.class);
        final TextCommandInfo helpInfo = context.findFirstCommand(CommandPath.of("help"));
        if (helpInfo == null)
            throw new IllegalStateException("HelpCommand did not build properly");
        final HelpCommand help = (HelpCommand) helpInfo.getInstance();
        help.generate();
    }
    prefixedCommandsBuilder.postProcess();
    if (context.getComponentManager() != null) {
        // Load button listeners
        for (Class<?> aClass : classes) {
            componentsBuilder.processClass(aClass);
        }
    } else {
        LOGGER.info("ComponentManager is not set, the Components API, paginators and menus won't be usable");
    }
    applicationCommandsBuilder.postProcess();
    if (context.getComponentManager() != null) {
        componentsBuilder.postProcess();
    }
    eventListenersBuilder.postProcess();
    autocompletionHandlersBuilder.postProcess();
    context.getRegistrationListeners().forEach(RegistrationListener::onBuildComplete);
    LOGGER.info("Finished registering all commands");
}
Also used : RegistrationListener(com.freya02.botcommands.api.RegistrationListener) HelpCommand(com.freya02.botcommands.internal.prefixed.HelpCommand) TextCommandInfo(com.freya02.botcommands.internal.prefixed.TextCommandInfo) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 5 with TextCommandInfo

use of com.freya02.botcommands.internal.prefixed.TextCommandInfo in project BotCommands by freya022.

the class PrefixedCommandsBuilder method checkMethodDuplicates.

private void checkMethodDuplicates() {
    for (TextCommandCandidates command : context.getCommands()) {
        for (TextCommandInfo info : command) {
            for (TextCommandInfo commandInfo : command) {
                if (info == commandInfo)
                    continue;
                final Method commandMethod1 = info.getMethod();
                final Method commandMethod2 = commandInfo.getMethod();
                final List<? extends TextCommandParameter> parameters1 = info.getOptionParameters();
                final List<? extends TextCommandParameter> parameters2 = commandInfo.getOptionParameters();
                if (parameters1.stream().map(CommandParameter::getParameter).collect(Collectors.toList()).equals(parameters2.stream().map(CommandParameter::getParameter).collect(Collectors.toList()))) {
                    throw new IllegalStateException("Method " + Utils.formatMethodShort(commandMethod1) + " has the same parameters as " + Utils.formatMethodShort(commandMethod2));
                }
            }
        }
    }
}
Also used : CommandParameter(com.freya02.botcommands.internal.application.CommandParameter) Method(java.lang.reflect.Method)

Aggregations

BaseCommandEvent (com.freya02.botcommands.api.prefixed.BaseCommandEvent)2 Method (java.lang.reflect.Method)2 Logging (com.freya02.botcommands.api.Logging)1 RegistrationListener (com.freya02.botcommands.api.RegistrationListener)1 CommandPath (com.freya02.botcommands.api.application.CommandPath)1 Emoji (com.freya02.botcommands.api.entities.Emoji)1 EmojiOrEmote (com.freya02.botcommands.api.entities.EmojiOrEmote)1 QuotableRegexParameterResolver (com.freya02.botcommands.api.parameters.QuotableRegexParameterResolver)1 CommandEvent (com.freya02.botcommands.api.prefixed.CommandEvent)1 Category (com.freya02.botcommands.api.prefixed.annotations.Category)1 Description (com.freya02.botcommands.api.prefixed.annotations.Description)1 CommandParameter (com.freya02.botcommands.internal.application.CommandParameter)1 HelpCommand (com.freya02.botcommands.internal.prefixed.HelpCommand)1 TextCommandCandidates (com.freya02.botcommands.internal.prefixed.TextCommandCandidates)1 TextCommandInfo (com.freya02.botcommands.internal.prefixed.TextCommandInfo)1 TextSubcommandCandidates (com.freya02.botcommands.internal.prefixed.TextSubcommandCandidates)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Parameter (java.lang.reflect.Parameter)1 java.util (java.util)1 ThreadLocalRandom (java.util.concurrent.ThreadLocalRandom)1