Search in sources :

Example 16 with Command

use of net.dv8tion.jda.api.interactions.commands.Command in project Bean by Xirado.

the class InteractionCommandHandler method handleUserContextCommand.

public void handleUserContextCommand(@NotNull UserContextInteractionEvent event) {
    if (!event.isFromGuild())
        return;
    Guild guild = event.getGuild();
    Member member = event.getMember();
    UserContextCommand command = null;
    if (registeredGuildCommands.containsKey(guild.getIdLong())) {
        List<UserContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof UserContextCommand).map(cmd -> (UserContextCommand) cmd).toList();
        UserContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (guildCommand != null)
            command = guildCommand;
    }
    if (command == null) {
        UserContextCommand globalCommand = getRegisteredUserContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (globalCommand != null)
            command = globalCommand;
    }
    if (command == null)
        return;
    List<Permission> neededPermissions = command.getRequiredUserPermissions();
    List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
    if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
        event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
        return;
    }
    if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
        event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
        return;
    }
    if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
        GuildVoiceState guildVoiceState = member.getVoiceState();
        if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
            event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
            return;
        }
    }
    if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
        GuildVoiceState voiceState = member.getVoiceState();
        AudioManager manager = event.getGuild().getAudioManager();
        if (manager.isConnected()) {
            if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
                event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
                return;
            }
        }
    }
    UserContextCommand finalCommand = command;
    Runnable r = () -> {
        try {
            finalCommand.executeCommand(event);
            Metrics.COMMANDS.labels("success").inc();
        } catch (Exception e) {
            Metrics.COMMANDS.labels("failed").inc();
            LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
            if (event.isAcknowledged())
                event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            else
                event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            LOGGER.error("Could not execute user-context-menu-command", e);
            EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a user-context-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", event.getName(), false).setColor(EmbedUtil.ERROR_COLOR);
            event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
        }
    };
    Bean.getInstance().getCommandExecutor().submit(r);
}
Also used : LocaleLoader(at.xirado.bean.translation.LocaleLoader) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) Permission(net.dv8tion.jda.api.Permission) AudioManager(net.dv8tion.jda.api.managers.AudioManager) LoggerFactory(org.slf4j.LoggerFactory) Util(at.xirado.bean.misc.Util) Member(net.dv8tion.jda.api.entities.Member) Command(net.dv8tion.jda.api.interactions.commands.Command) ArrayList(java.util.ArrayList) at.xirado.bean.command.slashcommands.moderation(at.xirado.bean.command.slashcommands.moderation) UserContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent) Guild(net.dv8tion.jda.api.entities.Guild) at.xirado.bean.command.slashcommands.music(at.xirado.bean.command.slashcommands.music) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) Map(java.util.Map) GenericCommand(at.xirado.bean.command.GenericCommand) SlashCommand(at.xirado.bean.command.SlashCommand) EmbedUtil(at.xirado.bean.misc.EmbedUtil) UserContextCommand(at.xirado.bean.command.context.UserContextCommand) MockContextMenuCommand(at.xirado.bean.command.context.message.MockContextMenuCommand) Logger(org.slf4j.Logger) at.xirado.bean.command.slashcommands(at.xirado.bean.command.slashcommands) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Metrics(at.xirado.bean.misc.Metrics) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) MessageContextCommand(at.xirado.bean.command.context.MessageContextCommand) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) CommandFlag(at.xirado.bean.command.CommandFlag) at.xirado.bean.command.slashcommands.leveling(at.xirado.bean.command.slashcommands.leveling) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Bean(at.xirado.bean.Bean) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) SlapContextMenuCommand(at.xirado.bean.command.context.user.SlapContextMenuCommand) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) UserContextCommand(at.xirado.bean.command.context.UserContextCommand) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) Guild(net.dv8tion.jda.api.entities.Guild) AudioManager(net.dv8tion.jda.api.managers.AudioManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member)

Example 17 with Command

use of net.dv8tion.jda.api.interactions.commands.Command in project Bean by Xirado.

the class InteractionCommandHandler method handleMessageContextCommand.

