Search in sources :

Example 1 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Bean by Xirado.

the class ReactionRoleCommand method executeCommand.

@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
    Guild guild = event.getGuild();
    Member bot = guild.getSelfMember();
    String subcommand = event.getSubcommandName();
    if (subcommand == null) {
        ctx.reply(ctx.getLocalized("commands.invalid_subcommand")).setEphemeral(true).queue();
        return;
    }
    if (subcommand.equalsIgnoreCase("remove")) {
        TextChannel channel = (TextChannel) event.getOption("channel").getAsGuildChannel();
        if (channel == null) {
            ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.channel_not_exists")).setEphemeral(true).queue();
            return;
        }
        long messageID = 0;
        try {
            messageID = Long.parseLong(event.getOption("message_id").getAsString());
        } catch (Exception e) {
            ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_invalid")).setEphemeral(true).queue();
            return;
        }
        channel.retrieveMessageById(messageID).queue((message) -> {
            ctx.getGuildData().removeReactionRoles(message.getIdLong()).update();
            message.clearReactions().queue(s -> {
            }, e -> {
            });
            ctx.reply(SlashCommandContext.SUCCESS + " " + ctx.getLocalized("commands.reactionroles.removed_success")).setEphemeral(true).queue();
        }, new ErrorHandler().handle(ErrorResponse.UNKNOWN_MESSAGE, (err) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_not_exists")).setEphemeral(true).queue()).handle(EnumSet.allOf(ErrorResponse.class), (err) -> {
            ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("general.unknown_error_occured")).setEphemeral(true).queue();
            LOGGER.error("An error occurred while trying to remove reaction roles!", err);
        }));
    } else if (subcommand.equalsIgnoreCase("create")) {
        TextChannel channel = (TextChannel) event.getOption("channel").getAsGuildChannel();
        if (channel == null) {
            ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.channel_not_exists")).setEphemeral(true).queue();
            return;
        }
        long messageID = 0;
        try {
            messageID = Long.parseLong(event.getOption("message_id").getAsString());
        } catch (Exception e) {
            ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_invalid")).setEphemeral(true).queue();
            return;
        }
        channel.retrieveMessageById(messageID).queue((message) -> {
            Role role = event.getOption("role").getAsRole();
            if (!bot.canInteract(role)) {
                ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.cannot_interact_role", role.getAsMention())).setEphemeral(true).queue();
                return;
            }
            String emoticon = event.getOption("emote").getAsString();
            String emote = emoticon;
            Pattern pattern = Message.MentionType.EMOTE.getPattern();
            Matcher matcher = pattern.matcher(emoticon);
            if (matcher.matches()) {
                emoticon = "emote:" + matcher.group(2);
                emote = matcher.group(2);
            }
            String finalEmote = emote;
            message.addReaction(emoticon).queue((success) -> {
                ReactionRole reactionRole = new at.xirado.bean.data.ReactionRole(finalEmote, message.getIdLong(), role.getIdLong());
                ctx.getGuildData().addReactionRoles(reactionRole).update();
                ctx.reply(SlashCommandContext.SUCCESS + " " + ctx.getLocalized("commands.reactionroles.added_success")).setEphemeral(true).queue();
            }, new ErrorHandler().handle(ErrorResponse.UNKNOWN_EMOJI, (e) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.emote_invalid")).setEphemeral(true).queue()).handle(EnumSet.allOf(ErrorResponse.class), (e) -> {
                ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("general.unknown_error_occured")).setEphemeral(true).queue();
                LOGGER.error("An error occurred while adding reaction-role!", e);
            }));
        }, (error) -> ctx.reply(SlashCommandContext.ERROR + " " + ctx.getLocalized("commands.message_not_exists")).setEphemeral(true).queue());
    }
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) Logger(org.slf4j.Logger) SubcommandData(net.dv8tion.jda.api.interactions.commands.build.SubcommandData) ReactionRole(at.xirado.bean.data.ReactionRole) Permission(net.dv8tion.jda.api.Permission) OptionData(net.dv8tion.jda.api.interactions.commands.build.OptionData) LoggerFactory(org.slf4j.LoggerFactory) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) Commands(net.dv8tion.jda.api.interactions.commands.build.Commands) Matcher(java.util.regex.Matcher) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) SlashCommand(at.xirado.bean.command.SlashCommand) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) EnumSet(java.util.EnumSet) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ReactionRole(at.xirado.bean.data.ReactionRole) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) ReactionRole(at.xirado.bean.data.ReactionRole) ReactionRole(at.xirado.bean.data.ReactionRole)

