Question AsyncChatEvent Replace Content

ArturM

New member
Feb 15, 2023
1
0
1
Hey, I need to change a message piece, and I don't know how. I've already tried and it doesn't work either:
Java:
@EventHandler
    public void onRun(AsyncChatEvent e) {
        PlayerData playerData = this.pureSkyWars.mysql.getPlayerCoins(e.getPlayer());
        Component component = e.message().replaceText(TextReplacementConfig.builder()
                .replacement(String.valueOf(playerData.getLevel())).match("#level_" + e.getPlayer().getName()).build());
        e.message(component);


    }
 

Josh

New member
Feb 21, 2023
4
0
1
It looks like you're trying to replace a piece of text in the chat message with the player's level, using the replaceText method from the Component class. However, it's not clear from your code snippet what exactly is not working.

One issue with your code is that you're using the AsyncChatEvent event, which is fired before the chat message is sent to other players. This means that modifying the chat message in this event will only affect what the original player sees, not what other players see.

To modify the chat message that is sent to all players, you should use the AsyncPlayerChatEvent event instead, like this:

Java:
@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
    PlayerData playerData = this.pureSkyWars.mysql.getPlayerCoins(e.getPlayer());
    Component component = e.getMessage().replaceText(TextReplacementConfig.builder()
            .replacement(String.valueOf(playerData.getLevel())).match("#level_" + e.getPlayer().getName()).build());
    e.setMessage(component);
}

This code should replace all instances of the text #level_<player name> in the chat message with the player's level, using the replaceText method.

Hopefully this works!