public void handleMessageContextCommand(@NotNull MessageContextInteractionEvent event) {
    if (!event.isFromGuild())
        return;
    Guild guild = event.getGuild();
    Member member = event.getMember();
    MessageContextCommand command = null;
    if (registeredGuildCommands.containsKey(guild.getIdLong())) {
        List<MessageContextCommand> guildCommands = registeredGuildCommands.get(guild.getIdLong()).stream().filter(cmd -> cmd instanceof MessageContextCommand).map(cmd -> (MessageContextCommand) cmd).toList();
        MessageContextCommand guildCommand = guildCommands.stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (guildCommand != null)
            command = guildCommand;
    }
    if (command == null) {
        MessageContextCommand globalCommand = getRegisteredMessageContextCommands().stream().filter(cmd -> cmd.getData().getName().equalsIgnoreCase(event.getName())).findFirst().orElse(null);
        if (globalCommand != null)
            command = globalCommand;
    }
    if (command == null)
        return;
    List<Permission> neededPermissions = command.getRequiredUserPermissions();
    List<Permission> neededBotPermissions = command.getRequiredBotPermissions();
    if (neededPermissions != null && !member.hasPermission((GuildChannel) event.getChannel(), neededPermissions)) {
        event.reply(LocaleLoader.ofGuild(guild).get("general.no_perms", String.class)).queue();
        return;
    }
    if (neededBotPermissions != null && !event.getGuild().getSelfMember().hasPermission((GuildChannel) event.getChannel(), neededBotPermissions)) {
        event.reply(LocaleLoader.ofGuild(guild).get("general.no_bot_perms1", String.class)).queue();
        return;
    }
    if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_VC)) {
        GuildVoiceState guildVoiceState = member.getVoiceState();
        if (guildVoiceState == null || !guildVoiceState.inAudioChannel()) {
            event.replyEmbeds(EmbedUtil.errorEmbed("You are not connected to a voice-channel!")).queue();
            return;
        }
    }
    if (command.getCommandFlags().contains(CommandFlag.MUST_BE_IN_SAME_VC)) {
        GuildVoiceState voiceState = member.getVoiceState();
        AudioManager manager = event.getGuild().getAudioManager();
        if (manager.isConnected()) {
            if (!manager.getConnectedChannel().equals(voiceState.getChannel())) {
                event.replyEmbeds(EmbedUtil.errorEmbed("You must be listening in " + manager.getConnectedChannel().getAsMention() + "to do this!")).setEphemeral(true).queue();
                return;
            }
        }
    }
    MessageContextCommand finalCommand = command;
    Runnable r = () -> {
        try {
            finalCommand.executeCommand(event);
            Metrics.COMMANDS.labels("success").inc();
        } catch (Exception e) {
            Metrics.COMMANDS.labels("failed").inc();
            LinkedDataObject translation = event.getGuild() == null ? LocaleLoader.getForLanguage("en_US") : LocaleLoader.ofGuild(event.getGuild());
            if (event.isAcknowledged())
                event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            else
                event.replyEmbeds(EmbedUtil.errorEmbed(translation.getString("general.unknown_error_occured"))).setEphemeral(true).queue(s -> {
                }, ex -> {
                });
            LOGGER.error("Could not execute message-context-menu-command", e);
            EmbedBuilder builder = new EmbedBuilder().setTitle("An error occurred while executing a message-context-command!").addField("Guild", event.getGuild() == null ? "None (Direct message)" : event.getGuild().getIdLong() + " (" + event.getGuild().getName() + ")", true).addField("Channel", event.getGuild() == null ? "None (Direct message)" : event.getChannel().getName(), true).addField("User", event.getUser().getAsMention() + " (" + event.getUser().getAsTag() + ")", true).addField("Command", event.getName(), false).setColor(EmbedUtil.ERROR_COLOR);
            event.getJDA().openPrivateChannelById(Bean.OWNER_ID).flatMap(c -> c.sendMessageEmbeds(builder.build()).content("```fix\n" + ExceptionUtils.getStackTrace(e) + "\n```")).queue();
        }
    };
    Bean.getInstance().getCommandExecutor().submit(r);
}
Also used : LocaleLoader(at.xirado.bean.translation.LocaleLoader) MessageContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent) Permission(net.dv8tion.jda.api.Permission) AudioManager(net.dv8tion.jda.api.managers.AudioManager) LoggerFactory(org.slf4j.LoggerFactory) Util(at.xirado.bean.misc.Util) Member(net.dv8tion.jda.api.entities.Member) Command(net.dv8tion.jda.api.interactions.commands.Command) ArrayList(java.util.ArrayList) at.xirado.bean.command.slashcommands.moderation(at.xirado.bean.command.slashcommands.moderation) UserContextInteractionEvent(net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent) Guild(net.dv8tion.jda.api.entities.Guild) at.xirado.bean.command.slashcommands.music(at.xirado.bean.command.slashcommands.music) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) Map(java.util.Map) GenericCommand(at.xirado.bean.command.GenericCommand) SlashCommand(at.xirado.bean.command.SlashCommand) EmbedUtil(at.xirado.bean.misc.EmbedUtil) UserContextCommand(at.xirado.bean.command.context.UserContextCommand) MockContextMenuCommand(at.xirado.bean.command.context.message.MockContextMenuCommand) Logger(org.slf4j.Logger) at.xirado.bean.command.slashcommands(at.xirado.bean.command.slashcommands) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Metrics(at.xirado.bean.misc.Metrics) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) MessageContextCommand(at.xirado.bean.command.context.MessageContextCommand) CommandAutoCompleteInteractionEvent(net.dv8tion.jda.api.events.interaction.command.CommandAutoCompleteInteractionEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Consumer(java.util.function.Consumer) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) CommandFlag(at.xirado.bean.command.CommandFlag) at.xirado.bean.command.slashcommands.leveling(at.xirado.bean.command.slashcommands.leveling) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) Bean(at.xirado.bean.Bean) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) SlapContextMenuCommand(at.xirado.bean.command.context.user.SlapContextMenuCommand) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) LinkedDataObject(at.xirado.bean.data.LinkedDataObject) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) Guild(net.dv8tion.jda.api.entities.Guild) MessageContextCommand(at.xirado.bean.command.context.MessageContextCommand) AudioManager(net.dv8tion.jda.api.managers.AudioManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member)

