Search in sources :

Example 1 with RegisteredCommand

use of net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand in project Utility by anweisen.

the class DefaultResultHandler method handle.

@Override
public void handle(@Nonnull CommandManager manager, @Nonnull CommandEvent event, @Nonnull CommandResultInfo result) {
    if (!result.getType().isUserMistake())
        return;
    String defaultMessageName = getDefaultMessageName(result);
    // Custom error message
    if (result.getErrorMessage() != null) {
        sendMessage(event, result.getErrorMessage().getFirst(), result.getErrorMessage().getSecond());
        return;
    }
    if (result.getType() == CommandProcessResult.INCORRECT_ARGUMENTS) {
        RegisteredCommand command = result.getCommand() != null ? result.getCommand() : result.getCommandsMatchingName().size() == 1 ? result.getCommandsMatchingName().get(0) : null;
        if (command == null) {
            String headerMessageName = defaultMessageName + "-multiple";
            String entryMessageName = headerMessageName + "-entry";
            StringBuilder builder = new StringBuilder();
            builder.append(getMessage(event, headerMessageName).asString());
            List<String> commands = new ArrayList<>(result.getCommandsMatchingName().size());
            for (RegisteredCommand current : result.getCommandsMatchingName()) {
                commands.add(getMessage(event, entryMessageName).asString(buildFullSyntax(result, current)));
            }
            Collections.sort(commands);
            for (String current : commands) {
                builder.append("\n").append(current);
            }
            event.reply(builder).queue();
        } else {
            sendMessage(event, defaultMessageName, buildFullSyntax(result, command));
        }
        return;
    }
    // Some results require arguments or changed names but are handled standard
    Object[] arguments = new Object[0];
    if (result.getType() == CommandProcessResult.INVALID_SCOPE) {
        defaultMessageName += "-" + (result.getCommand().getOptions().getScope() == CommandScope.GUILD ? "guild" : "private");
    } else if (result.getType() == CommandProcessResult.COOLDOWN) {
        arguments = new Object[] { NumberFormatter.TIME.format(result.getCoolDown() + 0.1) };
    } else if (result.getType() == CommandProcessResult.UNKNOWN_COMMAND) {
        arguments = new Object[] { CommandHelper.removeMarkdown(result.getCommandName(), true) };
    }
    sendMessage(event, defaultMessageName, arguments);
}
Also used : ArrayList(java.util.ArrayList) RegisteredCommand(net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand)

Example 2 with RegisteredCommand

use of net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand in project Utility by anweisen.

the class AnnotatedCommandResolver method resolve.

@Nonnull
@Override
public Collection<RegisteredCommand> resolve(@Nonnull Object command, @Nonnull CommandManager manager) {
    List<RegisteredCommand> commands = new ArrayList<>();
    boolean isClass = command instanceof Class;
    Class<?> clazz = isClass ? (Class<?>) command : command.getClass();
    for (Method method : ReflectionUtils.getMethodsAnnotatedWith(clazz, Command.class)) {
        Class<?>[] parameters = method.getParameterTypes();
        // Ignore instance commands when registering via class
        if (!Modifier.isStatic(method.getModifiers()) && isClass)
            continue;
        if (parameters.length != 2)
            throw new IllegalArgumentException("Cannot register " + method + ", parameter count is not 2");
        if (!parameters[0].isAssignableFrom(CommandEvent.class) || !parameters[1].isAssignableFrom(CommandArguments.class))
            throw new IllegalArgumentException("Cannot register " + method + ", parameters are not (" + CommandEvent.class.getName() + ", " + CommandArguments.class.getName() + ")");
        RegisteredCommand registeredCommand = new RegisteredCommand(command, method, manager);
        commands.add(registeredCommand);
    }
    return commands;
}
Also used : ArrayList(java.util.ArrayList) RegisteredCommand(net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand) Method(java.lang.reflect.Method) Nonnull(javax.annotation.Nonnull)

Example 3 with RegisteredCommand

use of net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand in project Utility by anweisen.

the class SlashCommandHelper method acquireCommand.

