Search in sources :

Example 1 with GenericGuildMessageReactionEvent

use of net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent in project Sx4 by sx4-discord-bot.

the class ReactionRoleHandler method onGenericGuildMessageReaction.

public void onGenericGuildMessageReaction(GenericGuildMessageReactionEvent event) {
    User user = event.getUser();
    Guild guild = event.getGuild();
    ReactionEmote emote = event.getReactionEmote();
    if (user == null || user.isBot()) {
        return;
    }
    Config config = this.bot.getConfig();
    List<Document> reactionRoles = this.bot.getMongo().getReactionRoles(Filters.eq("messageId", event.getMessageIdLong()), MongoDatabase.EMPTY_DOCUMENT).into(new ArrayList<>());
    if (reactionRoles.isEmpty()) {
        return;
    }
    if (!guild.getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
        user.openPrivateChannel().flatMap(channel -> channel.sendMessage("I am missing the `" + Permission.MANAGE_ROLES.getName() + "` permission " + config.getFailureEmote())).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
        return;
    }
    int reactedTo = 0;
    List<Role> roles = null;
    Document reactionRole = null;
    boolean remove = false;
    Set<Role> memberRoles = new HashSet<>(event.getMember().getRoles());
    for (Document data : reactionRoles) {
        List<Role> rolesData = data.getList("roles", Long.class).stream().map(guild::getRoleById).filter(Objects::nonNull).filter(role -> guild.getSelfMember().canInteract(role)).collect(Collectors.toList());
        boolean allRoles = memberRoles.containsAll(rolesData);
        if (allRoles) {
            reactedTo++;
        }
        Document emoteData = data.get("emote", Document.class);
        if ((emote.isEmoji() && emoteData.containsKey("name") && emoteData.getString("name").equals(emote.getEmoji())) || (emote.isEmote() && emoteData.containsKey("id") && emoteData.getLong("id") == emote.getEmote().getIdLong())) {
            if (rolesData.isEmpty()) {
                return;
            }
            roles = rolesData;
            reactionRole = data;
            remove = allRoles;
        }
    }
    if (roles == null) {
        return;
    }
    if (!remove) {
        List<Document> permissions = reactionRole.getList("permissions", Document.class, Collections.emptyList());
        for (int i = 0; i < permissions.size(); i++) {
            Document permission = permissions.get(i);
            long holderId = permission.getLong("id");
            int type = permission.getInteger("type");
            boolean granted = permission.getBoolean("granted");
            if (type == HolderType.USER.getType() && holderId == user.getIdLong()) {
                if (granted) {
                    break;
                }
            } else if (type == HolderType.ROLE.getType() && (holderId == guild.getIdLong() || memberRoles.stream().anyMatch(role -> role.getIdLong() == holderId))) {
                if (granted) {
                    break;
                }
            }
            if (i == permissions.size() - 1) {
                user.openPrivateChannel().flatMap(channel -> channel.sendMessage("You are not whitelisted to be able to get the roles behind this reaction " + config.getFailureEmote())).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
                return;
            }
        }
    }
    int maxReactions = reactionRole.get("maxReactions", 0);
    if (!remove && reactedTo >= maxReactions && maxReactions != 0) {
        user.openPrivateChannel().flatMap(channel -> channel.sendMessage("You can only react to **" + maxReactions + "** reaction" + (maxReactions == 1 ? "" : "s") + " on this message " + config.getFailureEmote())).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
        return;
    }
    if (remove) {
        guild.modifyMemberRoles(event.getMember(), null, roles).queue();
    } else {
        guild.modifyMemberRoles(event.getMember(), roles, null).queue();
    }
    String message = "You " + (remove ? "no longer" : "now") + " have the role" + (roles.size() == 1 ? "" : "s") + " `" + roles.stream().map(Role::getName).collect(Collectors.joining("`, `")) + "` " + config.getSuccessEmote();
    if (reactionRole.getBoolean("dm", true)) {
        user.openPrivateChannel().flatMap(channel -> channel.sendMessage(message)).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
    }
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) Document(org.bson.Document) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) java.util(java.util) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) User(net.dv8tion.jda.api.entities.User) Filters(com.mongodb.client.model.Filters) Guild(net.dv8tion.jda.api.entities.Guild) Sx4(com.sx4.bot.core.Sx4) Role(net.dv8tion.jda.api.entities.Role) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) UpdateOptions(com.mongodb.client.model.UpdateOptions) GenericGuildMessageReactionEvent(net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent) Config(com.sx4.bot.config.Config) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Updates(com.mongodb.client.model.Updates) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) EventListener(net.dv8tion.jda.api.hooks.EventListener) MessageDeleteEvent(net.dv8tion.jda.api.events.message.MessageDeleteEvent) RoleDeleteEvent(net.dv8tion.jda.api.events.role.RoleDeleteEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) NotNull(org.jetbrains.annotations.NotNull) User(net.dv8tion.jda.api.entities.User) Config(com.sx4.bot.config.Config) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) Role(net.dv8tion.jda.api.entities.Role)

