javadiscord4j

Discord4J issue: sending messages in a loop instead


Below is the code I used for a test command in Discord4J

gateway.on(MessageCreateEvent.class)
            .map(MessageCreateEvent::getMessage)
            .filter(message -> message.getContent().contains("test"))
            .flatMap(Message::getChannel)
            .flatMap(channel -> channel.createMessage("test!"))
            .subscribe();

but now if you type "test" in discord, it keeps sending messages, instead of a single message like I would expect. What's the issue here? It does work with equals() and equalsignorecase(), but with all other String checking methods it goes into a loop.


Solution

  • This is because you receive a MessageCreateEvent for all messages you send with the bot as well. Since your message is createMessage("test!"), you will also receive a message where getContent() returns "test!". This will obviously result in "test!".contains("test") but not "test!".equals("test").

    This can be prevented by checking if the message author is a bot.

    filter(message -> !message.getAuthor().map(User::isBot).orElse(true))