Search code examples
javaminecraftbukkit

Minecraft Chat Message Replacement


I am making a permissions plugin, and want to replace the name of a player with their rank tag. For this, I have the following code:

public void playerChat(AsyncPlayerChatEvent e) {
    Player target = e.getPlayer();

    String message = e.getMessage().replaceAll(target.getName(), colorize(rFile.getString("players." + target)) + " " + target.getName());
    e.setMessage(message);
}

Whenever I send a message to chat, it appears like it would normally. What am I doing wrong here?

Additionally, I am using a config file (cFile) and a ranks.yml file (rFile).


Solution

  • First off, make sure you include the @EventHandler annotation.

    @EventHandler
    public void playerChat(AsyncPlayerChatEvent e) {
       [...]
    }
    

    Next, check if the listener is registered in your onEnable()method. getServer().getPluginManager().registerEvents(new YourListener(...), this);

    (Replace the YourListener with this in case it's your main class)

    Finally, as Luftbaum said, use AsyncPlayerChatEvent#setFormat within the event. Example Usage:

     e.setFormat(colorize(rFile.getString("players." + target)) + ": " + e.getMessage());
    

    Edit:

    In order to translate color codes such as '&3' to Bukkit's ChatColor format, you can use the ChatColor#translateAlternativeColorCodes method.

    ChatColor.translateAlternateColorCodes('&', stringThatContainsCodes);