Search in sources :

Example 1 with GuildSlashEvent

use of com.freya02.botcommands.api.application.slash.GuildSlashEvent in project BotCommands by freya022.

the class SlashCommandInfo method execute.

public boolean execute(BContext context, SlashCommandInteractionEvent event, Consumer<Throwable> throwableConsumer) throws Exception {
    List<Object> objects = new ArrayList<>(commandParameters.size() + 1) {

        {
            if (guildOnly) {
                add(new GuildSlashEvent(context, event));
            } else {
                add(new GlobalSlashEventImpl(context, event));
            }
        }
    };
    int optionIndex = 0;
    final List<String> optionNames = event.getGuild() != null ? getLocalizedOptions(event.getGuild()) : null;
    for (final SlashCommandParameter parameter : commandParameters) {
        final ApplicationOptionData applicationOptionData = parameter.getApplicationOptionData();
        final Object obj;
        if (parameter.isOption()) {
            String optionName = optionNames == null ? applicationOptionData.getEffectiveName() : optionNames.get(optionIndex);
            if (optionName == null) {
                throw new IllegalArgumentException(String.format("Option name #%d (%s) could not be resolved for %s", optionIndex, applicationOptionData.getEffectiveName(), Utils.formatMethodShort(getMethod())));
            }
            optionIndex++;
            final OptionMapping optionMapping = event.getOption(optionName);
            if (optionMapping == null) {
                if (parameter.isOptional()) {
                    if (parameter.isPrimitive()) {
                        objects.add(0);
                    } else {
                        objects.add(null);
                    }
                    continue;
                } else {
                    throw new RuntimeException("Slash parameter couldn't be resolved for method " + Utils.formatMethodShort(commandMethod) + " at parameter " + applicationOptionData.getEffectiveName() + " (localized '" + optionName + "')");
                }
            }
            obj = parameter.getResolver().resolve(context, this, event, optionMapping);
            if (obj == null) {
                event.replyFormat(context.getDefaultMessages(event.getGuild()).getSlashCommandUnresolvableParameterMsg(), applicationOptionData.getEffectiveName(), parameter.getBoxedType().getSimpleName()).setEphemeral(true).queue();
                // Not a warning, could be normal if the user did not supply a valid string for user-defined resolvers
                LOGGER.trace("The parameter '{}' of value '{}' could not be resolved into a {}", applicationOptionData.getEffectiveName(), optionMapping.getAsString(), parameter.getBoxedType().getSimpleName());
                return false;
            }
            if (!parameter.getBoxedType().isAssignableFrom(obj.getClass())) {
                event.replyFormat(context.getDefaultMessages(event.getGuild()).getSlashCommandInvalidParameterTypeMsg(), applicationOptionData.getEffectiveName(), parameter.getBoxedType().getSimpleName(), obj.getClass().getSimpleName()).setEphemeral(true).queue();
                LOGGER.error("The parameter '{}' of value '{}' is not a valid type (expected a {})", applicationOptionData.getEffectiveName(), optionMapping.getAsString(), parameter.getBoxedType().getSimpleName());
                return false;
            }
        } else {
            obj = parameter.getCustomResolver().resolve(context, this, event);
        }
        // For some reason using an array list instead of a regular array
        // magically unboxes primitives when passed to Method#invoke
        objects.add(obj);
    }
    applyCooldown(event);
    getMethodRunner().invoke(objects.toArray(), throwableConsumer);
    return true;
}
Also used : OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) ArrayList(java.util.ArrayList) ApplicationOptionData(com.freya02.botcommands.internal.ApplicationOptionData) GuildSlashEvent(com.freya02.botcommands.api.application.slash.GuildSlashEvent)

Example 2 with GuildSlashEvent

use of com.freya02.botcommands.api.application.slash.GuildSlashEvent 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 GuildSlashEvent

use of com.freya02.botcommands.api.application.slash.GuildSlashEvent in project BotCommands by freya022.

the class ApplicationCommandsBuilder method processSlashCommand.