@Nonnull
private IBaseCommandData<?, ?> acquireCommand(@Nonnull RegisteredCommand command) {
    String name = command.getOptions().getFirstName();
    List<String> subcommandNames = new ArrayList<>(Arrays.asList(name.split(" ")));
    String parentName = subcommandNames.get(0);
    ICommandData parentRootCommand = slashCommands.computeIfAbsent(parentName, key -> new ICommandData(parentName));
    switch(subcommandNames.size()) {
        default:
            throw new IllegalArgumentException("Discord only supports 3 chained command names for subcommands in slashcommands (got " + subcommandNames.size() + ": '" + name + "')");
        case 1:
            return parentRootCommand;
        case 2:
            {
                String commandName = subcommandNames.get(1);
                ISubcommandData commandData = new ISubcommandData(commandName);
                parentRootCommand.addSubcommand(commandData);
                return commandData;
            }
        case 3:
            {
                String subCommandName = subcommandNames.get(1);
                ISubcommandGroupData subcommandGroup = parentRootCommand.getSubcommandGroups().stream().filter(data -> data.getName().equals(subCommandName)).findFirst().orElseGet(() -> {
                    ISubcommandGroupData result = new ISubcommandGroupData(subCommandName);
                    parentRootCommand.addSubcommandGroup(result);
                    return result;
                });
                String commandName = subcommandNames.get(2);
                ISubcommandData commandData = new ISubcommandData(commandName);
                subcommandGroup.addSubcommand(commandData);
                return commandData;
            }
    }
}
Also used : PrintWriter(java.io.PrintWriter) IBaseCommandData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.IBaseCommandData) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) CommandData(net.dv8tion.jda.api.interactions.commands.build.CommandData) ISubcommandGroupData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandGroupData) WrappedException(net.anweisen.utilities.common.collection.WrappedException) RequiredArgument(net.anweisen.utilities.jda.manager.hooks.registered.RequiredArgument) RegisteredCommand(net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand) ICommandData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ICommandData) ISubcommandData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandData) CommandManager(net.anweisen.utilities.jda.manager.CommandManager) Nonnull(javax.annotation.Nonnull) StringBuilderPrintWriter(net.anweisen.utilities.common.collection.StringBuilderPrintWriter) ISubcommandData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandData) ISubcommandGroupData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandGroupData) ICommandData(net.anweisen.utilities.jda.manager.impl.slashcommands.build.ICommandData) Nonnull(javax.annotation.Nonnull)

Example 4 with RegisteredCommand

use of net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand in project Utility by anweisen.

the class DefaultCommandManager method handleCommand00.

protected Object handleCommand00(@Nonnull CommandPreProcessInfo info, @Nonnull Callback callback, @Nonnull String prefix, @Nonnull String content) {
    String lower = content.toLowerCase();
    List<RegisteredCommand> matchingName = new ArrayList<>();
    Optional<Tuple<String, RegisteredCommand>> optional = findCommand(lower, matchingName);
    if (!optional.isPresent()) {
        if (matchingName.isEmpty()) {
            return callback.call(CommandProcessResult.UNKNOWN_COMMAND, prefix, content);
        } else if (matchingName.size() == 1) {
            RegisteredCommand matchingCommand = matchingName.get(0);
            doCommonChecks(matchingCommand, callback, prefix, matchingCommand.getOptions().getFirstName(), info);
            return callback.call(new CommandResultInfo(CommandProcessResult.INCORRECT_ARGUMENTS, matchingName, matchingCommand.getOptions().getFirstName(), prefix));
        } else {
            return callback.call(new CommandResultInfo(CommandProcessResult.INCORRECT_ARGUMENTS, matchingName, null, prefix));
        }
    }
    Tuple<String, RegisteredCommand> pair = optional.get();
    String commandName = pair.getFirst();
    RegisteredCommand command = pair.getSecond();
    if (doCommonChecks(command, callback, prefix, commandName, info) == CALLBACK_RESULT)
        return CALLBACK_RESULT;
    if (command.getCoolDown().isOnCoolDown(info.getUser(), info.isFromGuild() ? info.getMember().getGuild() : null))
        return callback.call(new CommandResultInfo(CommandProcessResult.COOLDOWN, command, commandName, prefix, command.getCoolDown().getCoolDown(info.getUser(), info.isFromGuild() ? info.getMember().getGuild() : null)));
    command.getCoolDown().renewCoolDown(info.getUser(), info.isFromGuild() ? info.getMember().getGuild() : null);
    String stripped = content.substring(commandName.length()).trim();
    CommandEvent event = eventCreator.createEvent(this, info, command, useEmbeds);
    if (command.getOptions().getAutoSendTyping() && info.getMessage() != null)
        info.getChannel().sendTyping().queue();
    ArgumentParseResult parsed = parseArguments(command, stripped, event);
    if (parsed.success == null)
        return callback.call(new CommandResultInfo(CommandProcessResult.INCORRECT_ARGUMENTS, command, commandName, prefix, parsed.failure));
    CommandArguments args = new CommandArgumentsImpl(parsed.success.getFirst(), parsed.success.getSecond());
    if (command.getOptions().isAsync()) {
        executor.submit(() -> execute0(command, callback, event, args, prefix, commandName));
    } else {
        execute0(command, callback, event, args, prefix, commandName);
    }
    return null;
}
Also used : CommandResultInfo(net.anweisen.utilities.jda.manager.process.CommandResultInfo) CommandArguments(net.anweisen.utilities.jda.manager.hooks.event.CommandArguments) CommandEvent(net.anweisen.utilities.jda.manager.hooks.event.CommandEvent) CommandArgumentsImpl(net.anweisen.utilities.jda.manager.impl.entities.CommandArgumentsImpl) RegisteredCommand(net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand) Tuple(net.anweisen.utilities.common.collection.pair.Tuple)

