How to send a private message to a user by user id

59 Views Asked by At

I was trying to code a bot that dms people, but I wasn't able to find user by their id.

package me.rtx4090;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.events.guild.GuildReadyEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.entities.User;

public class Main extends ListenerAdapter {
    private JDA jda;

    public Main() {
        String botToken = "(censored)";
        jda = JDABuilder.createDefault(botToken).addEventListeners(this).build();
    }

    public static void main(String[] args) {
        new Main();
    }

    @Override
    public void onGuildReady(GuildReadyEvent event) {
        System.out.println("All members in the guild " + event.getGuild().getName() + " have been downloaded.");

        sendPrivateMessage();
    }

    private void sendPrivateMessage() {
        String recipientUserId = "(censored)"; 
        String messageContent = "L";

        User recipient = jda.getUserById(recipientUserId);
        System.out.println(recipient);

        if (recipient != null) {
            recipient.openPrivateChannel().queue(privateChannel -> {
                privateChannel.sendMessage(messageContent).queue();
                System.out.println("Message has been sent to " + recipient.getAsTag() + " successfully");
            });
        } else {
            System.out.println("Can't find the user. Please make sure you've used the correct ID");
        }
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

You can use openPrivateChannelById:

jda.openPrivateChannelById(recipientUserId).queue(channel -> {
  User user = channel.getUser();
  channel.sendMessage(messageContent).queue();
  System.out.printf("Message has been sent to %#s successfully\n", user);
});