Okaam
Okaam

Reputation: 11

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

So I am experiencing things with the discord JDA api. I tried to get my bot's servers but it doesn't work at all.

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

But in fact it doesn't show anything but 0, meaning the getGuilds() method's list is empty.

Any help would be appreciated, and thanks for any answer

Upvotes: 1

Views: 1805

Answers (2)

A. Smith
A. Smith

Reputation: 487

While the accepted answer might work, I think the proper way to do this is to add an onReady override in an event listener.

Create an event listener class Example.java

public class Example extends ListenerAdapter {
 @Override
 public void onReady(ReadyEvent event) {
  for(Guild g : jda.getGuilds()) {
        System.out.println(g.getName());
  }
 }
}

After you've created your listener class, added it to your jdabuilder

JDABuilder jdab = JDABuilder.create("token",GatewayIntent.DIRECT_MESSAGES)
                            .addEventListener(new Example());

You'll want to keep your main class clean of any business logic, most of your work will be done in event listeners, so getting into the habit of that will help later.

Upvotes: 0

Minn
Minn

Reputation: 6131

The documentation for JDABuilder#build states:

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.

So all you gotta do is call awaitReady() to block the main thread until JDA is ready. Only then can you reliably access the JDA cache.

Upvotes: 2

Related Questions