Example 5 with RegisteredCommand

use of net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand in project Utility by anweisen.

the class DefaultCommandManager method findCommand.

@Nonnull
public Optional<Tuple<String, RegisteredCommand>> findCommand(@Nonnull String input, @Nonnull Collection<RegisteredCommand> matchingName) {
    for (RegisteredCommand command : commands) {
        for (String name : command.getOptions().getName()) {
            boolean beginsWithName = input.startsWith(name);
            if (!(beginsWithName || name.startsWith(input)))
                continue;
            matchingName.add(command);
            if (!beginsWithName)
                continue;
            if (input.length() > name.length() && !input.substring(name.length()).startsWith(" "))
                continue;
            RequiredArgument[] arguments = command.getArguments();
            String argumentInput = input.substring(name.length()).trim();
            if (!isArgumentLengthAssignable(argumentInput, arguments))
                continue;
            return Optional.of(Tuple.of(name, command));
        }
    }
    return Optional.empty();
}
Also used : RequiredArgument(net.anweisen.utilities.jda.manager.hooks.registered.RequiredArgument) RegisteredCommand(net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand) Nonnull(javax.annotation.Nonnull)

Aggregations

RegisteredCommand (net.anweisen.utilities.jda.manager.hooks.registered.RegisteredCommand)5 Nonnull (javax.annotation.Nonnull)3 ArrayList (java.util.ArrayList)2 RequiredArgument (net.anweisen.utilities.jda.manager.hooks.registered.RequiredArgument)2 PrintWriter (java.io.PrintWriter)1 Method (java.lang.reflect.Method)1 java.util (java.util)1 StringBuilderPrintWriter (net.anweisen.utilities.common.collection.StringBuilderPrintWriter)1 WrappedException (net.anweisen.utilities.common.collection.WrappedException)1 Tuple (net.anweisen.utilities.common.collection.pair.Tuple)1 CommandManager (net.anweisen.utilities.jda.manager.CommandManager)1 CommandArguments (net.anweisen.utilities.jda.manager.hooks.event.CommandArguments)1 CommandEvent (net.anweisen.utilities.jda.manager.hooks.event.CommandEvent)1 CommandArgumentsImpl (net.anweisen.utilities.jda.manager.impl.entities.CommandArgumentsImpl)1 IBaseCommandData (net.anweisen.utilities.jda.manager.impl.slashcommands.build.IBaseCommandData)1 ICommandData (net.anweisen.utilities.jda.manager.impl.slashcommands.build.ICommandData)1 ISubcommandData (net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandData)1 ISubcommandGroupData (net.anweisen.utilities.jda.manager.impl.slashcommands.build.ISubcommandGroupData)1 CommandResultInfo (net.anweisen.utilities.jda.manager.process.CommandResultInfo)1 JDA (net.dv8tion.jda.api.JDA)1