Search in sources :

Example 1 with ButtonInteractionEvent

use of net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent in project Wylx by Wylx-Bot.

the class Helper method createButtonInteraction.

/**
 * Helper function to create button interactions on a message.
 * The buttons remain until either interactionRunnable returns true, or a timeout occurs after 2 minutes.
 *
 * @param interactionRunnable (ButtonInteractionEvent, Object == ctx) -> Boolean
 *                            Ran anytime a button is pressed on the method
 * @param interactionEndRunnable (Message, Boolean == timed out) -> Void
 *                               Ran once when buttons are removed.
 * @param actionRows Action Rows which contain buttons
 * @param toSend Message to be sent with buttons
 * @param ctx Context to be passed into interactionRunnable.
 *            Useful for keeping state between calls of interactionRunnable
 */
public static void createButtonInteraction(BiFunction<ButtonInteractionEvent, Object, Boolean> interactionRunnable, BiConsumer<Message, Boolean> interactionEndRunnable, Collection<ActionRow> actionRows, MessageAction toSend, Object ctx) {
    Timer timer = new Timer();
    Message msg = toSend.setActionRows(actionRows).complete();
    JDA jda = Wylx.getInstance().getJDA();
    ListenerAdapter adapter = new ListenerAdapter() {

        @Override
        public void onButtonInteraction(@NotNull ButtonInteractionEvent event) {
            // Not the message we sent
            if (event.getMessage().getIdLong() != msg.getIdLong()) {
                return;
            }
            if (interactionRunnable.apply(event, ctx)) {
                jda.removeEventListener(this);
                timer.cancel();
                interactionEndRunnable.accept(msg, false);
            }
        }
    };
    jda.addEventListener(adapter);
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            jda.removeEventListener(adapter);
            timer.cancel();
            interactionEndRunnable.accept(msg, true);
        }
    }, ONE_HOUR);
}
Also used : ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) Timer(java.util.Timer) Message(net.dv8tion.jda.api.entities.Message) TimerTask(java.util.TimerTask) ButtonInteractionEvent(net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent) JDA(net.dv8tion.jda.api.JDA) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

Timer (java.util.Timer)1 TimerTask (java.util.TimerTask)1 JDA (net.dv8tion.jda.api.JDA)1 Message (net.dv8tion.jda.api.entities.Message)1 ButtonInteractionEvent (net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent)1 ListenerAdapter (net.dv8tion.jda.api.hooks.ListenerAdapter)1 NotNull (org.jetbrains.annotations.NotNull)1