Example 18 with Command

use of net.dv8tion.jda.api.interactions.commands.Command 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)

Example 19 with Command

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

the class DiscordBotTag method registerTags.

public static void registerTags() {
    AbstractFlagTracker.registerFlagHandlers(tagProcessor);
    // <--[tag]
    // @attribute <DiscordBotTag.name>
    // @returns ElementTag
    // @plugin dDiscordBot
    // @description
    // Returns the name of the bot.
    // -->
    tagProcessor.registerTag(ElementTag.class, "name", (attribute, object) -> {
        return new ElementTag(object.bot);
    });
    // <--[tag]
    // @attribute <DiscordBotTag.self_user>
    // @returns DiscordUserTag
    // @plugin dDiscordBot
    // @description
    // Returns the bot's own Discord user object.
    // -->
    tagProcessor.registerTag(DiscordUserTag.class, "self_user", (attribute, object) -> {
        DiscordConnection connection = object.getConnection();
        if (connection == null) {
            return null;
        }
        return new DiscordUserTag(object.bot, connection.client.getSelfUser());
    });
    // <--[tag]
    // @attribute <DiscordBotTag.groups>
    // @returns ListTag(DiscordGroupTag)
    // @plugin dDiscordBot
    // @description
    // Returns a list of all groups (aka 'guilds' or 'servers') that this Discord bot has access to.
    // -->
    tagProcessor.registerTag(ListTag.class, "groups", (attribute, object) -> {
        DiscordConnection connection = object.getConnection();
        if (connection == null) {
            return null;
        }
        ListTag list = new ListTag();
        for (Guild guild : connection.client.getGuilds()) {
            list.addObject(new DiscordGroupTag(object.bot, guild));
        }
        return list;
    });
    // <--[tag]
    // @attribute <DiscordBotTag.commands>
    // @returns ListTag(DiscordCommandTag)
    // @plugin dDiscordBot
    // @description
    // Returns a list of all application commands.
    // -->
    tagProcessor.registerTag(ListTag.class, "commands", (attribute, object) -> {
        DiscordConnection connection = object.getConnection();
        if (connection == null) {
            return null;
        }
        ListTag list = new ListTag();
        for (Command command : connection.client.retrieveCommands().complete()) {
            list.addObject(new DiscordCommandTag(object.bot, null, command));
        }
        return list;
    });
    // <--[tag]
    // @attribute <DiscordBotTag.group[<name>]>
    // @returns DiscordGroupTag
    // @plugin dDiscordBot
    // @description
    // Returns the Discord group (aka 'guild' or 'server') that best matches the input name, or null if there's no match.
    // -->
    tagProcessor.registerTag(DiscordGroupTag.class, "group", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        DiscordConnection connection = object.getConnection();
        if (connection == null) {
            return null;
        }
        String matchString = CoreUtilities.toLowerCase(attribute.getParam());
        Guild bestMatch = null;
        for (Guild guild : connection.client.getGuilds()) {
            String guildName = CoreUtilities.toLowerCase(guild.getName());
            if (matchString.equals(guildName)) {
                bestMatch = guild;
                break;
            }
            if (guildName.contains(matchString)) {
                bestMatch = guild;
            }
        }
        if (bestMatch == null) {
            return null;
        }
        return new DiscordGroupTag(object.bot, bestMatch);
    });
    // <--[tag]
    // @attribute <DiscordBotTag.command[<name>]>
    // @returns DiscordCommandTag
    // @plugin dDiscordBot
    // @description
    // Returns the application command that best matches the input name, or null if there's no match.
    // -->
    tagProcessor.registerTag(DiscordCommandTag.class, "command", (attribute, object) -> {
        if (!attribute.hasParam()) {
            return null;
        }
        DiscordConnection connection = object.getConnection();
        if (connection == null) {
            return null;
        }
        String matchString = CoreUtilities.toLowerCase(attribute.getParam());
        Command bestMatch = null;
        for (Command command : connection.client.retrieveCommands().complete()) {
            String commandName = CoreUtilities.toLowerCase(command.getName());
            if (matchString.equals(commandName)) {
                bestMatch = command;
                break;
            }
            if (commandName.contains(matchString)) {
                bestMatch = command;
            }
        }
        if (bestMatch == null) {
            return null;
        }
        return new DiscordCommandTag(object.bot, null, bestMatch);
    });
}
Also used : Command(net.dv8tion.jda.api.interactions.commands.Command) DiscordConnection(com.denizenscript.ddiscordbot.DiscordConnection) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) Guild(net.dv8tion.jda.api.entities.Guild) ListTag(com.denizenscript.denizencore.objects.core.ListTag)

