javadiscorddiscord4j

Get all messages from a channel, discord-api


(discord4j 3.1.0) So i want to get all the messages from a (Guild)MessageChannel, but as far as i know there is no straight forward way of doing it (what i mean by that there is no channel.getMessages().block() or something). What i've been using as a substitue for a while now, is a method which gets the last message of the channel, and then gets all messages before that.

public static List<Message> getMessagesOfChannel(MessageChannel channel){
        try {
            //get the last message
            Message tempMessage = channel.getLastMessage().block();
            //get all messages before the last message and then add the last message to it
            List<Message> messages = channel.getMessagesBefore(tempMessage.getId()).collectList().block();

            return messages;
        }catch(ClientException | NullPointerException e){
            //if there was no last message then the channel is empty so return an empty list
            return new ArrayList<>();
        }

    }

And it worked good until today... Because there is a problem when you call this method inside of a MessageDeleteEvent. If the said deleted method is the last method of a channel. Because eventhough the message was deleted channel.getLastMessage() as well as channel.getLastMessageId() both refer to the deleted method. (the first method throws an exception in that case and the second is useless because eventhough it returns the messageId all methods trying to get the actual message would be throwing an exception as well). I have tried creating my own message in the channel, then calling channel.getMessagesBefore(message) but the getMessagesOfChannel() method gets called too often in my program so it completely fills my notifications in discord :(. So is there any clever (or not) way to either get all messages of a channel somehow else, or can you update the lastMessage stored in the channel during the MessageDeleteEvent?


Solution

  • You can use Snowflake.of(Instant.now()) to get all messages:

    public static List<Message> getMessagesOfChannel(MessageChannel channel){
        Snowflake now = Snowflake.of(Instant.now());
        return channel.getMessagesBefore(now).collectList().block();
    }