Discord机器人无法验证用户是否不存在,抛出了IndexOutOfBounds错误。

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

Discord bot cannot verify if the user is not existing, throws an indexoutofbounds error

问题

我正在创建一个 Discord 机器人我已经成功地调用了用户输入的名称但是如果用户在服务器中不存在我无法抛出错误消息并且一直给我 IndexOutOfBoundsError

String[] message = e.getMessage().getContentRaw().split(" ");
if (message.length == 1 && message[0].equalsIgnoreCase("!user")) {
    e.getChannel().sendMessage("要获取用户信息,请输入 !user [name]").queue();
} else if (message.length == 2 && message[0].equalsIgnoreCase("!user")) {
    String username = message[1];
    User user = e.getGuild().getMembersByName(username, true).get(0).getUser();
    EmbedBuilder avatarEmbed = new EmbedBuilder();
    String avatar = user.getAvatarUrl();

    avatarEmbed.setTitle(user.getName() + "的信息:");
    avatarEmbed.addField("名称", user.getName(), true);
    avatarEmbed.addField("在线状态:", e.getGuild().getMembersByName(username,
            true).get(0).getOnlineStatus().toString(), true);

    if (!user.getName().equalsIgnoreCase(username)) {
        e.getChannel().sendMessage("用户不存在!").queue();
    }
}

这是验证用户不存在的代码部分,但是它给了我一个 IndexOutOfBoundError。可能的原因是什么呢?如果需要更多的代码,请留言回复,但我认为这部分足够了,其他代码只是添加了字段和设计等内容。

[JDA MainWS-ReadThread] ERROR JDA - 其中一个 EventListener 发生了未捕获的异常
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
    at java.base/java.util.LinkedList.get(LinkedList.java:480)
    at java.base/java.util.Collections$UnmodifiableList.get(Collections.java:1310)
    at UserInfoCommand.onGuildMessageReceived(UserInfoCommand.java:25)
    at net.dv8tion.jda.core.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:373)
    at net.dv8tion.jda.core.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:84)
    at net.dv8tion.jda.core.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:90)
    at net.dv8tion.jda.core.handle.SocketHandler.handle(SocketHandler.java:37)
    at net.dv8tion.jda.core.requests.WebSocketClient.handleEvent(WebSocketClient.java:1040)
    at net.dv8tion.jda.core.requests.WebSocketClient.onTextMessage(WebSocketClient.java:680)

这是错误代码。谢谢!


<details>
<summary>英文:</summary>