Example 20 with Command

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

the class DiscordCommandTag method registerTags.

public static void registerTags() {
    AbstractFlagTracker.registerFlagHandlers(tagProcessor);
    // <--[tag]
    // @attribute <DiscordCommandTag.id>
    // @returns ElementTag(Number)
    // @plugin dDiscordBot
    // @description
    // Returns the ID of the command.
    // -->
    tagProcessor.registerTag(ElementTag.class, "id", (attribute, object) -> {
        return new ElementTag(object.command_id);
    });
    // <--[tag]
    // @attribute <DiscordCommandTag.name>
    // @returns ElementTag
    // @plugin dDiscordBot
    // @description
    // Returns the name of the command.
    // -->
    tagProcessor.registerTag(ElementTag.class, "name", (attribute, object) -> {
        return new ElementTag(object.getCommand().getName());
    });
    // <--[tag]
    // @attribute <DiscordCommandTag.description>
    // @returns ElementTag
    // @plugin dDiscordBot
    // @description
    // Returns the description of the command.
    // -->
    tagProcessor.registerTag(ElementTag.class, "description", (attribute, object) -> {
        return new ElementTag(object.getCommand().getDescription());
    });
    // <--[tag]
    // @attribute <DiscordCommandTag.options>
    // @returns ListTag(MapTag)
    // @plugin dDiscordBot
    // @description
    // Returns the option MapTags of the command. This is the same value as the one provided when creating a command, as documented in <@link command DiscordCommand>.
    // -->
    tagProcessor.registerTag(ListTag.class, "options", (attribute, object) -> {
        ListTag options = new ListTag();
        for (Command.Option option : object.getCommand().getOptions()) {
            MapTag map = new MapTag();
            map.putObject("type", new ElementTag(option.getType().toString().toLowerCase().replaceAll("_", "")));
            map.putObject("name", new ElementTag(option.getName()));
            map.putObject("description", new ElementTag(option.getDescription()));
            map.putObject("required", new ElementTag(option.isRequired()));
            if (option.getType() == OptionType.STRING || option.getType() == OptionType.INTEGER) {
                ListTag choices = new ListTag();
                for (Command.Choice choice : option.getChoices()) {
                    MapTag choiceData = new MapTag();
                    choiceData.putObject("name", new ElementTag(choice.getName()));
                    if (option.getType() == OptionType.STRING) {
                        choiceData.putObject("value", new ElementTag(choice.getAsString()));
                    } else {
                        choiceData.putObject("value", new ElementTag(choice.getAsLong()));
                    }
                    choices.addObject(choiceData);
                }
                map.putObject("choices", choices);
            }
            options.addObject(map);
        }
        return options;
    });
}
Also used : Command(net.dv8tion.jda.api.interactions.commands.Command) ElementTag(com.denizenscript.denizencore.objects.core.ElementTag) ListTag(com.denizenscript.denizencore.objects.core.ListTag) MapTag(com.denizenscript.denizencore.objects.core.MapTag)

Aggregations

Command (net.dv8tion.jda.api.interactions.commands.Command)22 ArrayList (java.util.ArrayList)8 Guild (net.dv8tion.jda.api.entities.Guild)7 List (java.util.List)6 CommandListUpdateAction (net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction)6 IOException (java.io.IOException)4 Collectors (java.util.stream.Collectors)4 JDA (net.dv8tion.jda.api.JDA)4 MessageContextInteractionEvent (net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent)4 NotNull (org.jetbrains.annotations.NotNull)4 Nullable (org.jetbrains.annotations.Nullable)4 Bean (at.xirado.bean.Bean)3 CommandFlag (at.xirado.bean.command.CommandFlag)3 GenericCommand (at.xirado.bean.command.GenericCommand)3 SlashCommand (at.xirado.bean.command.SlashCommand)3 SlashCommandContext (at.xirado.bean.command.SlashCommandContext)3 ElementTag (com.denizenscript.denizencore.objects.core.ElementTag)3 ListTag (com.denizenscript.denizencore.objects.core.ListTag)3 java.util (java.util)3 Member (net.dv8tion.jda.api.entities.Member)3