Search code examples
javadiscorddiscord-jda

How to send a DM (Direct Message) to someone on Discord via JDA


I want the bot to send a direct message to someone, but I don't know how to do so.

event.getChannel().sendMessage("Hello World").queue();

I wonder if I can change the channel to a DM or send a DM in any other way, I want it sent directly to the user or that only him can see it.


Solution

  • You never have to guess at how to use a library - that's what documentation is for. Any library worth its salt has documentation listing every single class, method, and property you need to worry about.

    A quick google search for "discord-jda docs" takes us to the javadoc: https://ci.dv8tion.net/job/JDA/javadoc/index.html

    You want to send a message to a user, right? So let's use the search bar and find User. First result under Types is net.dv8tion.jda.api.entities.User. We're now at https://ci.dv8tion.net/job/JDA/javadoc/net/dv8tion/jda/api/entities/User.html

    If you want to know how to do something with a user, we look at the Methods every User has. Two catch my eye right away: User.hasPrivateChannel() and User.openPrivateChannel(). We'll click the second one since it looks relevant.

    Lo and behold, the docs have example usage! I'll quote it below:

    // Send message without response handling
    public void sendMessage(User user, String content) {
        user.openPrivateChannel()
            .flatMap(channel -> channel.sendMessage(content))
            .queue();
    }
    

    This seems pretty straightforward. So the basic usage you're looking for (assuming event is a MessageReceivedEvent) is this:

    event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessage("hello")).queue();