Search in sources :

Example 1 with Component

use of net.dv8tion.jda.api.interactions.components.Component in project Pagination-Utils by ygimenez.

the class Pages method categorize.

/**
 * Adds menu-like buttons to the specified {@link Message}/{@link MessageEmbed}
 * which will browse through a given {@link Map} of pages. You may only specify
 * one {@link Page} per button, adding another button with an existing unicode
 * will overwrite the current button's {@link Page}. You can specify how long
 * the listener will stay active before shutting down itself after a no-activity
 * interval.
 *
 * @param msg         The {@link Message} sent which will be categorized.
 * @param categories  The categories to be shown. The categories are defined by
 *                    a {@link Map} containing emoji unicodes or emote ids as keys and
 *                    {@link Pages} as values.
 * @param useButtons  Whether to use interaction {@link Button} or reactions. Will fallback to false if the supplied
 *                    {@link Message} was not sent by the bot.
 * @param time        The time before the listener automatically stop listening
 *                    for further events (recommended: 60).
 * @param unit        The time's {@link TimeUnit} (recommended:
 *                    {@link TimeUnit#SECONDS}).
 * @param canInteract {@link Predicate} to determine whether the {@link User}
 *                    that pressed the button can interact with it or not.
 * @throws ErrorResponseException          Thrown if the {@link Message} no longer exists
 *                                         or cannot be accessed when triggering a
 *                                         {@link GenericMessageReactionEvent}.
 * @throws InsufficientPermissionException Thrown if this library cannot remove reactions
 *                                         due to lack of bot permission.
 * @throws InvalidStateException           Thrown if the library wasn't activated.
 */
