Search code examples
javadiscord-jda

How to cast User to Member during making Discord Bot with JDA? (Java)


I have a problem with creating a Member variable during making Discord Bot with JDA. I wanted to create a Member variable with a concrete User ID but I bump into a problem that not all users of my Discord server are visible for bot.

Here's the code that shows only 1 user instead of 3. (prints only bot name)

jda.getUsers().stream()
            .map(User::getName)
            .forEach(System.out::println);

Here's the code that causes an error.

Member member = event.getGuild().getMemberById("*************");
System.out.println(member.getNickname());

For example, this code works correctly (prints neccessary username)

User user = event.getJDA().retrieveUserById("*************").complete();
System.out.println(user.getName)

Here's the error shown by IDE

(I need Member variable to change userName using .modifyNickname that available only for Member variable)

Have you got any ideas to create a Member variable using userID? Or maybe I can somehow cast User to Member? Thanks for your help.


Solution

  • Take a look at GatewayIntent. Currently, the members aren't cashed. Depending on your use case it may be sufficient to simply retrieve the member similar to what you did with the user.

    event.getGuild().retrieveMemberById(id).queue()
    

    Please note that using .complete() is not recommended. Stick to .queue() since it's asynchronous and won't block your thread.