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();
}
});
}
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}<{@link Member}, {@link Message}, {@link InteractionHook}>
* 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));
}
}
}
});
}
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);
}
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();
}
}
Aggregations