Search in sources :

Example 11 with InteractionHook

use of net.dv8tion.jda.api.interactions.InteractionHook in project JavaBot by Java-Discord.

the class HelpChannelManager method unreserveChannelByOwner.

private void unreserveChannelByOwner(TextChannel channel, User owner, Interaction interaction) {
    var optionalReservation = getReservationForChannel(channel.getIdLong());
    if (optionalReservation.isEmpty()) {
        log.warn("Could not find current reservation data for channel {}. Unreserving the channel without thanks.", channel.getAsMention());
        unreserveChannel(channel);
        return;
    }
    var reservation = optionalReservation.get();
    // Ask the user for some feedback about the help channel, if possible.
    getParticipantsSinceReserved(channel).thenAcceptAsync(participants -> {
        List<Member> potentialHelpers = new ArrayList<>(participants.size());
        for (var entry : participants.entrySet()) {
            if (!entry.getKey().getUser().equals(owner))
                potentialHelpers.add(entry.getKey());
        }
        if (potentialHelpers.isEmpty()) {
            InteractionHook hook;
            if (interaction.getType() == InteractionType.COMPONENT) {
                hook = ((ButtonInteractionEvent) interaction).getHook();
            } else if (interaction.getType() == InteractionType.COMMAND) {
                hook = ((SlashCommandInteractionEvent) interaction).getHook();
            } else {
                throw new IllegalStateException("Unable to obtain Interaction Hook!");
            }
            Responses.info(hook, "Channel Unreserved", "Your channel has been unreserved.").queue();
            unreserveChannel(channel).queue();
            return;
        }
        potentialHelpers.sort((o1, o2) -> {
            int c = Integer.compare(participants.get(o1).size(), participants.get(o2).size());
            if (c == 0)
                return o1.getEffectiveName().compareTo(o2.getEffectiveName());
            return c;
        });
        sendThanksButtonsMessage(potentialHelpers, reservation, interaction, channel);
        try {
            setTimeout(channel, 5);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    });
}
Also used : InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) SQLException(java.sql.SQLException)

Example 12 with InteractionHook

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

Example 13 with InteractionHook

use of net.dv8tion.jda.api.interactions.InteractionHook in project Lauren by Yuhtin.

the class QueueCommand method execute.

@Override
public void execute(CommandInteraction event, InteractionHook hook) throws Exception {
    if (event.getMember() == null || event.getGuild() == null)
        return;
    val trackManager = TrackManager.of(event.getGuild());
    if (trackManager.getQueuedTracks().isEmpty()) {
        hook.sendMessageEmbeds(SimpleEmbed.of("Eita não tem nenhum batidão tocando, adiciona uns ai <3")).queue();
        return;
    }
    val pageOption = event.getOption("pagina");
    val page = pageOption == null ? 1 : (int) pageOption.getAsDouble();
    val queue = trackManager.getQueuedTracks();
    val songs = new String[queue.size()];
    var totalTime = 0L;
    var i = 0;
    for (val audioInfo : queue) {
        totalTime += audioInfo.getTrack().getInfo().length;
        songs[i] = audioInfo.toString();
        ++i;
    }
    val timeInLetter = TrackUtils.getTimeStamp(totalTime);
    BUILDER.setText((number, number2) -> {
        val stringBuilder = new StringBuilder();
        if (trackManager.getPlayer().getPlayingTrack() != null) {
            stringBuilder.append(trackManager.getPlayer().isPaused() ? "\u23F8" : "\u25B6").append(" **").append(trackManager.getPlayer().getPlayingTrack().getInfo().title).append("**").append(" - ").append("`").append(TrackUtils.getTimeStamp(trackManager.getPlayer().getPlayingTrack().getPosition())).append(" / ").append(TrackUtils.getTimeStamp(trackManager.getPlayer().getPlayingTrack().getInfo().length)).append("`").append("\n");
        }
        return stringBuilder.append("\uD83D\uDCBF Informações da Fila | ").append(queue.size()).append(" músicas | `").append(timeInLetter).append("`").toString();
    }).setItems(songs).setUsers(event.getUser()).setColor(event.getMember().getColor());
    BUILDER.build().paginate(hook, page);
}
Also used : lombok.val(lombok.val) CommandInteraction(net.dv8tion.jda.api.interactions.commands.CommandInteraction) lombok.var(lombok.var) Command(com.yuhtin.lauren.commands.Command) Paginator(com.yuhtin.lauren.utils.Paginator) Getter(lombok.Getter) TrackUtils(com.yuhtin.lauren.utils.TrackUtils) CommandInfo(com.yuhtin.lauren.commands.CommandInfo) lombok.val(lombok.val) TimeUnit(java.util.concurrent.TimeUnit) TrackManager(com.yuhtin.lauren.core.music.TrackManager) SimpleEmbed(com.yuhtin.lauren.utils.SimpleEmbed) Startup(com.yuhtin.lauren.startup.Startup) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) lombok.var(lombok.var)

