JAVA Discord 机器人 (java.lang.ArrayIndexOutOfBoundsException)

JAVA Discord Bot (java.lang.ArrayIndexOutOfBoundsException)

我有一个奇怪的问题。由于我是编码新手,也许我很笨,我不知道如何解决这个问题,所以问题是,我的 discord 机器人有 2 个命令,永久静音和临时静音。我想在 config.yml 中使用占位符之类的东西,因为它更易于配置,但是当我使用 args[] 时,我遇到了一个奇怪的问题,就是这样:

    [JDA MainWS-ReadThread] ERROR net.dv8tion.jda.api.JDA - One of the EventListeners had an uncaught exception
java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
        at me.trashlord.bot.events.TempMuteCommand.onGuildMessageReceived(TempMuteCommand.java:34)
        at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:396)
        at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
        at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:82)
        at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:69)
        at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:166)
        at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:97)
        at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
        at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:921)
        at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:808)
        at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:786)
        at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:959)
        at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
        at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
        at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
        at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
        at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
        at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
        at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)

此外,这是我在这些行的代码:

        String[] args = event.getMessage().getContentRaw().split("\s+");

        String MutedMessage = ConfigManager.INSTANCE.getSetting("MutedMessage")
                .replaceAll("%muteduser", args[1]);

        String UnMutedMessage = ConfigManager.INSTANCE.getSetting("UnMutedMessage")
                .replaceAll("%unmuteduser", args[1]);

        String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
                .replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""))))
                .replaceAll("%tempmutetime", args[2]);

        if (args[0].equalsIgnoreCase(Commands.prefix + "mute")) {
            if (Objects.requireNonNull(event.getMember()).hasPermission(Permission.MESSAGE_MANAGE)) {
                if (args.length == 2) {
                    Member member = event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""));
                    Role role = event.getGuild().getRoleById(MutedRole);

                    if (!Objects.requireNonNull(member).getRoles().contains(role)) {
                        // Mute user
                        event.getChannel().sendMessage(MutedMessage).queue();
                        event.getGuild().addRoleToMember(member, Objects.requireNonNull(role)).complete();
                    } else {
                        // Unmute user
                        event.getChannel().sendMessage(UnMutedMessage).queue();
                        event.getGuild().removeRoleFromMember(member, Objects.requireNonNull(role)).complete();
                    }
                } else if (args.length == 3) {
                    Member member = event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""));
                    Role role = event.getGuild().getRoleById(MutedRole);

                    //event.getChannel().sendMessage(TempMuted1 + " " + args[1] + " " + TempMuted2 + " " + args[2] + " " + TempMuted3).queue();
                    event.getChannel().sendMessage(TempMuted1).queue();
                    event.getGuild().addRoleToMember(Objects.requireNonNull(member), Objects.requireNonNull(role))
                            .complete();

                    // Unmute after a few seconds
                    new java.util.Timer().schedule(
                            new java.util.TimerTask() {
                                @Override
                                public void run() {
                                    event.getChannel().sendMessage(TempUnMuted + " " + args[1] + ".").queue();
                                    event.getGuild().removeRoleFromMember(member, role).complete();
                                }
                            },
                            TimeUnit.MINUTES.toMillis(Integer.parseInt(args[2]))
                    );
                } else {
                    event.getChannel().sendMessage("Incorrect syntax. Use `~mute [user mention] [time {optional}]`")
                            .queue();
                }
            }
        }
    }
}

您确定您的代码中的这一行:

String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
            .replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""))))
            .replaceAll("%tempmutetime", args[2]);

args[1] 和 args[2] 是否正确?

如果长度为 2,则 args[2] 正在寻找第 3 个值,而您可能没有... 进一步了解数组的长度和索引是如何工作的。

问题是您正试图从 args[2] 中获取一个元素,这可能在以下代码中该数组仅包含 2 个元素(长度为 2):

String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
        .replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""))))
        .replaceAll("%tempmutetime", args[2]);

请注意,在 java 中,数组是 zero-based 并且索引从 0 开始到长度 - 1。 您可以在 if-condition:

中获取此代码
else if (args.length == 3) {
     String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
            .replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\d]+", ""))))
            .replaceAll("%tempmutetime", args[2]);
// your code
}