Replace a word in a chat message

I’m trying to learn how to make sponge plugins, so I’m starting with something simple.
I want to replace a word in a players chat, if it appears, to something else.
Even something this simple is boggling my mind. I think I might have something going, but I’m not sure. Could I see an example so I can compare it to mine?

I haven’t exactly tested this in-game but something like this should work

@Listener public void onChat(MessageChannelEvent.Chat event) { Optional<Player> optionalPlayer = event.getCause().first(Player.class); if (optionalPlayer.isPresent()) { String originalMessage = event.getRawMessage().toPlain(); String newMessage = originalMessage.replace("someword", "anotherword"); event.setMessage(Text.of(newMessage)); } }

That works, but it becomes more complicated if you want to deal with messages set by plugins.

If no other plugin is modifying the player’s message, then what you’d doing is reasonably safe. However, there’s a major downside - you’ll lose Vanilla’s default formatting such as the <username> prefix before any chat message. If a plugin modifies the chat message in some way, such as adding formatting, things becom even more complicated.

This will become much simpler once some form of text templates are added. @Minecrell can tell you more about that.

Essentially what I want to do is replace [item] in the players message to a hover link to the item in the players hand. I see how the example he gave works if you wanted to replace just a simple word with no formatting, but what if I wanted the hover link? I understand (I think…) how to get the player, and their item in their hand to make a Text with the hover effect with the item, just not sure how to replace the word “[item]” with that.