Example 2 with GenericGuildMessageReactionEvent

use of net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent in project pokeraidbot by magnusmickelsson.

the class EmoticonSignUpMessageListener method onEvent.

@Override
public void onEvent(GenericEvent event) {
    String reactionMessageId = null;
    User user = null;
    if (emoteMessageId == null && infoMessageId == null) {
        LOGGER.trace("This listener haven't received a emote message id or info message id yet.");
        return;
    }
    try {
        if (event instanceof GuildMessageReactionAddEvent) {
            final GuildMessageReactionAddEvent reactionEvent = (GuildMessageReactionAddEvent) event;
            user = reactionEvent.getUser();
            // If the bot added any reactions, don't respond to them
            if (user.isBot())
                return;
            reactionMessageId = reactionEvent.getReaction().getMessageId();
            if (emoteMessageId == null || !emoteMessageId.equals(reactionMessageId)) {
                return;
            }
            // If this is a reaction for a user that just triggered an error with his/her reaction, skip it
            if (user.getName().equals(userHadError)) {
                userHadError = null;
                return;
            }
            final MessageReaction.ReactionEmote emote = reactionEvent.getReaction().getReactionEmote();
            if (emote != null) {
                switch(emote.getName()) {
                    case Emotes.ONE:
                        addToSignUp(user, 0, 0, 0, 1);
                        break;
                    case Emotes.TWO:
                        addToSignUp(user, 0, 0, 0, 2);
                        break;
                    case Emotes.THREE:
                        addToSignUp(user, 0, 0, 0, 3);
                        break;
                    case Emotes.FOUR:
                        addToSignUp(user, 0, 0, 0, 4);
                        break;
                    case Emotes.FIVE:
                        addToSignUp(user, 0, 0, 0, 5);
                        break;
                    default:
                }
            }
        } else if (event instanceof GuildMessageReactionRemoveEvent) {
            final GuildMessageReactionRemoveEvent reactionEvent = (GuildMessageReactionRemoveEvent) event;
            // If the bot added any reactions, don't respond to them
            user = reactionEvent.getUser();
            if (user.isBot())
                return;
            // If this is a reaction for a user that just triggered an error with his/her reaction, skip it
            if (user.getName().equals(userHadError)) {
                userHadError = null;
                return;
            }
            reactionMessageId = reactionEvent.getReaction().getMessageId();
            if (!emoteMessageId.equals(reactionMessageId)) {
                return;
            }
            final MessageReaction.ReactionEmote emote = reactionEvent.getReaction().getReactionEmote();
            if (emote != null) {
                switch(emote.getName()) {
                    case Emotes.ONE:
                        removeFromSignUp(user, 0, 0, 0, 1);
                        break;
                    case Emotes.TWO:
                        removeFromSignUp(user, 0, 0, 0, 2);
                        break;
                    case Emotes.THREE:
                        removeFromSignUp(user, 0, 0, 0, 3);
                        break;
                    case Emotes.FOUR:
                        removeFromSignUp(user, 0, 0, 0, 4);
                        break;
                    case Emotes.FIVE:
                        removeFromSignUp(user, 0, 0, 0, 5);
                        break;
                    default:
                }
            }
        }
    } catch (Throwable t) {
        if (event instanceof GenericGuildMessageReactionEvent) {
            final GenericGuildMessageReactionEvent guildMessageReactionEvent = (GenericGuildMessageReactionEvent) event;
            reactionMessageId = guildMessageReactionEvent.getReaction().getMessageId();
            if (emoteMessageId == null) {
                LOGGER.warn("Emote message ID = null, this should get cleaned up!" + " Event: " + printInfoAbout(event));
                return;
            }
            if (!emoteMessageId.equals(reactionMessageId)) {
                LOGGER.warn("We got a guild reaction event throwing exception, but not one we were listening for!" + " Event: " + printInfoAbout(event));
                return;
            }
            // Since we got an error, remove last reaction
            if (reactionMessageId != null && reactionMessageId.equals(emoteMessageId)) {
                // Do this with a slight delay to prevent graphical glitches client side.
                guildMessageReactionEvent.getReaction().removeReaction(user).queueAfter(30, TimeUnit.MILLISECONDS);
                userHadError = user.getName();
            }
            if (user != null && t.getMessage() != null) {
                MessageBuilder messageBuilder = new MessageBuilder();
                if (!t.getMessage().contains(user.getAsMention())) {
                    messageBuilder.append(user.getAsMention()).append(": ");
                }
                messageBuilder.append(t.getMessage());
                guildMessageReactionEvent.getChannel().sendMessage(messageBuilder.build()).queue();
            } else {
                LOGGER.warn("We have a situation where user " + user + " or exception (of type " + t.getClass().getSimpleName() + ") message is null! Event: " + printInfoAbout(event));
            }
        } else {
            LOGGER.warn("Exception in event listener! Event: " + printInfoAbout(event));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Stacktrace:", t);
            }
        }
    }
}
Also used : MessageReaction(net.dv8tion.jda.api.entities.MessageReaction) User(net.dv8tion.jda.api.entities.User) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) GuildMessageReactionRemoveEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionRemoveEvent) GuildMessageReactionAddEvent(net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent) GenericGuildMessageReactionEvent(net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent)