Example 2 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Bean by Xirado.

the class UnbanCommand method executeCommand.

@Override
public void executeCommand(@NotNull SlashCommandInteractionEvent event, @NotNull SlashCommandContext ctx) {
    Guild guild = event.getGuild();
    if (guild == null)
        return;
    User user = event.getOption("user").getAsUser();
    event.deferReply(true).flatMap(ban -> guild.unban(user)).flatMap(ban -> event.getHook().sendMessageEmbeds(EmbedUtil.successEmbed(user.getAsTag() + " has been unbanned!"))).queue(null, new ErrorHandler().handle(ErrorResponse.UNKNOWN_BAN, (e) -> event.getHook().sendMessageEmbeds(EmbedUtil.errorEmbed("This user is not banned!")).queue()));
}
Also used : OptionType(net.dv8tion.jda.api.interactions.commands.OptionType) Commands(net.dv8tion.jda.api.interactions.commands.build.Commands) Guild(net.dv8tion.jda.api.entities.Guild) SlashCommandContext(at.xirado.bean.command.SlashCommandContext) Permission(net.dv8tion.jda.api.Permission) SlashCommandInteractionEvent(net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent) SlashCommand(at.xirado.bean.command.SlashCommand) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) NotNull(org.jetbrains.annotations.NotNull) EmbedUtil(at.xirado.bean.misc.EmbedUtil) User(net.dv8tion.jda.api.entities.User) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) User(net.dv8tion.jda.api.entities.User) Guild(net.dv8tion.jda.api.entities.Guild)

Example 3 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project SkyBot by duncte123.

the class CommandManager method dispatchCommand.

public void dispatchCommand(@Nonnull ICommand cmd, String invoke, List<String> args, GuildMessageReceivedEvent event) {
    this.commandThread.submit(() -> {
        MDC.put("command.invoke", invoke);
        MDC.put("command.args", args.toString());
        MDC.put("user.tag", event.getAuthor().getAsTag());
        MDC.put("user.id", event.getAuthor().getId());
        MDC.put("guild", event.getGuild().toString());
        setJDAContext(event.getJDA());
        final TextChannel channel = event.getChannel();
        if (!channel.canTalk()) {
            return;
        }
        // Suppress errors from when we can't type in the channel
        channel.sendTyping().queue(null, new ErrorHandler().ignore(UNKNOWN_CHANNEL, MISSING_ACCESS));
        try {
            if (cmd.isCustom()) {
                runCustomCommand(cmd, invoke, args, event);
            } else {
                runNormalCommand(cmd, invoke, args, event);
            }
        } catch (Throwable ex) {
            Sentry.captureException(ex);
            LOGGER.error("Error while parsing command", ex);
            sendMsg(MessageConfig.Builder.fromEvent(event).setMessage("Something went wrong whilst executing the command, my developers have been informed of this\n" + ex.getMessage()).build());
        }
    });
}
Also used : ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) TextChannel(net.dv8tion.jda.api.entities.TextChannel)

Example 4 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project SkyBot by duncte123.

the class MessageListener method blacklistedWordCheck.

