Search in sources :

Example 1 with OptionType

use of net.dv8tion.jda.api.interactions.commands.OptionType in project JDA by DV8FromTheWorld.

the class OptionData method fromData.

/**
 * Parses the provided serialization back into an OptionData instance.
 * <br>This is the reverse function for {@link #toData()}.
 *
 * @param  json
 *         The serialized {@link DataObject} representing the option
 *
 * @throws net.dv8tion.jda.api.exceptions.ParsingException
 *         If the serialized object is missing required fields
 * @throws IllegalArgumentException
 *         If any of the values are failing the respective checks such as length
 *
 * @return The parsed OptionData instance, which can be further configured through setters
 */
@Nonnull
public static OptionData fromData(@Nonnull DataObject json) {
    String name = json.getString("name");
    String description = json.getString("description");
    OptionType type = OptionType.fromKey(json.getInt("type"));
    OptionData option = new OptionData(type, name, description);
    option.setRequired(json.getBoolean("required"));
    option.setAutoComplete(json.getBoolean("autocomplete"));
    if (type == OptionType.INTEGER || type == OptionType.NUMBER) {
        if (!json.isNull("min_value")) {
            if (json.isType("min_value", DataType.INT))
                option.setMinValue(json.getLong("min_value"));
            else if (json.isType("min_value", DataType.FLOAT))
                option.setMinValue(json.getDouble("min_value"));
        }
        if (!json.isNull("max_value")) {
            if (json.isType("max_value", DataType.INT))
                option.setMaxValue(json.getLong("max_value"));
            else if (json.isType("max_value", DataType.FLOAT))
                option.setMaxValue(json.getDouble("max_value"));
        }
    }
    if (type == OptionType.CHANNEL) {
        option.setChannelTypes(json.optArray("channel_types").map(it -> it.stream(DataArray::getInt).map(ChannelType::fromId).collect(Collectors.toSet())).orElse(Collections.emptySet()));
    }
    json.optArray("choices").ifPresent(choices1 -> choices1.stream(DataArray::getObject).forEach(o -> {
        if (o.isType("value", DataType.FLOAT))
            option.addChoice(o.getString("name"), o.getDouble("value"));
        else if (o.isType("value", DataType.INT))
            option.addChoice(o.getString("name"), o.getLong("value"));
        else
            option.addChoice(o.getString("name"), o.get("value").toString());
    }));
    return option;
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Checks(net.dv8tion.jda.internal.utils.Checks) java.util(java.util) SerializableData(net.dv8tion.jda.api.utils.data.SerializableData) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) DataType(net.dv8tion.jda.api.utils.data.DataType) Command(net.dv8tion.jda.api.interactions.commands.Command) Collectors(java.util.stream.Collectors) ChannelType(net.dv8tion.jda.api.entities.ChannelType) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ChannelType(net.dv8tion.jda.api.entities.ChannelType) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) DataArray(net.dv8tion.jda.api.utils.data.DataArray) Nonnull(javax.annotation.Nonnull)

Example 2 with OptionType

use of net.dv8tion.jda.api.interactions.commands.OptionType in project JDA by DV8FromTheWorld.

the class SlashCommandData method fromData.

/**
 * Parses the provided serialization back into a SlashCommandData instance.
 * <br>This is the reverse function for {@link SlashCommandData#toData()}.
 *
 * @param  object
 *         The serialized {@link DataObject} representing the command
 *
 * @throws net.dv8tion.jda.api.exceptions.ParsingException
 *         If the serialized object is missing required fields
 * @throws IllegalArgumentException
 *         If any of the values are failing the respective checks such as length
 *
 * @return The parsed SlashCommandData instance, which can be further configured through setters
 *
 * @see    CommandData#fromData(DataObject)
 * @see    Commands#fromList(Collection)
 */