Example 3 with GenericGuildMessageReactionEvent

use of net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent in project Gary by help-chat.

the class ChatSettingsHandler method execute.

@Override
protected void execute(GenericEvent event) {
    GenericGuildMessageReactionEvent e = (GenericGuildMessageReactionEvent) event;
    MessageReaction.ReactionEmote emote = e.getReactionEmote();
    Guild guild = e.getGuild();
    if (e.getMessageIdLong() == 574493964724469780L && !e.getUser().isBot()) {
        ChatSettings setting = ChatSettings.getSetting(emote);
        Member member = e.getMember();
        Role role = guild.getRoleById(setting.roleID);
        if (role == null) {
            return;
        }
        long id = member.getIdLong();
        switch(EventsEnum.fromEvent(event)) {
            case MESSAGE_REACTION_ADD:
                guild.addRoleToMember(member, role).queue();
                set(setting, emote, id, true);
                break;
            case MESSAGE_REACTION_REMOVE:
                guild.removeRoleFromMember(member, role).queue();
                set(setting, emote, id, false);
                break;
        }
    }
}
Also used : Role(net.dv8tion.jda.api.entities.Role) MessageReaction(net.dv8tion.jda.api.entities.MessageReaction) ChatSettings(me.piggypiglet.gary.core.objects.enums.ChatSettings) GenericGuildMessageReactionEvent(net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member)

Example 4 with GenericGuildMessageReactionEvent

use of net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent in project Gary by help-chat.

the class GiveawayHandler method execute.

@Override
protected void execute(GenericEvent event) {
    GenericGuildMessageReactionEvent e = (GenericGuildMessageReactionEvent) event;
    if (!e.getUser().isBot() && e.getReactionEmote().getName().equalsIgnoreCase(Constants.THUMBSUP) && e.getMessageIdLong() == Constants.GIVEAWAY_MESSAGE) {
        Guild guild = e.getGuild();
        Role role = guild.getRoleById(Constants.GIVEAWAY_ROLE);
        switch(EventsEnum.fromEvent(event)) {
            case MESSAGE_REACTION_ADD:
                guild.addRoleToMember(e.getMember(), role).queue();
                break;
            case MESSAGE_REACTION_REMOVE:
                guild.removeRoleFromMember(e.getMember(), role).queue();
                break;
        }
    }
}
Also used : Role(net.dv8tion.jda.api.entities.Role) GenericGuildMessageReactionEvent(net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent) Guild(net.dv8tion.jda.api.entities.Guild)

Aggregations

GenericGuildMessageReactionEvent (net.dv8tion.jda.api.events.message.guild.react.GenericGuildMessageReactionEvent)4 Guild (net.dv8tion.jda.api.entities.Guild)3 Role (net.dv8tion.jda.api.entities.Role)3 MessageReaction (net.dv8tion.jda.api.entities.MessageReaction)2 User (net.dv8tion.jda.api.entities.User)2 MongoWriteException (com.mongodb.MongoWriteException)1 Filters (com.mongodb.client.model.Filters)1 UpdateOptions (com.mongodb.client.model.UpdateOptions)1 Updates (com.mongodb.client.model.Updates)1 Config (com.sx4.bot.config.Config)1 Sx4 (com.sx4.bot.core.Sx4)1 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)1 HolderType (com.sx4.bot.entities.settings.HolderType)1 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)1 java.util (java.util)1 CompletionException (java.util.concurrent.CompletionException)1 Collectors (java.util.stream.Collectors)1 ChatSettings (me.piggypiglet.gary.core.objects.enums.ChatSettings)1 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)1 Permission (net.dv8tion.jda.api.Permission)1