Search in sources :

Example 11 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project mc-discord-bridge by Selicre.

the class DiscordBotImpl method updateChannels.

private void updateChannels() {
    nextTopicUpdateTime = Instant.now().plus(TIME_BETWEEN_TOPIC_UPDATES);
    topicNeedsUpdating = false;
    TextChannel chatChannel = discord.getTextChannelById(config.channelId);
    if (chatChannel != null && config.updateTopic) {
        String topic = config.getTopicName(getPlayerNames());
        chatChannel.getManager().setTopic(topic).queue(null, new ErrorHandler().handle(ErrorResponse.MISSING_PERMISSIONS, c -> {
            LogManager.getLogger().warn("Missing permissions to change channel info!");
            // Don't try again
            config.updateTopic = false;
        }));
    }
    GuildChannel renameChannel = discord.getGuildChannelById(config.renameChannelId);
    int playerCount = server.getCurrentPlayerCount();
    if (renameChannel != null) {
        renameChannel.getManager().setName(config.getRenameChannelName(playerCount)).queue();
    }
}
Also used : LoginException(javax.security.auth.login.LoginException) LiteralText(net.minecraft.text.LiteralText) GameProfile(com.mojang.authlib.GameProfile) Timer(java.util.Timer) Member(net.dv8tion.jda.api.entities.Member) TextChannel(net.dv8tion.jda.api.entities.TextChannel) HoverEvent(net.minecraft.text.HoverEvent) GatewayIntent(net.dv8tion.jda.api.requests.GatewayIntent) MinecraftServer(net.minecraft.server.MinecraftServer) Style(net.minecraft.text.Style) Guild(net.dv8tion.jda.api.entities.Guild) GameMessageConverter.convertGameMessage(selic.re.discordbridge.GameMessageConverter.convertGameMessage) Duration(java.time.Duration) TimerTask(java.util.TimerTask) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Message(net.dv8tion.jda.api.entities.Message) PlayerEntity(net.minecraft.entity.player.PlayerEntity) UserUpdateActivitiesEvent(net.dv8tion.jda.api.events.user.update.UserUpdateActivitiesEvent) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel) Activity(net.dv8tion.jda.api.entities.Activity) Set(java.util.Set) GenericGuildMemberEvent(net.dv8tion.jda.api.events.guild.member.GenericGuildMemberEvent) UUID(java.util.UUID) Instant(java.time.Instant) List(java.util.List) DiscordFormattingConverter.discordChannelToMinecraft(selic.re.discordbridge.DiscordFormattingConverter.discordChannelToMinecraft) ServerPlayerEntity(net.minecraft.server.network.ServerPlayerEntity) Logger(org.apache.logging.log4j.Logger) GuildVoiceUpdateEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent) Optional(java.util.Optional) Text(net.minecraft.text.Text) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) NotNull(org.jetbrains.annotations.NotNull) WebhookClientBuilder(club.minnced.discord.webhook.WebhookClientBuilder) GuildVoiceStreamEvent(net.dv8tion.jda.api.events.guild.voice.GuildVoiceStreamEvent) JDA(net.dv8tion.jda.api.JDA) WebhookClient(club.minnced.discord.webhook.WebhookClient) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) MessageType(net.minecraft.network.MessageType) PlayerListS2CPacket(net.minecraft.network.packet.s2c.play.PlayerListS2CPacket) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) DiscordFormattingConverter.discordUserToMinecraft(selic.re.discordbridge.DiscordFormattingConverter.discordUserToMinecraft) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) JDABuilder(net.dv8tion.jda.api.JDABuilder) GuildVoiceState(net.dv8tion.jda.api.entities.GuildVoiceState) ClickEvent(net.minecraft.text.ClickEvent) MutableText(net.minecraft.text.MutableText) TemporalAmount(java.time.temporal.TemporalAmount) DiscordFormattingConverter.discordMessageToMinecraft(selic.re.discordbridge.DiscordFormattingConverter.discordMessageToMinecraft) WhitelistEntry(net.minecraft.server.WhitelistEntry) Nonnull(javax.annotation.Nonnull) GenericRoleUpdateEvent(net.dv8tion.jda.api.events.role.update.GenericRoleUpdateEvent) Nullable(javax.annotation.Nullable) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) DiscordFormattingConverter.minecraftToDiscord(selic.re.discordbridge.DiscordFormattingConverter.minecraftToDiscord) DecimalFormat(java.text.DecimalFormat) ListenerAdapter(net.dv8tion.jda.api.hooks.ListenerAdapter) IOException(java.io.IOException) LogManager(org.apache.logging.log4j.LogManager) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) TextChannel(net.dv8tion.jda.api.entities.TextChannel) GuildChannel(net.dv8tion.jda.api.entities.GuildChannel)

Example 12 with ErrorHandler

use of net.dv8tion.jda.api.exceptions.ErrorHandler in project Wylx by Wylx-Bot.

the class Helper method selfDestructingMsg.