public static WeakReference<String> categorize(@Nonnull Message msg, @Nonnull Map<Emoji, Page> categories, boolean useButtons, int time, TimeUnit unit, Predicate<User> canInteract) throws ErrorResponseException, InsufficientPermissionException {
    if (!isActivated())
        throw new InvalidStateException();
    boolean useBtns = useButtons && msg.getAuthor().getId().equals(msg.getJDA().getSelfUser().getId());
    Map<Emoji, Page> cats = Collections.unmodifiableMap(categories);
    clearButtons(msg);
    clearReactions(msg);
    if (useBtns) {
        List<ActionRow> rows = new ArrayList<>();
        List<Component> row = new ArrayList<>();
        for (Emoji k : cats.keySet()) {
            if (row.size() == 5) {
                rows.add(ActionRow.of(row));
                row = new ArrayList<>();
            }
            row.add(Button.secondary(Emote.getId(k), k));
        }
        Button button = Button.danger(CANCEL.name(), paginator.getEmote(CANCEL));
        if (rows.size() == 5 && row.size() == 5) {
            row.set(4, button);
        } else if (row.size() == 5) {
            rows.add(ActionRow.of(row));
            row = new ArrayList<>();
            row.add(button);
        } else {
            row.add(button);
        }
        rows.add(ActionRow.of(row));
        msg.editMessageComponents(rows).submit();
    } else {
        for (Emoji k : cats.keySet()) {
            msg.addReaction(k.getAsMention().replaceAll("[<>]", "")).submit();
        }
        msg.addReaction(paginator.getStringEmote(CANCEL)).submit();
    }
    return handler.addEvent(msg, new ThrowingBiConsumer<>() {

        private Emoji currCat = null;

        private ScheduledFuture<?> timeout;

        private final Consumer<Void> success = s -> {
            if (timeout != null)
                timeout.cancel(true);
            handler.removeEvent(msg);
            if (paginator.isDeleteOnCancel())
                msg.delete().submit();
        };

        {
            if (time > 0 && unit != null)
                timeout = executor.schedule(() -> finalizeEvent(msg, success), time, unit);
        }

        @Override
        public void acceptThrows(@Nonnull User u, @Nonnull PaginationEventWrapper wrapper) {
            Message m = subGet(wrapper.retrieveMessage());
            if (canInteract == null || canInteract.test(u)) {
                if (u.isBot() || m == null || !wrapper.getMessageId().equals(msg.getId()))
                    return;
                Emoji emoji = null;
                Emote emt = NONE;
                if (wrapper.getContent() instanceof MessageReaction) {
                    MessageReaction.ReactionEmote reaction = ((MessageReaction) wrapper.getContent()).getReactionEmote();
                    emoji = toEmoji(reaction);
                    emt = toEmote(reaction);
                } else if (wrapper.getContent() instanceof Button) {
                    Button btn = (Button) wrapper.getContent();
                    emoji = btn.getEmoji();
                    if (btn.getId() != null && Emote.isNative(btn) && !btn.getId().contains(".")) {
                        emt = Emote.valueOf(btn.getId().replace("*", ""));
                    }
                }
                if (emt == CANCEL) {
                    finalizeEvent(m, success);
                    return;
                } else if (emoji != null && !Objects.equals(emoji, currCat)) {
                    Page pg = cats.get(emoji);
                    if (pg != null) {
                        if (currCat != null && pg instanceof InteractPage) {
                            modifyButtons(m, Map.of(Emote.getId(currCat), Button::asEnabled));
                        }
                        updatePage(m, pg);
                        currCat = emoji;
                        if (pg instanceof InteractPage) {
                            modifyButtons(m, Map.of(Emote.getId(currCat), Button::asDisabled));
                        }
                    }
                }
                if (timeout != null)
                    timeout.cancel(true);
                if (time > 0 && unit != null)
                    timeout = executor.schedule(() -> finalizeEvent(m, success), time, unit);
                if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
                    subGet(((MessageReaction) wrapper.getContent()).removeReaction(u));
                }
            }
        }
    });
}
Also used : InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Function(java.util.function.Function) MessageHandler(com.github.ygimenez.listener.MessageHandler) Component(net.dv8tion.jda.api.interactions.components.Component) GenericMessageReactionEvent(net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent) Button(net.dv8tion.jda.api.interactions.components.Button) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) WeakReference(java.lang.ref.WeakReference) Nonnull(javax.annotation.Nonnull) RestAction(net.dv8tion.jda.api.requests.RestAction) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Emote(com.github.ygimenez.type.Emote) java.util.concurrent(java.util.concurrent) Predicate(java.util.function.Predicate) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) InvalidStateException(com.github.ygimenez.exception.InvalidStateException) Consumer(java.util.function.Consumer) InvalidHandlerException(com.github.ygimenez.exception.InvalidHandlerException) NullPageException(com.github.ygimenez.exception.NullPageException) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) AlreadyActivatedException(com.github.ygimenez.exception.AlreadyActivatedException) com.github.ygimenez.model(com.github.ygimenez.model) Button(net.dv8tion.jda.api.interactions.components.Button) Component(net.dv8tion.jda.api.interactions.components.Component) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) Emote(com.github.ygimenez.type.Emote) InvalidStateException(com.github.ygimenez.exception.InvalidStateException)

Example 2 with Component

use of net.dv8tion.jda.api.interactions.components.Component in project Pagination-Utils by ygimenez.

the class Pages method modifyButtons.

/**
 * Utility method for modifying message buttons.
 *
 * @param msg     The {@link Message} holding the buttons.
 * @param changes {@link Map} containing desired changes, indexed by {@link Button} ID.
 */
public static void modifyButtons(Message msg, Map<String, Function<Button, Button>> changes) {
    List<ActionRow> rows = new ArrayList<>(msg.getActionRows());
    for (ActionRow ar : rows) {
        List<Component> row = ar.getComponents();
        for (int i = 0; i < row.size(); i++) {
            Component c = row.get(i);
            if (c instanceof Button && changes.containsKey(c.getId())) {
                row.set(i, changes.get(c.getId()).apply((Button) c));
            }
        }
    }
    subGet(msg.editMessageComponents(rows));
}
Also used : Button(net.dv8tion.jda.api.interactions.components.Button) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) Component(net.dv8tion.jda.api.interactions.components.Component)

Example 3 with Component

use of net.dv8tion.jda.api.interactions.components.Component in project Pagination-Utils by ygimenez.

the class Pages method buttonize.