I&#39;m creating a discord bot, I&#39;ve managed to call the names of the user input, however, if the user is not existing in the server, I couldn&#39;t throw an error message and keeps giving me IndexOutOfBoundsError.

   

     String[] message = e.getMessage().getContentRaw().split(&quot; &quot;);
                if(message.length == 1 &amp;&amp; message[0].equalsIgnoreCase(&quot;!user&quot;)){
                    e.getChannel().sendMessage(&quot;To get a user&#39;s info, type !user [name]&quot;).queue();
                }
                else if(message.length == 2 &amp;&amp; message[0].equalsIgnoreCase(&quot;!user&quot;)){
        
                   String username = message[1];
                   User user = e.getGuild().getMembersByName(username, true).get(0).getUser();
                   EmbedBuilder avatarEmbed = new EmbedBuilder();
                   String avatar = user.getAvatarUrl();
        
                   avatarEmbed.setTitle(user.getName() + &quot;&#39;s Info:&quot;);
                   avatarEmbed.addField(&quot;Name&quot;, user.getName(), true);
                   avatarEmbed.addField(&quot;Online Status: &quot;, e.getGuild().getMembersByName(username,
                   true).get(0).getOnlineStatus().toString(), true);
    
    
For example, if I input !user Mark then the bot will show the information of the user if the user is existing in the server.


    if(!user.getName().equalsIgnoreCase(username)){
                       e.getChannel().sendMessage(&quot;User doesn&#39;t exist!&quot;).queue();
                   }


And this is the code for verifying if the user is not existing, the bot would message but it gives me an IndexOutOfBoundError. What could be the reason? Please leave an answer if you need more codes but I believe this would be enough, other codes are just adding fields and design, etc.

        [JDA MainWS-ReadThread] ERROR JDA - One of the EventListeners had an uncaught exception
    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    	at java.base/java.util.LinkedList.checkElementIndex(LinkedList.java:559)
    	at java.base/java.util.LinkedList.get(LinkedList.java:480)
    	at java.base/java.util.Collections$UnmodifiableList.get(Collections.java:1310)
    	at UserInfoCommand.onGuildMessageReceived(UserInfoCommand.java:25)
    	at net.dv8tion.jda.core.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:373)
    	at net.dv8tion.jda.core.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:84)
    	at net.dv8tion.jda.core.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:90)
    	at net.dv8tion.jda.core.handle.SocketHandler.handle(SocketHandler.java:37)
    	at net.dv8tion.jda.core.requests.WebSocketClient.handleEvent(WebSocketClient.java:1040)
    	at net.dv8tion.jda.core.requests.WebSocketClient.onTextMessage(WebSocketClient.java:680)

This is the error code. Thank you!

</details>


# 答案1
**得分**: 0

问题出在 ``User user = e.getGuild().getMembersByName(username, true).get(0).getUser();``

你看,你正在调用一个成员的数组列表,使用 ``getMembersByName("name", ignoreCase);`` 方法。但是因为找不到任何成员,那个数组列表将会是空的。

尝试一下这段代码:

```java
        String[] message = e.getMessage().getContentRaw().split(" ");
        if(message.length == 1 && message[0].equalsIgnoreCase("!user")){
            e.getChannel().sendMessage("要获取用户信息,请输入 !user [name]").queue();
        }
        else if(message.length == 2 && message[0].equalsIgnoreCase("!user")){

            String username = message[1];
            ArrayList<Member> memberList = e.getGuild().getMembersByName(username, true);

            if (memberList.size()>0) {
                User user = memberList.get(0);
                EmbedBuilder avatarEmbed = new EmbedBuilder();
                String avatar = user.getAvatarUrl();

                avatarEmbed.setTitle(user.getName() + "'s 信息:");
                avatarEmbed.addField("名称", user.getName(), true);
                avatarEmbed.addField("在线状态: ", memberList.get(0).getOnlineStatus().toString(), true);
            } else {
                e.getChannel().sendMessage("用户不存在!").queue();
            }
        }

这将检查是否有满足参数的成员在服务器中。如果没有(没有名字匹配的成员),就会发送错误消息!

英文:

The problem lies within the User user = e.getGuild().getMembersByName(username, true).get(0).getUser();

See, you're calling a arraylist of members with the getMembersByName(&quot;name&quot;, ignoreCase); method. But because no members can be found, that arraylist will be given 0 members.

Try this code for a change:

        String[] message = e.getMessage().getContentRaw().split(&quot; &quot;);
        if(message.length == 1 &amp;&amp; message[0].equalsIgnoreCase(&quot;!user&quot;)){
            e.getChannel().sendMessage(&quot;To get a user&#39;s info, type !user [name]&quot;).queue();
        }
        else if(message.length == 2 &amp;&amp; message[0].equalsIgnoreCase(&quot;!user&quot;)){

            String username = message[1];
            ArrayList&lt;Member&gt; memberList = e.getGuild().getMembersByName(username, true);

            if (memberList.size()&gt;0) {
                User user = memberList.get(0);
                EmbedBuilder avatarEmbed = new EmbedBuilder();
                String avatar = user.getAvatarUrl();

                avatarEmbed.setTitle(user.getName() + &quot;&#39;s Info:&quot;);
                avatarEmbed.addField(&quot;Name&quot;, user.getName(), true);
                avatarEmbed.addField(&quot;Online Status: &quot;, memberList.get(0).getOnlineStatus().toString(), true);
            } else {
                e.getChannel().sendMessage(&quot;User doesn&#39;t exist!&quot;).queue();
            }
        }

This checks if there are members in the guild that suffice the argument. If it doesn't (No members with the name) it will go to the error message!

huangapple
  • 本文由 发表于 2020年10月8日 20:22:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64262435.html
匿名

发表评论

匿名网友

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

确定