/**
 * Create a self-destructing message which deletes itself after timeout
 * @param msg Message to send
 * @param timeout Time until message is deleted
 */
public static void selfDestructingMsg(MessageAction msg, Duration timeout) {
    msg.queue(message -> {
        var errorHandler = new ErrorHandler().ignore(ErrorResponse.UNKNOWN_MESSAGE);
        message.delete().queueAfter(timeout.toSeconds(), TimeUnit.SECONDS, null, errorHandler);
    });
}
Also used : ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler)

Example 13 with ErrorHandler

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

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 14 with ErrorHandler

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

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 15 with ErrorHandler

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

the class MessageListener method checkMessageForInvites.

// / <editor-fold desc="auto moderation" defaultstate="collapsed">
private void checkMessageForInvites(Guild guild, GuildMessageReceivedEvent event, GuildSetting settings, String raw) {
    if (settings.isFilterInvites() && guild.getSelfMember().hasPermission(Permission.MANAGE_SERVER)) {
        final Matcher matcher = Message.INVITE_PATTERN.matcher(raw);
        if (matcher.find()) {
            // Get the invite Id from the message
            final String inviteID = matcher.group(matcher.groupCount());
            // Prohibiting failure because the bot is currently banned from the other guild.
            guild.retrieveInvites().queue((invites) -> {
                // Check if the invite is for this guild, if it is not delete the message
                if (invites.stream().noneMatch((invite) -> invite.getCode().equals(inviteID))) {
                    event.getMessage().delete().reason("Contained unauthorized invite.").queue((it) -> sendMsg(MessageConfig.Builder.fromEvent(event).setMessage(event.getAuthor().getAsMention() + ", please don't post invite links here.").setSuccessAction(m -> m.delete().queueAfter(4, TimeUnit.SECONDS)).build()), new ErrorHandler().ignore(UNKNOWN_MESSAGE, MISSING_PERMISSIONS));
                }
            });
        }
    }
}
Also used : MessageData(ml.duncte123.skybot.objects.discord.MessageData) MessageBulkDeleteEvent(net.dv8tion.jda.api.events.message.MessageBulkDeleteEvent) EmbedUtils(me.duncte123.botcommons.messaging.EmbedUtils) StringUtils(me.duncte123.botcommons.StringUtils) Permission(net.dv8tion.jda.api.Permission) CommandCategory(ml.duncte123.skybot.objects.command.CommandCategory) PerspectiveApi(ml.duncte123.skybot.utils.PerspectiveApi) UNKNOWN_MESSAGE(net.dv8tion.jda.api.requests.ErrorResponse.UNKNOWN_MESSAGE) SpamFilter(ml.duncte123.skybot.utils.SpamFilter) Matcher(java.util.regex.Matcher) GuildSettingsUtils(ml.duncte123.skybot.utils.GuildSettingsUtils) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) GuildSetting(com.dunctebot.models.settings.GuildSetting) GuildMessageUpdateEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent) Variables(ml.duncte123.skybot.Variables) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) UnknownUser(ml.duncte123.skybot.objects.user.UnknownUser) Pattern(java.util.regex.Pattern) MISSING_PERMISSIONS(net.dv8tion.jda.api.requests.ErrorResponse.MISSING_PERMISSIONS) ICommand(ml.duncte123.skybot.objects.command.ICommand) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) BotCommons(me.duncte123.botcommons.BotCommons) java.util(java.util) JDA(net.dv8tion.jda.api.JDA) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) CustomCommand(ml.duncte123.skybot.objects.command.custom.CustomCommand) GuildMessageDeleteEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent) MessageUtils(me.duncte123.botcommons.messaging.MessageUtils) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Sentry(io.sentry.Sentry) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) GenericGuildMessageEvent(net.dv8tion.jda.api.events.message.guild.GenericGuildMessageEvent) CommandUtils.isGuildPatron(ml.duncte123.skybot.utils.CommandUtils.isGuildPatron) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) MessageUtils.sendMsg(me.duncte123.botcommons.messaging.MessageUtils.sendMsg) CommandContext(ml.duncte123.skybot.objects.command.CommandContext) CommandUtils.isDev(ml.duncte123.skybot.utils.CommandUtils.isDev) ModerationUtils.modLog(ml.duncte123.skybot.utils.ModerationUtils.modLog) CommandManager(ml.duncte123.skybot.CommandManager) DunctebotGuild(ml.duncte123.skybot.entities.jda.DunctebotGuild) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) AirUtils.setJDAContext(ml.duncte123.skybot.utils.AirUtils.setJDAContext) Triple(kotlin.Triple) Settings(ml.duncte123.skybot.Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MessageConfig(me.duncte123.botcommons.messaging.MessageConfig) RedisConnection(ml.duncte123.skybot.database.RedisConnection) DateTimeFormatter(java.time.format.DateTimeFormatter) ErrorHandler(net.dv8tion.jda.api.exceptions.ErrorHandler) Matcher(java.util.regex.Matcher)

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