/**
 * Adds buttons to the specified {@link Message}/{@link MessageEmbed}, with each
 * executing a specific task on click. You may only specify one {@link Runnable}
 * per button, adding another button with an existing unicode will overwrite the
 * current button's {@link Runnable}. You can specify the time in which the
 * listener will automatically stop itself after a no-activity interval.
 *
 * @param msg              The {@link Message} sent which will be buttoned.
 * @param buttons          The buttons to be shown. The buttons are defined by a
 *                         Map containing emoji unicodes or emote ids as keys and
 *                         {@link ThrowingTriConsumer}&lt;{@link Member}, {@link Message}, {@link InteractionHook}&gt;
 *                         containing desired behavior as value.
 * @param useButtons       Whether to use interaction {@link Button} or reactions. Will fallback to false if the supplied
 *                         {@link Message} was not sent by the bot.
 * @param showCancelButton Should the {@link Emote#CANCEL} button be created automatically?
 * @param time             The time before the listener automatically stop
 *                         listening for further events (recommended: 60).
 * @param unit             The time's {@link TimeUnit} (recommended:
 *                         {@link TimeUnit#SECONDS}).
 * @param canInteract      {@link Predicate} to determine whether the
 *                         {@link User} that pressed the button can interact
 *                         with it or not.
 * @param onCancel         Action to be run after the listener is removed.
 * @throws ErrorResponseException          Thrown if the {@link Message} no longer exists
 *                                         or cannot be accessed when triggering a
 *                                         {@link GenericMessageReactionEvent}.
 * @throws InsufficientPermissionException Thrown if this library cannot remove reactions
 *                                         due to lack of bot permission.
 * @throws InvalidStateException           Thrown if the library wasn't activated.
 */
