use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.
the class StarboardCommand method delete.
@Command(value = "delete", aliases = { "remove" }, description = "Deletes a starboard")
@CommandId(204)
@Examples({ "starboard delete 5ff636647f93247aeb2ac429", "starboard delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
if (option.isAlternative()) {
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** starboards in this server?").setActionRow(buttons).submit().thenCompose(message -> {
return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
}).whenComplete((e, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
GenericEvent cancelEvent = ((CancelException) cause).getEvent();
if (cancelEvent != null) {
((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
}
return;
} else if (cause instanceof TimeoutException) {
event.reply("Timed out :stopwatch:").queue();
return;
} else if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getMongo().deleteManyStarboards(Filters.eq("guildId", event.getGuild().getIdLong())).thenCompose(result -> event.getMongo().deleteManyStars(Filters.eq("guildId", event.getGuild().getIdLong()))).whenComplete((result, databaseException) -> {
if (ExceptionUtility.sendExceptionally(event, databaseException)) {
return;
}
if (result.getDeletedCount() == 0) {
e.reply("There are no starboards in this server " + event.getConfig().getFailureEmote()).queue();
return;
}
e.reply("All starboards have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
});
});
} else {
ObjectId id = option.getValue();
AtomicReference<Document> atomicData = new AtomicReference<>();
event.getMongo().findAndDeleteStarboard(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong()))).thenCompose(data -> {
if (data == null) {
return CompletableFuture.completedFuture(null);
}
atomicData.set(data);
return event.getMongo().deleteManyStars(Filters.eq("messageId", data.getLong("originalMessageId")));
}).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result == null) {
event.replyFailure("I could not find that starboard").queue();
return;
}
Document data = atomicData.get();
WebhookClient webhook = event.getBot().getStarboardManager().getWebhook(data.getLong("channelId"));
if (webhook != null) {
webhook.delete(data.getLong("messageId"));
}
event.replySuccess("That starboard has been deleted").queue();
});
}
}
use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent in project Sx4 by sx4-discord-bot.
the class TemplateCommand method delete.
@Command(value = "delete", aliases = { "remove" }, description = "Deletes a template from the current server")
@CommandId(256)
@Examples({ "template delete 6006ff6b94c9ed0f764ada83", "template delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
if (option.isAlternative()) {
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** the templates in this server?").setActionRow(buttons).submit().thenCompose(message -> {
return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
}).whenComplete((e, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
GenericEvent cancelEvent = ((CancelException) cause).getEvent();
if (cancelEvent != null) {
((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
}
return;
} else if (cause instanceof TimeoutException) {
event.reply("Timed out :stopwatch:").queue();
return;
} else if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getMongo().deleteManyTemplates(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
if (ExceptionUtility.sendExceptionally(event, databaseException)) {
return;
}
if (result.getDeletedCount() == 0) {
e.reply("There are no templates in this server " + event.getConfig().getFailureEmote()).queue();
return;
}
e.reply("All templates have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
});
});
} else {
event.getMongo().deleteTemplateById(option.getValue()).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result.getDeletedCount() == 0) {
event.replyFailure("I could not find that template").queue();
return;
}
event.replySuccess("That template has been deleted").queue();
});
}
}
use of net.dv8tion.jda.api.events.interaction.ButtonClickEvent 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.events.interaction.ButtonClickEvent in project c10ver by Gartham.
the class DungeonGame method startDungeon.
private void startDungeon(ButtonClickEvent e) {
// This is broken lmao.
t = e.getMessage();
// try {
// Thread.sleep((long) (Math.random() * 3500 + 1500));
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
var dungeon = Dungeon.simpleEasyDungeon();
var initialRoom = dungeon.getInitialRoom();
var dirsel = new CustomDirsel();
dirsel.disableDirections();
for (var d : initialRoom.getConnectionDirectionsUnmodifiable()) dirsel.enable(d);
var inp = new InputConsumer<ButtonClickEvent>() {
DungeonRoom currentRoom = initialRoom;
@Override
public boolean consume(ButtonClickEvent event, InputProcessor<? extends ButtonClickEvent> processor, InputConsumer<ButtonClickEvent> consumer) {
if (event.getMessageIdLong() != t.getIdLong())
return false;
if (event.getUser().getIdLong() != target.getIdLong()) {
event.reply("That's not for you. >:(").setEphemeral(true).queue();
return true;
}
if (event.getComponentId().equals("act")) {
if (currentRoom.isClaimed()) {
event.reply("You already collected the loot from this room... (You're not supposed to be able to click that button again!)").setEphemeral(true).queue();
return true;
}
currentRoom.setClaimed(true);
var user = clover.getEconomy().getUser(target.getId());
Receipt receipt;
var lr = (LootRoom) currentRoom;
receipt = user.reward(lr.getRewards().autoSetMultipliers(user, channel.getType().isGuild() ? ((GuildChannel) channel).getGuild() : null));
currentRoom.prepare(dirsel, "act");
event.editComponents(dirsel.actionRows()).queue();
t.reply(target.getAsMention() + ", you earned:\n\n" + Utilities.listRewards(receipt)).queue();
// Resend message? Send ephemeral rewards?
} else if (event.getComponentId().equals("repeat")) {
var dsn = new CustomDirsel();
dsn.disableManaged();
var s = channel.sendMessageEmbeds(event.getMessage().getEmbeds()).setActionRows(event.getMessage().getActionRows());
event.editComponents(dsn.actionRows()).queue(x -> s.queue(q -> t = q));
} else {
var dir = DirectionSelector.getDirectionSelected(event);
currentRoom = currentRoom.getRoom(dir);
if (currentRoom == null) {
// Player moved in the wrong direction.
event.reply("You are not supposed to be able to click that!").setEphemeral(true).queue();
return true;
// processor.removeInputConsumer(consumer);
} else if (!currentRoom.isClaimed() && currentRoom instanceof EnemyRoom) {
dirsel.reset();
dirsel.disableManaged();
event.editComponents(dirsel.actionRows()).setContent("**You got into a fight!!!**").setEmbeds(new EmbedBuilder().setColor(new Color(0xFF0000)).setTitle("Room #" + (dungeon.index(currentRoom) + 1)).setDescription("```" + currentRoom.getRoom().tilemapString() + "```").setFooter("Choose a path.").build()).queue();
channel.sendMessage("The room was full of enemies!").queue(x -> {
channel.sendTyping().queue(x0 -> {
var room = (EnemyRoom) currentRoom;
currentRoom.setClaimed(true);
GarmonTeam player = new GarmonTeam(target.getAsTag(), new PlayerFighter(target.getName(), target.getEffectiveAvatarUrl(), BigInteger.valueOf(25), BigInteger.valueOf(100), BigInteger.valueOf(100), BigInteger.valueOf(25), BigInteger.valueOf(5)));
var team = room.getEnemies();
GarmonBattle battle = new GarmonBattle(player, team);
player.setController(new PlayerController(battle, clover, target, channel));
team.setController(new CreatureAI(battle, channel));
battle.startAsync(true, winner -> {
if (winner == player) {
EconomyUser user = clover.getEconomy().getUser(target.getId());
RewardsOperation rewop = RewardsOperation.build(user, channel.getGuild(), BigInteger.valueOf((long) (Math.random() * 142 + 25)), new ItemBunch<>(new VoteToken(gartham.c10ver.economy.items.valuables.VoteToken.Type.NORMAL)));
currentRoom.prepare(dirsel, "act");
channel.sendMessage(target.getAsMention() + ", you won the fight!\nYou earned:\n\n" + Utilities.listRewards(user.reward(rewop))).setEmbeds(new EmbedBuilder().setColor(new Color(0xFF00)).setTitle("Room #" + (dungeon.index(currentRoom) + 1)).setDescription("```" + currentRoom.getRoom().tilemapString() + "```").setFooter("Choose a path.").build()).setActionRows(dirsel.actionRows()).queue(msg -> t = msg);
}
}, (long) (2000 + Math.random() * 1000));
});
});
} else {
currentRoom.prepare(dirsel, "act");
event.editMessageEmbeds(new EmbedBuilder().setTitle("Room #" + (dungeon.index(currentRoom) + 1)).setDescription("```" + currentRoom.getRoom().tilemapString() + "```").setFooter("Choose a path.").build()).setActionRows(dirsel.actionRows()).setContent("").queue();
}
}
return true;
}
};
clover.getEventHandler().getButtonClickProcessor().registerInputConsumer(inp);
t.editMessage(new MessageBuilder().setEmbeds(new EmbedBuilder().setTitle("W1-1").setDescription("```" + initialRoom.getRoom().tilemapString() + "```").setFooter("Choose a path.").build()).setActionRows(dirsel.actionRows()).build()).queue();
}
Aggregations