private boolean blacklistedWordCheck(DunctebotGuild dbG, Message messageToCheck, Member member, List<String> blacklist) {
    if (member.hasPermission(Permission.KICK_MEMBERS)) {
        return false;
    }
    final String raw = messageToCheck.getContentRaw().toLowerCase();
    for (final String foundWord : blacklist) {
        if (Pattern.compile("\\b" + foundWord + "\\b").matcher(raw).find()) {
            messageToCheck.delete().reason(String.format("Contains blacklisted word: \"%s\"", foundWord)).queue();
            modLog(String.format("Deleted message from %#s in %s for containing the blacklisted word \"%s\"", messageToCheck.getAuthor(), messageToCheck.getChannel(), foundWord), dbG);
            sendMsg(new MessageConfig.Builder().setChannel((TextChannel) messageToCheck.getChannel()).setMessageFormat("%s the word \"%s\" is blacklisted on this server", messageToCheck.getMember(), foundWord).setSuccessAction((m) -> m.delete().queueAfter(5, TimeUnit.SECONDS, null, new ErrorHandler().ignore(UNKNOWN_MESSAGE))).build());
            return true;
        }
    }
    return false;
}
Also used : ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig)

Example 5 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project SkyBot by duncte123.

the class MessageListener method checkSwearFilter.

private boolean checkSwearFilter(Message messageToCheck, GenericGuildMessageEvent event, DunctebotGuild guild) {
    final GuildSetting settings = guild.getSettings();
    if (settings.isEnableSwearFilter() && !topicContains(event.getChannel(), PROFANITY_DISABLE)) {
        final float score = PerspectiveApi.checkSwearFilter(messageToCheck.getContentRaw(), event.getChannel().getId(), variables.getConfig().apis.googl, settings.getFilterType(), variables.getJackson());
        // if the score is less than our target value it's not swearing
        if (score < settings.getAiSensitivity()) {
            return false;
        }
        final String display = messageToCheck.getContentDisplay();
        messageToCheck.delete().reason("Blocked for swearing: " + display).queue(null, new ErrorHandler().ignore(UNKNOWN_MESSAGE, MISSING_PERMISSIONS));
        sendMsg(new MessageConfig.Builder().setChannel(event.getChannel()).setMessageFormat(// TODO: allow patrons to customise this message
        "Hello there, %s please do not use cursive language within this server.", messageToCheck.getAuthor().getAsMention()).setSuccessAction((m) -> m.delete().queueAfter(5, TimeUnit.SECONDS, null, new ErrorHandler().ignore(UNKNOWN_MESSAGE, MISSING_PERMISSIONS))).build());
        modLog(String.format("Message with score %.2f by %#s deleted in %s for profanity, message content was:```\n%s```", score, messageToCheck.getAuthor(), event.getChannel().getAsMention(), // Just to be safe
        StringUtils.abbreviate(display, Message.MAX_CONTENT_LENGTH - 150)), guild);
        return true;
    }
    return false;
}
Also used : ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) GuildSetting(com.dunctebot.models.settings.GuildSetting)

Aggregations

ErrorHandler (net.dv8tion.jda.api.exceptions.ErrorHandler)20 ErrorResponse (net.dv8tion.jda.api.requests.ErrorResponse)8 Instant (java.time.Instant)6 MessageConfig (me.duncte123.botcommons.messaging.MessageConfig)6 net.dv8tion.jda.api.entities (net.dv8tion.jda.api.entities)6 List (java.util.List)5 TimeUnit (java.util.concurrent.TimeUnit)5 Collectors (java.util.stream.Collectors)5 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)5 JDA (net.dv8tion.jda.api.JDA)5 Message (net.dv8tion.jda.api.entities.Message)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)5 NotNull (org.jetbrains.annotations.NotNull)5 GuildSetting (com.dunctebot.models.settings.GuildSetting)4 Matcher (java.util.regex.Matcher)4 Pattern (java.util.regex.Pattern)4 User (net.dv8tion.jda.api.entities.User)4 ListenerAdapter (net.dv8tion.jda.api.hooks.ListenerAdapter)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4