public static WeakReference<String> buttonize(@Nonnull Message msg, @Nonnull Map<Emoji, ThrowingConsumer<ButtonWrapper>> buttons, boolean useButtons, boolean showCancelButton, int time, TimeUnit unit, Predicate<User> canInteract, Consumer<Message> onCancel) throws ErrorResponseException, InsufficientPermissionException {
    if (!isActivated())
        throw new InvalidStateException();
    boolean useBtns = useButtons && msg.getAuthor().getId().equals(msg.getJDA().getSelfUser().getId());
    Map<Emoji, ThrowingConsumer<ButtonWrapper>> btns = Collections.unmodifiableMap(buttons);
    clearButtons(msg);
    clearReactions(msg);
    if (useBtns) {
        List<ActionRow> rows = new ArrayList<>();
        List<Component> row = new ArrayList<>();
        for (Emoji k : btns.keySet()) {
            if (row.size() == 5) {
                rows.add(ActionRow.of(row));
                row = new ArrayList<>();
            }
            row.add(Button.secondary(Emote.getId(k), k));
        }
        if (!btns.containsKey(paginator.getEmote(CANCEL)) && showCancelButton) {
            Button button = Button.danger(CANCEL.name(), paginator.getEmote(CANCEL));
            if (rows.size() == 5 && row.size() == 5) {
                row.set(4, button);
            } else if (row.size() == 5) {
                rows.add(ActionRow.of(row));
                row = new ArrayList<>();
                row.add(button);
            } else {
                row.add(button);
            }
        }
        rows.add(ActionRow.of(row));
        msg.editMessageComponents(rows).submit();
    } else {
        for (Emoji k : btns.keySet()) {
            msg.addReaction(k.getAsMention().replaceAll("[<>]", "")).submit();
        }
        if (!btns.containsKey(paginator.getEmote(CANCEL)) && showCancelButton)
            msg.addReaction(paginator.getStringEmote(CANCEL)).submit();
    }
    return handler.addEvent(msg, new ThrowingBiConsumer<>() {

        private ScheduledFuture<?> timeout;

        private final Consumer<Void> success = s -> {
            if (timeout != null)
                timeout.cancel(true);
            handler.removeEvent(msg);
            if (onCancel != null)
                onCancel.accept(msg);
            if (paginator.isDeleteOnCancel())
                msg.delete().submit();
        };

        {
            if (time > 0 && unit != null)
                timeout = executor.schedule(() -> finalizeEvent(msg, success), time, unit);
        }

        @Override
        public void acceptThrows(@Nonnull User u, @Nonnull PaginationEventWrapper wrapper) {
            Message m = subGet(wrapper.retrieveMessage());
            if (canInteract == null || canInteract.test(u)) {
                if (u.isBot() || m == null || !wrapper.getMessageId().equals(msg.getId()))
                    return;
                Emoji emoji = null;
                Emote emt = NONE;
                if (wrapper.getContent() instanceof MessageReaction) {
                    MessageReaction.ReactionEmote reaction = ((MessageReaction) wrapper.getContent()).getReactionEmote();
                    emoji = toEmoji(reaction);
                    emt = toEmote(reaction);
                } else if (wrapper.getContent() instanceof Button) {
                    Button btn = (Button) wrapper.getContent();
                    emoji = btn.getEmoji();
                    if (btn.getId() != null && Emote.isNative(btn) && !btn.getId().contains(".")) {
                        emt = Emote.valueOf(btn.getId().replace("*", ""));
                    }
                }
                if ((!btns.containsKey(paginator.getEmote(CANCEL)) && showCancelButton) && emt == CANCEL) {
                    finalizeEvent(m, success);
                    return;
                }
                InteractionHook hook;
                if (wrapper.getSource() instanceof ButtonClickEvent) {
                    hook = ((ButtonClickEvent) wrapper.getSource()).getHook();
                } else {
                    hook = null;
                }
                ThrowingConsumer<ButtonWrapper> act = btns.get(emoji);
                if (act != null) {
                    act.accept(new ButtonWrapper(wrapper.getUser(), hook, m));
                }
                if (timeout != null)
                    timeout.cancel(true);
                if (time > 0 && unit != null)
                    timeout = executor.schedule(() -> finalizeEvent(m, success), time, unit);
                if (wrapper.isFromGuild() && wrapper.getSource() instanceof MessageReactionAddEvent && paginator.isRemoveOnReact()) {
                    subGet(((MessageReaction) wrapper.getContent()).removeReaction(u));
                }
            }
        }
    });
}
Also used : InsufficientPermissionException(net.dv8tion.jda.api.exceptions.InsufficientPermissionException) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Function(java.util.function.Function) MessageHandler(com.github.ygimenez.listener.MessageHandler) Component(net.dv8tion.jda.api.interactions.components.Component) GenericMessageReactionEvent(net.dv8tion.jda.api.events.message.react.GenericMessageReactionEvent) Button(net.dv8tion.jda.api.interactions.components.Button) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) WeakReference(java.lang.ref.WeakReference) Nonnull(javax.annotation.Nonnull) RestAction(net.dv8tion.jda.api.requests.RestAction) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Emote(com.github.ygimenez.type.Emote) java.util.concurrent(java.util.concurrent) Predicate(java.util.function.Predicate) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) InvalidStateException(com.github.ygimenez.exception.InvalidStateException) Consumer(java.util.function.Consumer) InvalidHandlerException(com.github.ygimenez.exception.InvalidHandlerException) NullPageException(com.github.ygimenez.exception.NullPageException) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) AlreadyActivatedException(com.github.ygimenez.exception.AlreadyActivatedException) com.github.ygimenez.model(com.github.ygimenez.model) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Component(net.dv8tion.jda.api.interactions.components.Component) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) Emote(com.github.ygimenez.type.Emote) InvalidStateException(com.github.ygimenez.exception.InvalidStateException) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook)

Aggregations

ActionRow (net.dv8tion.jda.api.interactions.components.ActionRow)3 Button (net.dv8tion.jda.api.interactions.components.Button)3 Component (net.dv8tion.jda.api.interactions.components.Component)3 AlreadyActivatedException (com.github.ygimenez.exception.AlreadyActivatedException)2 InvalidHandlerException (com.github.ygimenez.exception.InvalidHandlerException)2 InvalidStateException (com.github.ygimenez.exception.InvalidStateException)2 NullPageException (com.github.ygimenez.exception.NullPageException)2 MessageHandler (com.github.ygimenez.listener.MessageHandler)2 com.github.ygimenez.model (com.github.ygimenez.model)2 Emote (com.github.ygimenez.type.Emote)2 WeakReference (java.lang.ref.WeakReference)2 java.util (java.util)2 java.util.concurrent (java.util.concurrent)2 Consumer (java.util.function.Consumer)2 Function (java.util.function.Function)2 Predicate (java.util.function.Predicate)2 Nonnull (javax.annotation.Nonnull)2 JDA (net.dv8tion.jda.api.JDA)2 net.dv8tion.jda.api.entities (net.dv8tion.jda.api.entities)2 ButtonClickEvent (net.dv8tion.jda.api.events.interaction.ButtonClickEvent)2