@Nonnull
static SlashCommandData fromData(@Nonnull DataObject object) {
    Checks.notNull(object, "DataObject");
    String name = object.getString("name");
    Command.Type commandType = Command.Type.fromId(object.getInt("type", 1));
    if (commandType != Command.Type.SLASH)
        throw new IllegalArgumentException("Cannot convert command of type " + commandType + " to SlashCommandData!");
    String description = object.getString("description");
    DataArray options = object.optArray("options").orElseGet(DataArray::empty);
    CommandDataImpl command = new CommandDataImpl(name, description);
    options.stream(DataArray::getObject).forEach(opt -> {
        OptionType type = OptionType.fromKey(opt.getInt("type"));
        switch(type) {
            case SUB_COMMAND:
                command.addSubcommands(SubcommandData.fromData(opt));
                break;
            case SUB_COMMAND_GROUP:
                command.addSubcommandGroups(SubcommandGroupData.fromData(opt));
                break;
            default:
                command.addOptions(OptionData.fromData(opt));
        }
    });
    return command;
}
Also used : Command(net.dv8tion.jda.api.interactions.commands.Command) CommandDataImpl(net.dv8tion.jda.internal.interactions.CommandDataImpl) DataArray(net.dv8tion.jda.api.utils.data.DataArray) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Nonnull(javax.annotation.Nonnull)

Example 3 with OptionType

use of net.dv8tion.jda.api.interactions.commands.OptionType in project Lauren by Yuhtin.

the class CommandRegistry method argsInterpreter.

private void argsInterpreter(CommandInfo handler, CommandDataImpl commandData, SubcommandData subcommandData) {
    for (val option : handler.args()) {
        val split = option.split("-");
        val argName = split[0];
        OptionType optionType;
        if (argName.contains("@"))
            optionType = OptionType.USER;
        else if (argName.contains("%"))
            optionType = OptionType.ROLE;
        else if (argName.contains("#"))
            optionType = OptionType.CHANNEL;
        else if (argName.contains("!"))
            optionType = OptionType.INTEGER;
        else
            optionType = OptionType.STRING;
        val reformatedName = argName.replace("[", "").replace("]", "").replace("!", "").replace("<", "").replace(">", "").replace("@", "").replace("%", "").replace("#", "");
        val optionData = new OptionData(optionType, reformatedName, split[1], argName.contains("<"));
        if (commandData != null)
            commandData.addOptions(optionData);
        if (subcommandData != null)
            subcommandData.addOptions(optionData);
    }
}
Also used : lombok.val(lombok.val) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType)

Example 4 with OptionType

use of net.dv8tion.jda.api.interactions.commands.OptionType in project dDiscordBot by DenizenScript.

the class DiscordCommandCommand method execute.