Example 14 with InteractionHook

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

the class RedditCommand method executeCommand.

@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
    InteractionHook hook = event.getHook();
    try {
        event.deferReply().queue();
        OptionMapping option = event.getOption("subreddit");
        String subreddit = option == null || option.getAsString().isEmpty() ? "memes" : option.getAsString().startsWith("r/") ? option.getAsString().substring(2) : option.getAsString();
        String requestURL = String.format("https://meme-api.herokuapp.com/gimme/%s", subreddit);
        OkHttpClient client = Bean.getInstance().getOkHttpClient();
        Request request = new Request.Builder().url(requestURL).get().build();
        Call call = client.newCall(request);
        Response response = call.execute();
        DataObject object = DataObject.fromJson(response.body().string());
        response.close();
        if (!response.isSuccessful()) {
            if (!object.isNull("message"))
                hook.sendMessageEmbeds(EmbedUtil.errorEmbed(object.getString("message"))).queue();
            else
                hook.sendMessageEmbeds(EmbedUtil.errorEmbed(ctx.getLocalized("commands.meme.api_down"))).queue();
            return;
        }
        if (object.getBoolean("nsfw") && !event.getTextChannel().isNSFW()) {
            hook.sendMessageEmbeds(EmbedUtil.errorEmbed(ctx.getLocalized("commands.meme.is_nsfw"))).setEphemeral(true).queue();
            return;
        }
        EmbedBuilder builder = new EmbedBuilder().setTitle(object.getString("title")).setImage(object.getString("url")).setDescription("[" + ctx.getLocalized("commands.meme.source") + "](" + object.getString("postLink") + ")").setFooter("r/" + object.getString("subreddit")).setColor(0x152238);
        hook.sendMessageEmbeds(builder.build()).queue();
    } catch (Exception e) {
        hook.sendMessageEmbeds(EmbedUtil.errorEmbed(ctx.getLocalized("general.unknown_error_occured"))).queue();
    }
}
Also used : OptionMapping(net.dv8tion.jda.api.interactions.commands.OptionMapping) Response(okhttp3.Response) Call(okhttp3.Call) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) InteractionHook(net.dv8tion.jda.api.interactions.InteractionHook) OkHttpClient(okhttp3.OkHttpClient) DataObject(net.dv8tion.jda.api.utils.data.DataObject) Request(okhttp3.Request)

Aggregations

InteractionHook (net.dv8tion.jda.api.interactions.InteractionHook)14 Member (net.dv8tion.jda.api.entities.Member)4 SlashCommandInteractionEvent (net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent)4 OptionMapping (net.dv8tion.jda.api.interactions.commands.OptionMapping)4 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)3 JDA (net.dv8tion.jda.api.JDA)3 User (net.dv8tion.jda.api.entities.User)3 ActionRow (net.dv8tion.jda.api.interactions.components.ActionRow)3 IOException (java.io.IOException)2 JDABuilder (net.dv8tion.jda.api.JDABuilder)2 Permission (net.dv8tion.jda.api.Permission)2 Message (net.dv8tion.jda.api.entities.Message)2 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)2 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)2 TextChannel (net.dv8tion.jda.api.entities.TextChannel)2 ListenerAdapter (net.dv8tion.jda.api.hooks.ListenerAdapter)2 OptionType (net.dv8tion.jda.api.interactions.commands.OptionType)2 Commands (net.dv8tion.jda.api.interactions.commands.build.Commands)2 CommandListUpdateAction (net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction)2 DiscordEmbedTag (com.denizenscript.ddiscordbot.objects.DiscordEmbedTag)1