Search code examples
javaminecraftbukkit

How do I turn off the chat for a specific player?


I am making a plugin where people can toggle the chat for themselves on the server.

What I have right now works pretty well:

@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerChat(@NotNull AsyncPlayerChatEvent e) {
    if(TOGGLED_USERS_BY_UUID.contains(e.getPlayer().getUniqueId().toString())) {
        e.setCancelled(true);
        e.getPlayer().sendRawMessage(ToggleChat.LANG.get("cannotChat"));
        return;
    }
    String message = e.getMessage();
    getLogger().info(String.format("<%s>: %s", e.getPlayer().getName(), message));
    e.setCancelled(true);
    for(Player p : getServer().getOnlinePlayers()) {
        if(!TOGGLED_USERS_BY_UUID.contains(p.getUniqueId().toString()))
            p.sendRawMessage(String.format("<%s> %s", e.getPlayer().getName(), message));
    }
}

But the problem comes when users have other things for their chat, such as a specific level for their chat message like (lvl) [username] - message or something.

How do I make it so that I don't have to re-send the message to users or just cancel the event for a specific user?

Thanks!


Solution

  • @EventHandler
    public void onPlayerChat(AsyncPlayerChatEvent event) {
        event.getRecipients().remove(/*player who shouldn't see chat*/);
    }
    

    If you want to filter players by their xp levels, you can use

    getRecipients().removeIf(p -> p.getLevel() < minimumLevel)