javadiscorddiscord4j

How to reply to a discord message using discord4j?


I'm trying to implement a discord bot using discord4j library. For the moment I managed to make the bot respond to some simple commands like ping or making it say things.

I'm trying to look at all the tutorials I found but none of them show how to actually reply to a message.

This is an example of the code I use to make the bot send messages with a POST call:

@PostMapping("/say")
public @ResponseBody String say(
    @RequestParam("message") String message,
    @RequestParam("channelId") String channelID,
    @RequestParam("replyMessageId") String replyMessageId
) { 
    Message messageToReply = client.getMessageById(Snowflake.of(channelID), Snowflake.of(replyMessageId)).block();
        
    client.getChannelById(Snowflake.of(channelID)).ofType(MessageChannel.class)
    .flatMap(channel -> channel.createMessage(message)).subscribe();
        
    return "OK";
}

I want to use the message I retrieved (messageToReply) so the message I create replies to it.

I tried looking at the documentation and to all the functions you can call after createMessage but I haven't found anything.


Solution

  • By adding .withMessageReference(...), you can specify the Id of a message to reply to, you don't need to get the message:

    channel.createMessage(message).withMessageReference(Snowflake.of(replyMessageId))