private void processSlashCommand(ApplicationCommand applicationCommand, Method method) {
    if (method.getAnnotation(JDASlashCommand.class).guildOnly()) {
        if (!ReflectionUtils.hasFirstParameter(method, GlobalSlashEvent.class) && !ReflectionUtils.hasFirstParameter(method, GuildSlashEvent.class))
            throw new IllegalArgumentException("Slash command at " + Utils.formatMethodShort(method) + " must have a GuildSlashEvent or GlobalSlashEvent as first parameter");
        if (!ReflectionUtils.hasFirstParameter(method, GuildSlashEvent.class)) {
            // If type is correct but guild specialization isn't used
            LOGGER.warn("Guild-only slash command {} uses GlobalSlashEvent, consider using GuildSlashEvent to remove warnings related to guild stuff's nullability", Utils.formatMethodShort(method));
        }
    } else {
        if (!ReflectionUtils.hasFirstParameter(method, GlobalSlashEvent.class))
            throw new IllegalArgumentException("Slash command at " + Utils.formatMethodShort(method) + " must have a GlobalSlashEvent as first parameter");
    }
    final SlashCommandInfo info = new SlashCommandInfo(context, applicationCommand, method);
    LOGGER.debug("Adding slash command path {} for method {}", info.getPath(), Utils.formatMethodShort(method));
    context.addSlashCommand(info);
}
Also used : SlashCommandInfo(com.freya02.botcommands.internal.application.slash.SlashCommandInfo) GuildSlashEvent(com.freya02.botcommands.api.application.slash.GuildSlashEvent) GlobalSlashEvent(com.freya02.botcommands.api.application.slash.GlobalSlashEvent) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand)

Example 4 with GuildSlashEvent

use of com.freya02.botcommands.api.application.slash.GuildSlashEvent in project BotCommands by freya022.

the class SlashInteractiveMenu method interactiveMenu.

@JDASlashCommand(name = "interactive")
public void interactiveMenu(GuildSlashEvent event) {
    final InteractiveMenu menu = new InteractiveMenuBuilder().addMenu(SelectContent.of("Joy", "This sparks joy", Emoji.fromMarkdown("\uD83D\uDE02")), (interactiveMenu, messageBuilder, components) -> {
        components.addComponents(1, Components.dangerButton(buttonEvent -> {
            event.getHook().deleteOriginal().queue();
            interactiveMenu.cancelTimeout();
            interactiveMenu.cleanup(event.getContext());
        }).build("Delete"), Components.secondaryButton(buttonEvent -> {
            interactiveMenu.setSelectedItem("Grin");
            buttonEvent.editMessage(interactiveMenu.get()).queue();
        }).build("Go to 'Grin'"));
        return new EmbedBuilder().setTitle("This sparks joy").build();
    }).addMenu(SelectContent.of("Grin", "This does not spark joy", Emoji.fromMarkdown("\uD83D\uDE00")), (interactiveMenu, messageBuilder, components) -> {
        components.addComponents(1, Components.dangerButton(buttonEvent -> {
            event.getHook().deleteOriginal().queue();
            interactiveMenu.cancelTimeout();
            interactiveMenu.cleanup(event.getContext());
        }).build("Delete"), Components.secondaryButton(buttonEvent -> {
            interactiveMenu.setSelectedItem(0);
            buttonEvent.editMessage(interactiveMenu.get()).queue();
        }).build("Go to 'Joy'"));
        return new EmbedBuilder().setTitle("This does not spark joy").build();
    }).setConstraints(InteractionConstraints.ofUsers(event.getUser())).setTimeout(5, TimeUnit.SECONDS, (interactiveMenu, msg) -> {
        System.out.println("bru");
        interactiveMenu.cleanup(event.getContext());
    }).build();
    event.reply(menu.get()).setEphemeral(false).queue();
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) InteractiveMenuBuilder(com.freya02.botcommands.api.pagination.interactive.InteractiveMenuBuilder) ApplicationCommand(com.freya02.botcommands.api.application.ApplicationCommand) Components(com.freya02.botcommands.api.components.Components) InteractionConstraints(com.freya02.botcommands.api.components.InteractionConstraints) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InteractiveMenu(com.freya02.botcommands.api.pagination.interactive.InteractiveMenu) Emoji(net.dv8tion.jda.api.entities.Emoji) GuildSlashEvent(com.freya02.botcommands.api.application.slash.GuildSlashEvent) SelectContent(com.freya02.botcommands.api.pagination.interactive.SelectContent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InteractiveMenu(com.freya02.botcommands.api.pagination.interactive.InteractiveMenu) InteractiveMenuBuilder(com.freya02.botcommands.api.pagination.interactive.InteractiveMenuBuilder) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand)

Example 5 with GuildSlashEvent

use of com.freya02.botcommands.api.application.slash.GuildSlashEvent in project BotCommands by freya022.

