Search in sources :

Example 1 with Components

use of com.freya02.botcommands.api.components.Components in project BotCommands by freya022.

the class ApplicationCommandsUpdater method computeSlashCommands.

private void computeSlashCommands(List<ApplicationCommandInfo> guildApplicationCommands) {
    guildApplicationCommands.stream().filter(a -> a instanceof SlashCommandInfo).map(a -> (SlashCommandInfo) a).distinct().forEachOrdered(info -> {
        final CommandPath notLocalizedPath = info.getPath();
        try {
            final LocalizedCommandData localizedCommandData = LocalizedCommandData.of(context, guild, info);
            // Put localized option names in order to resolve them when called
            final List<OptionData> localizedMethodOptions = getLocalizedMethodOptions(info, localizedCommandData);
            if (guild != null) {
                info.putLocalizedOptions(guild.getIdLong(), localizedMethodOptions.stream().map(OptionData::getName).collect(Collectors.toList()));
            }
            localizedBaseNameToBaseName.put(localizedCommandData.getLocalizedPath().getName(), notLocalizedPath.getName());
            final CommandPath localizedPath = localizedCommandData.getLocalizedPath();
            final String description = localizedCommandData.getLocalizedDescription();
            Checks.check(localizedPath.getNameCount() == notLocalizedPath.getNameCount(), "Localized path does not have the same name count as the not-localized path");
            final boolean isDefaultEnabled = isDefaultEnabled(info);
            if (localizedPath.getNameCount() == 1) {
                // Standard command
                final SlashCommandData rightCommand = Commands.slash(localizedPath.getName(), description);
                map.put(Command.Type.SLASH, localizedPath, rightCommand);
                rightCommand.addOptions(localizedMethodOptions);
                rightCommand.setDefaultEnabled(isDefaultEnabled);
            } else if (localizedPath.getNameCount() == 2) {
                Checks.notNull(localizedPath.getSubname(), "Subcommand name");
                final SlashCommandData commandData = (SlashCommandData) map.computeIfAbsent(Command.Type.SLASH, localizedPath, x -> {
                    final SlashCommandData tmpData = Commands.slash(localizedPath.getName(), "No description (base name)");
                    tmpData.setDefaultEnabled(isDefaultEnabled);
                    return tmpData;
                });
                // Subcommand of a command
                final SubcommandData subcommandData = new SubcommandData(localizedPath.getSubname(), description);
                subcommandData.addOptions(localizedMethodOptions);
                commandData.addSubcommands(subcommandData);
            } else if (localizedPath.getNameCount() == 3) {
                Checks.notNull(localizedPath.getGroup(), "Command group name");
                Checks.notNull(localizedPath.getSubname(), "Subcommand name");
                final SubcommandGroupData groupData = getSubcommandGroup(Command.Type.SLASH, localizedPath, x -> {
                    final SlashCommandData commandData = Commands.slash(localizedPath.getName(), "No description (base name)");
                    commandData.setDefaultEnabled(isDefaultEnabled);
                    return commandData;
                });
                final SubcommandData subcommandData = new SubcommandData(localizedPath.getSubname(), description);
                subcommandData.addOptions(localizedMethodOptions);
                groupData.addSubcommands(subcommandData);
            } else {
                throw new IllegalStateException("A slash command with more than 4 path components got registered");
            }
            context.addApplicationCommandAlternative(localizedPath, Command.Type.SLASH, info);
            if (!info.isOwnerRequired()) {
                if (ownerOnlyCommands.contains(notLocalizedPath.getName())) {
                    LOGGER.warn("Non owner-only command '{}' is registered as a owner-only command because of another command with the same base name '{}'", notLocalizedPath, notLocalizedPath.getName());
                }
            }
            if (info.isOwnerRequired()) {
                if (info.isGuildOnly()) {
                    ownerOnlyCommands.add(notLocalizedPath.getName());
                } else {
                    LOGGER.warn("Owner-only command '{}' cannot be owner-only as it is a global command", notLocalizedPath);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("An exception occurred while processing command '" + notLocalizedPath + "' at " + Utils.formatMethodShort(info.getMethod()), e);
        }
    });
}
Also used : java.util(java.util) Logging(com.freya02.botcommands.api.Logging) UserCommandInfo(com.freya02.botcommands.internal.application.context.user.UserCommandInfo) Command(net.dv8tion.jda.api.interactions.commands.Command) Function(java.util.function.Function) DebugBuilder(com.freya02.botcommands.api.builder.DebugBuilder) Guild(net.dv8tion.jda.api.entities.Guild) CommandPath(com.freya02.botcommands.api.application.CommandPath) CommandPrivilege(net.dv8tion.jda.api.interactions.commands.privileges.CommandPrivilege) Blocking(org.jetbrains.annotations.Blocking) Path(java.nio.file.Path) SettingsProvider(com.freya02.botcommands.api.SettingsProvider) SlashUtils.getLocalizedMethodOptions(com.freya02.botcommands.internal.application.slash.SlashUtils.getLocalizedMethodOptions) Checks(net.dv8tion.jda.internal.utils.Checks) Logger(org.slf4j.Logger) BContextImpl(com.freya02.botcommands.internal.BContextImpl) Utils(com.freya02.botcommands.internal.utils.Utils) MessageCommandInfo(com.freya02.botcommands.internal.application.context.message.MessageCommandInfo) Files(java.nio.file.Files) StandardOpenOption(java.nio.file.StandardOpenOption) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) net.dv8tion.jda.api.interactions.commands.build(net.dv8tion.jda.api.interactions.commands.build) Nullable(org.jetbrains.annotations.Nullable) SlashUtils.appendCommands(com.freya02.botcommands.internal.application.slash.SlashUtils.appendCommands) SlashCommandInfo(com.freya02.botcommands.internal.application.slash.SlashCommandInfo) CommandListUpdateAction(net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction) NotNull(org.jetbrains.annotations.NotNull) SlashCommandInfo(com.freya02.botcommands.internal.application.slash.SlashCommandInfo) IOException(java.io.IOException) CommandPath(com.freya02.botcommands.api.application.CommandPath)

Example 2 with Components

use of com.freya02.botcommands.api.components.Components in project BotCommands by freya022.

the class PaginatorCommand method run.

@JDASlashCommand(name = "paginator")
public void run(GuildSlashEvent event) {
    final List<EmbedBuilder> embedBuilders = new ArrayList<>();
    // Let's suppose you generated embeds like in JDA-U, so you'd have a collection of embeds to present
    for (int i = 0; i < 5; i++) {
        embedBuilders.add(new EmbedBuilder().setTitle("Page #" + (i + 1)));
    }
    final Paginator paginator = new PaginatorBuilder().setConstraints(InteractionConstraints.ofUsers(event.getUser())).useDeleteButton(false).setMaxPages(5).setPaginatorSupplier((instance, messageBuilder, components, page) -> embedBuilders.get(page).build()).build();
    // You must send the paginator as a message
    event.reply(paginator.get()).setEphemeral(true).queue();
}
Also used : List(java.util.List) ApplicationCommand(com.freya02.botcommands.api.application.ApplicationCommand) InteractionConstraints(com.freya02.botcommands.api.components.InteractionConstraints) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Paginator(com.freya02.botcommands.api.pagination.paginator.Paginator) CommandMarker(com.freya02.botcommands.api.annotations.CommandMarker) GuildSlashEvent(com.freya02.botcommands.api.application.slash.GuildSlashEvent) PaginatorBuilder(com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder) ArrayList(java.util.ArrayList) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ArrayList(java.util.ArrayList) Paginator(com.freya02.botcommands.api.pagination.paginator.Paginator) PaginatorBuilder(com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand)

Example 3 with Components

use of com.freya02.botcommands.api.components.Components in project BotCommands by freya022.

the class ComponentsBotMain method main.

public static void main(String[] args) {
    try {
        final CommonMain.CommonStuff commonStuff = CommonMain.start();
        final JDA jda = commonStuff.getJDA();
        // Instantiate the database needed for components
        final ComponentsDB componentsDB = new ComponentsDB(commonStuff.getConfig());
        // Build the command framework:
        // Prefix: !
        // Owner: User with the ID 222046562543468545
        // Commands package: com.freya02.bot.componentsbot.commands
        CommandsBuilder.newBuilder(222046562543468545L).textCommandBuilder(textCommandsBuilder -> textCommandsBuilder.addPrefix("!")).setComponentManager(new DefaultComponentManager(componentsDB::getConnection)).build(jda, // Registering listeners is taken care of by the lib
        "com.freya02.bot.componentsbot.commands");
    } catch (Exception e) {
        LOGGER.error("Unable to start the bot", e);
        System.exit(-1);
    }
}
Also used : JDA(net.dv8tion.jda.api.JDA) CommonMain(com.freya02.bot.CommonMain) ComponentsDB(com.freya02.bot.ComponentsDB) DefaultComponentManager(com.freya02.botcommands.api.components.DefaultComponentManager)

Example 4 with Components

use of com.freya02.botcommands.api.components.Components in project BotCommands by freya022.

the class Main method main.

public static void main(String[] args) {
    try {
        // Make sure that the file Config.json exists under src/main/java/resources/com/freya02/bot/Config.json and has a valid token inside
        final Config config = Config.readConfig();
        // Set up JDA
        final JDA jda = JDABuilder.createLight(config.getToken()).setActivity(Activity.playing("Prefix is " + config.getPrefix())).build().awaitReady();
        // Print some information about the bot
        LOGGER.info("Bot connected as {}", jda.getSelfUser().getAsTag());
        LOGGER.info("The bot is present on these guilds :");
        for (Guild guild : jda.getGuildCache()) {
            LOGGER.info("\t- {} ({})", guild.getName(), guild.getId());
        }
        // Instantiate the database needed for components
        final ComponentsDB componentsDB = new ComponentsDB(config);
        // Build the command framework:
        // Prefix: configured in Config.json
        // Owner: configured in Config.json
        // Commands package: com.freya02.bot.commands
        CommandsBuilder.newBuilder(config.getOwnerId()).textCommandBuilder(textCommandsBuilder -> textCommandsBuilder.addPrefix(config.getPrefix())).setComponentManager(new DefaultComponentManager(componentsDB::getConnection)).build(jda, // Registering listeners is taken care of by the lib
        "com.freya02.bot.commands");
    } catch (IOException | InterruptedException | LoginException | SQLException e) {
        LOGGER.error("Unable to start the bot", e);
        System.exit(-1);
    }
}
Also used : SQLException(java.sql.SQLException) JDA(net.dv8tion.jda.api.JDA) LoginException(javax.security.auth.login.LoginException) IOException(java.io.IOException) Guild(net.dv8tion.jda.api.entities.Guild) DefaultComponentManager(com.freya02.botcommands.api.components.DefaultComponentManager)

Example 5 with Components

use of com.freya02.botcommands.api.components.Components in project BotCommands by freya022.

the class ApplicationCommandsUpdater method getSubcommandGroup.

// I am aware that the type is always Command.Type#SLASH, still use a parameter to mimic how ApplicationCommandMap functions and for future proof uses
@SuppressWarnings("SameParameterValue")
@NotNull
private SubcommandGroupData getSubcommandGroup(Command.Type type, CommandPath path, Function<String, CommandData> baseCommandSupplier) {
    if (path.getGroup() == null)
        throw new IllegalArgumentException("Group component of command path is null at '" + path + "'");
    final SlashCommandData data = (SlashCommandData) map.computeIfAbsent(type, path, baseCommandSupplier);
    final CommandPath parent = path.getParent();
    if (parent == null)
        throw new IllegalStateException("A command path with less than 3 components was passed to #getSubcommandGroup");
    return subcommandGroupDataMap.computeIfAbsent(parent.getFullPath(), s -> {
        final SubcommandGroupData groupData = new SubcommandGroupData(path.getGroup(), "No description (group)");
        data.addSubcommandGroups(groupData);
        return groupData;
    });
}
Also used : CommandPath(com.freya02.botcommands.api.application.CommandPath) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

ApplicationCommand (com.freya02.botcommands.api.application.ApplicationCommand)3 GuildSlashEvent (com.freya02.botcommands.api.application.slash.GuildSlashEvent)3 JDASlashCommand (com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand)3 InteractionConstraints (com.freya02.botcommands.api.components.InteractionConstraints)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 JDA (net.dv8tion.jda.api.JDA)3 CommonMain (com.freya02.bot.CommonMain)2 Logging (com.freya02.botcommands.api.Logging)2 CommandPath (com.freya02.botcommands.api.application.CommandPath)2 Components (com.freya02.botcommands.api.components.Components)2 DefaultComponentManager (com.freya02.botcommands.api.components.DefaultComponentManager)2 Paginator (com.freya02.botcommands.api.pagination.paginator.Paginator)2 PaginatorBuilder (com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder)2 IOException (java.io.IOException)2 TimeUnit (java.util.concurrent.TimeUnit)2 Guild (net.dv8tion.jda.api.entities.Guild)2 NotNull (org.jetbrains.annotations.NotNull)2 ComponentsDB (com.freya02.bot.ComponentsDB)1 BContext (com.freya02.botcommands.api.BContext)1 CommandsBuilder (com.freya02.botcommands.api.CommandsBuilder)1