@Override
public void execute(ScriptEntry scriptEntry) {
    DiscordBotTag bot = scriptEntry.requiredArgForPrefix("id", DiscordBotTag.class);
    ElementTag commandInstruction = scriptEntry.getElement("instruction");
    DiscordGroupTag group = scriptEntry.getObjectTag("group");
    ElementTag name = scriptEntry.getElement("name");
    ElementTag description = scriptEntry.getElement("description");
    MapTag options = scriptEntry.getObjectTag("options");
    ElementTag enabled = scriptEntry.getElement("enabled");
    ListTag enableFor = scriptEntry.getObjectTag("enable_for");
    ListTag disableFor = scriptEntry.getObjectTag("disable_for");
    if (scriptEntry.dbCallShouldDebug()) {
        Debug.report(scriptEntry, getName(), bot, commandInstruction, group, name, description, options, enabled, enableFor, disableFor);
    }
    if (group != null && group.bot == null) {
        group.bot = bot.bot;
    }
    JDA client = bot.getConnection().client;
    Bukkit.getScheduler().runTaskAsynchronously(DenizenDiscordBot.instance, () -> {
        try {
            if (commandInstruction == null) {
                Debug.echoError(scriptEntry, "Must have a command instruction!");
                scriptEntry.setFinished(true);
                return;
            } else if (name == null) {
                Debug.echoError(scriptEntry, "Must specify a name!");
                scriptEntry.setFinished(true);
                return;
            }
            DiscordCommandInstruction commandInstructionEnum = DiscordCommandInstruction.valueOf(commandInstruction.asString().toUpperCase());
            boolean isEnabled = enabled == null || enabled.asBoolean();
            switch(commandInstructionEnum) {
                case CREATE:
                    {
                        if (description == null) {
                            Debug.echoError(scriptEntry, "Must specify a description!");
                            scriptEntry.setFinished(true);
                            return;
                        }
                        SlashCommandData data = Commands.slash(name.asString(), description.asString());
                        if (options != null) {
                            for (ObjectTag optionObj : options.map.values()) {
                                MapTag option = optionObj.asType(MapTag.class, scriptEntry.getContext());
                                ElementTag typeStr = (ElementTag) option.getObject("type");
                                if (typeStr == null) {
                                    Debug.echoError(scriptEntry, "Command options must specify a type!");
                                    scriptEntry.setFinished(true);
                                    return;
                                }
                                OptionType optionType = OptionType.valueOf(typeStr.toString().toUpperCase());
                                ElementTag optionName = (ElementTag) option.getObject("name");
                                ElementTag optionDescription = (ElementTag) option.getObject("description");
                                ElementTag optionIsRequired = (ElementTag) option.getObject("required");
                                MapTag optionChoices = (MapTag) option.getObject("choices");
                                if (optionName == null) {
                                    Debug.echoError(scriptEntry, "Command options must specify a name!");
                                    scriptEntry.setFinished(true);
                                    return;
                                } else if (optionDescription == null) {
                                    Debug.echoError(scriptEntry, "Command options must specify a description!");
                                    scriptEntry.setFinished(true);
                                    return;
                                }
                                if (optionType == OptionType.SUB_COMMAND) {
                                    data.addSubcommands(new SubcommandData(optionName.asString(), optionDescription.asString()));
                                } else /*
                                        support these later
                                        needs recursive logic

                                        else if (optionType == OptionType.SUB_COMMAND_GROUP) {
                                            data.addSubcommandGroups(new SubcommandGroupData(optionName.asString(), optionDescription.asString()));
                                        }
                                        */
                                {
                                    OptionData optionData = new OptionData(optionType, optionName.asString(), optionDescription.asString(), optionIsRequired == null ? true : optionIsRequired.asBoolean());
                                    if (optionChoices != null) {
                                        if (optionType != OptionType.STRING && optionType != OptionType.INTEGER) {
                                            Debug.echoError(scriptEntry, "Command options with choices must be either STRING or INTEGER!");
                                            scriptEntry.setFinished(true);
                                            return;
                                        }
                                        for (Map.Entry<StringHolder, ObjectTag> subChoiceValue : optionChoices.map.entrySet()) {
                                            MapTag choice = subChoiceValue.getValue().asType(MapTag.class, scriptEntry.getContext());
                                            ElementTag choiceName = (ElementTag) choice.getObject("name");
                                            ElementTag choiceValue = (ElementTag) choice.getObject("value");
                                            if (choiceName == null) {
                                                Debug.echoError(scriptEntry, "Command option choices must specify a name!");
                                                scriptEntry.setFinished(true);
                                                return;
                                            } else if (choiceValue == null) {
                                                Debug.echoError(scriptEntry, "Command option choices must specify a value!");
                                                scriptEntry.setFinished(true);
                                                return;
                                            }
                                            if (optionType == OptionType.STRING) {
                                                optionData.addChoice(choiceName.asString(), choiceValue.asString());
                                            } else {
                                                optionData.addChoice(choiceName.asString(), choiceValue.asInt());
                                            }
                                        }
                                    }
                                    data.addOptions(optionData);
                                }
                            }
                        }
                        CommandCreateAction action;
                        if (group == null) {
                            Debug.log("Registering a slash command globally may take up to an hour.");
                            action = (CommandCreateAction) client.upsertCommand(data);
                        } else {
                            action = (CommandCreateAction) group.getGuild().upsertCommand(data);
                        }
                        action.setDefaultEnabled(isEnabled);
                        Command slashCommand = action.complete();
                        scriptEntry.addObject("command", new DiscordCommandTag(bot.bot, group == null ? null : group.getGuild(), slashCommand));
                        break;
                    }
                case PERMS:
                    {
                        if (enableFor == null && disableFor == null) {
                            Debug.echoError(scriptEntry, "Must specify privileges!");
                            scriptEntry.setFinished(true);
                            return;
                        } else if (group == null) {
                            Debug.echoError(scriptEntry, "Must specify a group!");
                            scriptEntry.setFinished(true);
                            return;
                        }
                        Command bestMatch = matchCommandByName(scriptEntry, name, client, group);
                        if (bestMatch == null) {
                            return;
                        }
                        List<CommandPrivilege> privileges = new ArrayList<>();
                        if (enableFor != null) {
                            addPrivileges(scriptEntry, true, enableFor, privileges);
                        }
                        if (disableFor != null) {
                            addPrivileges(scriptEntry, false, disableFor, privileges);
                        }
                        bestMatch.editCommand().setDefaultEnabled(isEnabled).complete();
                        group.guild.updateCommandPrivilegesById(bestMatch.getIdLong(), privileges).complete();
                        break;
                    }
                case DELETE:
                    {
                        Command bestMatch = matchCommandByName(scriptEntry, name, client, group);
                        if (bestMatch == null) {
                            return;
                        }
                        if (group == null) {
                            client.deleteCommandById(bestMatch.getIdLong()).complete();
                        } else {
                            group.getGuild().deleteCommandById(bestMatch.getIdLong()).complete();
                        }
                        break;
                    }
            }
        } catch (Exception e) {
            Debug.echoError(e);
        }
        scriptEntry.setFinished(true);
    });
}
Also used : JDA(net.dv8tion.jda.api.JDA) CommandCreateAction(net.dv8tion.jda.api.requests.restaction.CommandCreateAction) ListTag(com.denizenscript.denizencore.objects.core.ListTag) MapTag(com.denizenscript.denizencore.objects.core.MapTag) InvalidArgumentsException(com.denizenscript.denizencore.exceptions.InvalidArgumentsException) ScriptEntry(com.denizenscript.denizencore.scripts.ScriptEntry) ObjectTag(com.denizenscript.denizencore.objects.ObjectTag) Command(net.dv8tion.jda.api.interactions.commands.Command) ArrayList(java.util.ArrayList) List(java.util.List) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) OptionType(net.dv8tion.jda.api.interactions.commands.OptionType)

Aggregations

OptionType (net.dv8tion.jda.api.interactions.commands.OptionType)4 Command (net.dv8tion.jda.api.interactions.commands.Command)3 Nonnull (javax.annotation.Nonnull)2 DataArray (net.dv8tion.jda.api.utils.data.DataArray)2 InvalidArgumentsException (com.denizenscript.denizencore.exceptions.InvalidArgumentsException)1 ObjectTag (com.denizenscript.denizencore.objects.ObjectTag)1 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)1 ListTag (com.denizenscript.denizencore.objects.core.ListTag)1 MapTag (com.denizenscript.denizencore.objects.core.MapTag)1 ScriptEntry (com.denizenscript.denizencore.scripts.ScriptEntry)1 java.util (java.util)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 Nullable (javax.annotation.Nullable)1 lombok.val (lombok.val)1 JDA (net.dv8tion.jda.api.JDA)1 ChannelType (net.dv8tion.jda.api.entities.ChannelType)1 CommandAutoCompleteInteractionEvent (net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent)1 OptionData (net.dv8tion.jda.api.interactions.commands.build.OptionData)1