JDA#getGuilds() 方法返回一个空列表

The JDA#getGuilds() method is returning an empty list

所以我遇到了不和谐的 JDA api。我试图获取我的机器人的服务器,但它根本不起作用。

public static void main(String[] args) {
        JDABuilder jdab = JDABuilder.create("token",GatewayIntent.DIRECT_MESSAGES);
        JDA jda = null;
        try { jda = jdab.build();
        } catch (LoginException e) { e.printStackTrace(); }
        assert jda != null;
        System.out.println(jda.getGuilds().size());
        for(Guild g : jda.getGuilds()) {
            System.out.println(g.getName());
        }
   }

但实际上它只显示 0,这意味着 getGuilds() 方法的列表是空的。

如有任何帮助,我们将不胜感激,感谢您的回答

JDABuilder#build 的文档指出:

The login process runs in a different thread, so while this will return immediately, JDA has not finished loading, thus many JDA methods have the chance to return incorrect information. For example JDA.getGuilds() might return an empty list or JDA.getUserById(long) might return null for arbitrary user IDs.

If you wish to be sure that the JDA information is correct, please use JDA.awaitReady() or register an EventListener to listen for the ReadyEvent.

所以您要做的就是调用 awaitReady() 阻塞主线程,直到 JDA 准备就绪。只有这样,您才能可靠地访问 JDA 缓存。