JAVA Discord Bot (java.lang.ArrayIndexOutOfBoundsException)

huangapple go评论73阅读模式
英文:

JAVA Discord Bot (java.lang.ArrayIndexOutOfBoundsException)

问题

我有一个奇怪的问题。因为我刚开始编码,可能我太笨了,我不知道该如何解决这个问题,所以问题是,我有两个命令用于我的Discord机器人,分别是永久禁言和临时禁言。我想做一些类似于占位符的东西,以便在config.yml中使用,因为这样会更加灵活,但是当我使用args[]时,我遇到了一个奇怪的问题,下面是问题的描述:

[JDA MainWS-ReadThread] ERROR net.dv8tion.jda.api.JDA - 一个事件监听器发生了未捕获的异常

java.lang.ArrayIndexOutOfBoundsException: 长度为2的数组索引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();
            }
        }
    }
}

}

英文:

I have a weird problem. Since I'm new in coding, maybe I am dumb and I don't know how can I resolve this issue, so the issue is, I have 2 commands for my discord bot, permanent mute, and temporary mute. I want to make something like a placeholder to be used in config.yml since it will be more configurable, but when I use args[], I have a weird problem, here is it :

    [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)

ALSO, here is my code at those lines :

        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();
                }
            }
        }
    }
}

答案1

得分: 0

你确定代码中这一行没有问题吗:

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个值,而你可能没有它...
进一步了解数组的长度和索引如何工作可能会有帮助。

英文:

Are you sure that this line from your code:

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

args[1] and args[2] is correct?

If the length is 2, Then args[2] is looking for the 3rd value and you might not have it...
Have a further look on how length and index works for arrays.

答案2

得分: 0

问题在于你正试图从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中,数组是基于零的,索引从0开始到长度-1结束。
你可以将这段代码放在if条件语句内部:

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]);
// 你的代码
}
英文:

the problem is you are trying to get an element from args[2], which may the array only contains 2 elements (length 2) in the following code:

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

Note that in java arrays are zero-based and indexes start from 0 to length - 1.
You can take this code inside the 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
}

huangapple
  • 本文由 发表于 2020年9月14日 22:39:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63886511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定