the class SlashPaginator method replyPaginator.

private void replyPaginator(GuildSlashEvent event, BContext context, InteractionConstraints constraints) {
    final PaginatorBuilder builder = new PaginatorBuilder().setConstraints(constraints).useDeleteButton(true).setTimeout(5, TimeUnit.SECONDS, (paginator, message) -> {
        paginator.cleanup(context);
        // Remove components on timeout
        event.getHook().editOriginalComponents().queue();
    // Disable all components on timeout, more expensive
    // event.getHook()
    // .retrieveOriginal()
    // .flatMap(m -> m.editMessageComponents(m.getActionRows().stream().map(ActionRow::asDisabled).toList()))
    // .queue();
    }).setMaxPages(5).setFirstContent(ButtonContent.withString("←")).setPaginatorSupplier((paginator, messageBuilder, components, page) -> {
        components.addComponents(1, Components.primaryButton(btnEvt -> {
            // Pages starts at 0
            paginator.setPage(2);
            btnEvt.editMessage(paginator.get()).queue();
        }).build(ButtonContent.withEmoji("Go to page 3", EmojiUtils.resolveJDAEmoji("page_facing_up"))));
        components.addComponents(1, Components.primaryButton(btnEvt -> {
            // Pages starts at 0
            paginator.setPage(4);
            btnEvt.editMessage(paginator.get()).queue();
        }).build(ButtonContent.withEmoji("Go to page 5", EmojiUtils.resolveJDAEmoji("page_facing_up"))));
        return new EmbedBuilder().setTitle(// Pages starts at 0
        "Page #" + (page + 1)).build();
    });
    final Paginator paginator = builder.build();
    event.reply(paginator.get()).setEphemeral(false).queue();
}
Also used : Components(com.freya02.botcommands.api.components.Components) InteractionConstraints(com.freya02.botcommands.api.components.InteractionConstraints) ButtonContent(com.freya02.botcommands.api.utils.ButtonContent) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Paginator(com.freya02.botcommands.api.pagination.paginator.Paginator) TimeUnit(java.util.concurrent.TimeUnit) AppOption(com.freya02.botcommands.api.application.annotations.AppOption) Role(net.dv8tion.jda.api.entities.Role) ApplicationCommand(com.freya02.botcommands.api.application.ApplicationCommand) JDASlashCommand(com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand) GuildSlashEvent(com.freya02.botcommands.api.application.slash.GuildSlashEvent) BContext(com.freya02.botcommands.api.BContext) PaginatorBuilder(com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder) EmojiUtils(com.freya02.botcommands.api.utils.EmojiUtils) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Paginator(com.freya02.botcommands.api.pagination.paginator.Paginator) PaginatorBuilder(com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder)

Aggregations

GuildSlashEvent (com.freya02.botcommands.api.application.slash.GuildSlashEvent)5 JDASlashCommand (com.freya02.botcommands.api.application.slash.annotations.JDASlashCommand)4 ApplicationCommand (com.freya02.botcommands.api.application.ApplicationCommand)3 InteractionConstraints (com.freya02.botcommands.api.components.InteractionConstraints)3 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 Components (com.freya02.botcommands.api.components.Components)2 Paginator (com.freya02.botcommands.api.pagination.paginator.Paginator)2 PaginatorBuilder (com.freya02.botcommands.api.pagination.paginator.PaginatorBuilder)2 ArrayList (java.util.ArrayList)2 TimeUnit (java.util.concurrent.TimeUnit)2 BContext (com.freya02.botcommands.api.BContext)1 CommandMarker (com.freya02.botcommands.api.annotations.CommandMarker)1 AppOption (com.freya02.botcommands.api.application.annotations.AppOption)1 GlobalSlashEvent (com.freya02.botcommands.api.application.slash.GlobalSlashEvent)1 InteractiveMenu (com.freya02.botcommands.api.pagination.interactive.InteractiveMenu)1 InteractiveMenuBuilder (com.freya02.botcommands.api.pagination.interactive.InteractiveMenuBuilder)1 SelectContent (com.freya02.botcommands.api.pagination.interactive.SelectContent)1 ButtonContent (com.freya02.botcommands.api.utils.ButtonContent)1 EmojiUtils (com.freya02.botcommands.api.utils.EmojiUtils)1 ApplicationOptionData (com.freya02.botcommands.internal.ApplicationOptionData)1