use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent in project Gary by help-chat.
the class PaginationHandler method execute.
@Override
protected void execute(GenericEvent event) {
switch(EventsEnum.fromEvent(event)) {
case MESSAGE_REACTION_ADD:
GuildMessageReactionAddEvent e = (GuildMessageReactionAddEvent) event;
if (!e.getMember().getUser().isBot()) {
String messageId = e.getMessageId();
if (paginations.containsKey(messageId)) {
MessageReaction.ReactionEmote reactionEmote = e.getReactionEmote();
PaginationPage newPage;
if (reactionEmote.getEmote() == null) {
newPage = paginations.get(messageId).getPage(reactionEmote.getName());
} else {
newPage = paginations.get(messageId).getPage(reactionEmote.getEmote());
}
if (newPage != null) {
Object newMessage = newPage.getMessage();
Message message = e.getChannel().retrieveMessageById(messageId).complete();
if (newMessage instanceof String) {
message.editMessage((String) newMessage).queue();
} else if (newMessage instanceof MessageEmbed) {
message.editMessage((MessageEmbed) newMessage).override(true).queue();
}
e.getReaction().removeReaction(e.getUser()).queue();
}
}
}
break;
case MESSAGE_DELETE:
paginations.remove(((GuildMessageDeleteEvent) event).getMessageId());
break;
}
}
use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent in project Sx4 by sx4-discord-bot.
the class StarboardHandler method onGuildMessageReactionAdd.
public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
if (event.getUser().isBot()) {
return;
}
List<Bson> starboardPipeline = List.of(Aggregates.match(Filters.or(Filters.eq("originalMessageId", event.getMessageIdLong()), Filters.eq("messageId", event.getMessageIdLong()))), Aggregates.project(Projections.include("originalMessageId", "channelId")));
List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("starboard"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.unionWith("starboards", starboardPipeline), Aggregates.group(null, Accumulators.max("messageId", "$originalMessageId"), Accumulators.max("channelId", "$channelId"), Accumulators.max("starboard", "$starboard"), Accumulators.max("premium", "$premium")));
this.bot.getMongo().aggregateGuilds(pipeline).whenComplete((documents, aggregateException) -> {
if (ExceptionUtility.sendErrorMessage(aggregateException)) {
return;
}
if (documents.isEmpty()) {
return;
}
Document data = documents.get(0);
Document starboard = data.get("starboard", MongoDatabase.EMPTY_DOCUMENT);
if (!starboard.get("enabled", false)) {
return;
}
long channelId = starboard.get("channelId", 0L), messageChannelId = data.get("channelId", 0L);
TextChannel messageChannel = messageChannelId == 0L ? event.getChannel() : event.getGuild().getTextChannelById(messageChannelId);
TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
if (channel == null || messageChannel == null) {
return;
}
ReactionEmote emote = event.getReactionEmote();
boolean emoji = emote.isEmoji();
Document emoteData = starboard.get("emote", new Document("name", "⭐"));
if ((emoji && !emote.getEmoji().equals(emoteData.getString("name"))) || (!emoji && (!emoteData.containsKey("id") || emoteData.getLong("id") != emote.getIdLong()))) {
return;
}
Long originalMessageId = data.getLong("messageId");
long messageId = originalMessageId == null ? event.getMessageIdLong() : originalMessageId;
messageChannel.retrieveMessageById(messageId).queue(message -> {
String image = message.getAttachments().stream().filter(Attachment::isImage).map(Attachment::getUrl).findFirst().orElse(null);
Document star = new Document("userId", event.getUser().getIdLong()).append("messageId", messageId).append("guildId", event.getGuild().getIdLong());
this.bot.getMongo().insertStar(star).thenCompose(result -> {
Bson update = Updates.combine(Updates.inc("count", 1), Updates.setOnInsert("originalMessageId", messageId), Updates.setOnInsert("guildId", event.getGuild().getIdLong()), Updates.setOnInsert("channelId", event.getChannel().getIdLong()), Updates.set("content", message.getContentRaw()), Updates.set("authorId", message.getAuthor().getIdLong()));
if (image != null) {
update = Updates.combine(update, Updates.set("image", image));
}
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).upsert(true);
return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", messageId), update, options);
}).thenCompose(updatedData -> {
WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
if (webhookMessage == null) {
return CompletableFuture.completedFuture(null);
}
if (updatedData.containsKey("messageId")) {
this.bot.getStarboardManager().editStarboard(updatedData.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
// return null so no update is made in the next stage
return CompletableFuture.completedFuture(null);
} else {
return this.bot.getStarboardManager().sendStarboard(channel, starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
}
}).whenComplete((createdMessage, exception) -> {
if (exception instanceof CompletionException) {
Throwable cause = exception.getCause();
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
// duplicate star just ignore
return;
}
}
if (ExceptionUtility.sendErrorMessage(exception)) {
return;
}
if (createdMessage != null) {
Route.CompiledRoute route = Route.Messages.ADD_REACTION.compile(Long.toString(createdMessage.getChannelId()), Long.toString(createdMessage.getId()), EncodingUtil.encodeReaction(emote.getAsReactionCode()), "@me");
new RestActionImpl<>(event.getJDA(), route).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_EMOJI, ErrorResponse.MISSING_PERMISSIONS, ErrorResponse.MISSING_ACCESS));
this.bot.getMongo().updateStarboard(Filters.eq("originalMessageId", messageId), Updates.set("messageId", createdMessage.getId())).whenComplete(MongoDatabase.exceptionally());
}
});
});
});
}
use of net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent in project Levelbot by Kaktushose.
the class ShopListener method onGuildMessageReactionAdd.
@Override
public void onGuildMessageReactionAdd(@NotNull GuildMessageReactionAddEvent event) {
// bots should just be ignored
if (event.getUser().isBot()) {
return;
}
// must be in channel #levelsystem
if (event.getChannel().getIdLong() != LEVEL_SYSTEM_CHANNEL_ID) {
return;
}
if (levelbot.getUserService().getMutedUsers().contains(event.getUser().getIdLong())) {
event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
return;
}
// indicates active purchase
if (activeUsers.contains(event.getUser().getIdLong())) {
event.getReaction().removeReaction(event.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
return;
}
Member member = event.getMember();
ItemCategory itemCategory;
switch(event.getMessageId()) {
case PREMIUM_MESSAGE_ID:
itemCategory = ItemCategory.PREMIUM;
break;
case DJ_MESSAGE_ID:
itemCategory = ItemCategory.DJ;
break;
case NICKNAME_MESSAGE_ID:
itemCategory = ItemCategory.NICKNAME;
break;
case COINS_BOOSTER_MESSAGE_ID:
itemCategory = ItemCategory.COINS_BOOSTER;
break;
case XP_BOOSTER_MESSAGE_ID:
itemCategory = ItemCategory.XP_BOOSTER;
break;
default:
event.getReaction().removeReaction(member.getUser()).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
return;
}
int variant;
switch(event.getReactionEmote().getName()) {
case NumberEmojis.ONE:
variant = 0;
break;
case NumberEmojis.TWO:
variant = 1;
break;
case NumberEmojis.THREE:
variant = 2;
break;
default:
event.getReaction().removeReaction(member.getUser()).queue();
return;
}
if ((itemCategory == ItemCategory.COINS_BOOSTER || itemCategory == ItemCategory.XP_BOOSTER) && variant == 2) {
event.getReaction().removeReaction(member.getUser()).queue();
return;
}
Item item = levelService.getItemsByCategoryId(itemCategory.id).get(variant);
BotUser botUser = userService.getUserById(member.getIdLong());
String fail = null;
if (shopService.hasItemOfCategory(member.getIdLong(), item.getCategoryId())) {
fail = "Du besitzt dieses Item bereits!";
}
if (botUser.getCoins() < item.getPrice()) {
fail = "Du hast nicht genug Münzen!";
}
TextChannel channel = event.getChannel();
Consumer<Message> delete = success -> success.delete().queueAfter(30, TimeUnit.SECONDS, null, new ErrorHandler().ignore(UNKNOWN_MESSAGE));
MessageBuilder builder = new MessageBuilder().append(member.getAsMention());
if (fail != null) {
// transaction failed
channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopError").injectValue("message", fail).toMessageEmbed()).build()).queue(delete);
} else {
activeUsers.add(member.getIdLong());
// confirm transaction
channel.sendMessage(builder.setEmbeds(embedCache.getEmbed("shopConfirm").injectValue("item", item.getName()).injectValue("price", item.getPrice()).toMessageEmbed()).build()).queue(confirmMessage -> {
// wait for reactions
// delete confirm message after 30 secs if nothing happens
confirmMessage.delete().queueAfter(30, TimeUnit.SECONDS, success -> activeUsers.remove(member.getIdLong()), new ErrorHandler().ignore(UNKNOWN_MESSAGE));
confirmMessage.addReaction(CONFIRM).and(confirmMessage.addReaction(CANCEL)).queue();
ReactionWaiter waiter = new ReactionWaiter(confirmMessage, event.getMember(), CONFIRM, CANCEL);
waiter.onEvent(reactionEvent -> {
// on reaction confirm or cancel emoji
confirmMessage.delete().queue();
if (reactionEvent.getEmote().equals(CONFIRM)) {
shopService.buyItem(botUser.getUserId(), item.getItemId());
// successful transaction
channel.sendMessageEmbeds(embedCache.getEmbed("shopSuccess").injectValue("item", item.getName()).injectValue("days", TimeUnit.MILLISECONDS.toDays(item.getDuration())).toMessageEmbed()).queue(delete);
levelbot.getLogChannel().sendMessageEmbeds(embedCache.getEmbed("buyLog").injectValue("user", member.getAsMention()).injectValue("item", item.getName()).toMessageEmbed()).queue();
}
activeUsers.remove(member.getIdLong());
waiter.stopWaiting(false);
});
});
}
event.getReaction().removeReaction(member.getUser()).queue();
}
Aggregations