Paper 聊天格式:AsyncChatEvent+ChatRenderer(每位觀看者各自渲染、提及高亮)、AsyncChatDecorateEvent 依權限開放玩家顏色標籤(不開放 click/hover)、viewers 做頻道與忽略名單、禁言取消事件、非同步聊天執行緒規則、簽章訊息與「已修改」標記 / Paper chat formatting: AsyncChatEvent + ChatRenderer (per-viewer rendering, mention highlights), AsyncChatDecorateEvent for permission-gated player color tags (never click / hover), viewers for channels and ignore lists, mutes by cancelling, async chat thread rules, signed messages and the modified indicator
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Paper Chat Renderer?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/mrpippi-paper-chat-renderer)
---
name: paper-chat-renderer
description: "Paper 聊天格式:AsyncChatEvent+ChatRenderer(每位觀看者各自渲染、提及高亮)、AsyncChatDecorateEvent 依權限開放玩家顏色標籤(不開放 click/hover)、viewers 做頻道與忽略名單、禁言取消事件、非同步聊天執行緒規則、簽章訊息與「已修改」標記 / Paper chat formatting: AsyncChatEvent + ChatRenderer (per-viewer rendering, mention highlights), AsyncChatDecorateEvent for permission-gated player color tags (never click / hover), viewers for channels and ignore lists, mutes by cancelling, async chat thread rules, signed messages and the modified indicator"
---
# Paper Chat Renderer
## Skill Name
`paper-chat-renderer`
## Purpose
Chat formatting on Paper goes through three stages, each with its own rules. Plugins that mix them up end up with lost formats, players running commands through `<click>` tags, or world access from the chat thread:
| Stage | Event / API | Use it for | Do not |
|------|------|------|------|
| 1. Decorate the typed text | `AsyncChatDecorateEvent#result(Component)` | Colors, emoji, links inside the message body | Add the player name or prefix here |
| 2. Choose who receives it | `AsyncChatEvent#viewers()` (mutable `Set<Audience>`) | Channels, ignore lists, local chat | Send the message yourself and cancel the event |
| 3. Render the line | `AsyncChatEvent#renderer(ChatRenderer)` | Name, prefix, channel tag, per-viewer highlights | Touch the world or block |
What the server does with the result (read from Paper's `ChatProcessor` and `ServerGamePacketListenerImpl`, 26.3 build 273):
| Behavior | Detail |
|------|------|
| Thread | Player chat runs on the `chatExecutor` pool (`event.isAsynchronous()` is true). `Player#chat(String)` called from the main thread fires the same event synchronously |
| Decorate first | `AsyncChatDecorateEvent` runs (also on the chat pool) before `AsyncChatEvent`; its result becomes `originalMessage()` and `message()` of the chat event |
| Legacy listeners | If any plugin listens to the deprecated `AsyncPlayerChatEvent`, it fires first and its format / message changes are converted into a renderer / message for `AsyncChatEvent` |
| Untouched `viewers()` | A lazy set: the server broadcasts to everyone online plus the console. Reading or editing it builds the real set (all players + console) |
| Renderer calls | A viewer-aware `ChatRenderer` is called once **per viewer**, console included (the console is an `Audience`, not a `Player`). `ChatRenderer.viewerUnaware(...)` is called once |
| Chat type | The default renderer uses the vanilla `chat` type (client draws `<name> message`); any other renderer uses `paper:raw`, so **your output is the whole line** |
| Signed message | Changing the message or the renderer sends your text as the *unsigned content* of the player's signed message. Clients mark the line with a gray "modified" indicator and show the original text on hover, unless only styling changed and the plain text is identical |
| Cancelled | Nothing is sent to anyone; later handlers with `ignoreCancelled = true` (logging, Discord bridges) skip it |
## Paper Version Requirements
- Paper 1.21.11 / 26.3: `AsyncChatEvent`, `AsyncChatDecorateEvent`, `ChatRenderer`, `ChatRenderer.ViewerUnaware` have identical signatures on both (compared with `javap`); compile-verified on both. 26.3 ships Adventure 5.2, 1.21.11 Adventure 4.26; every Adventure / MiniMessage call used here exists in both
- No world access and no scheduler in the chat path, so the template also runs on Folia (see `paper-folia-scheduler`)
- **Spigot**: Spigot only has `AsyncPlayerChatEvent` with a `String` format; none of this API exists there
## Triggers
- 「聊天格式」「chat format」「聊天前綴」「chat prefix」「AsyncChatEvent」「ChatRenderer」「AsyncChatDecorateEvent」
- 「聊天頻道」「staff chat」「忽略玩家」「ignore player」「禁言」「mute」「提及高亮」「mention highlight」
- 「玩家聊天顏色」「MiniMessage 聊天」「聊天訊息被修改標記」「刪除聊天訊息」
## Inputs
| Parameter | Example | Description |
|------|------|------|
| `format` | `<gray><name></gray> » <message>` | Admin-written MiniMessage line with `<name>` and `<message>` |
| `channels` | global, staff (`chat.channel.staff`) | Channels and who may read them |
| `player_formatting` | colors with `chat.format.color` | Which tags players may type |
| `moderation` | ignore list, timed mute | Who is hidden from whom, who may not chat |
## Outputs
- `Channel.java` — chat channels and the permission to read each
- `ChatStyle.java` — immutable, admin-written formats per channel and the mention color
- `ChatState.java` — thread-safe channel choice, ignore lists and mutes
- `ChatInput.java` — `AsyncChatDecorateEvent`: player tags limited by permission
- `ChatFormatter.java` — `AsyncChatEvent`: mutes, viewers per channel / ignore list, per-viewer renderer with mention highlights
- `ChatPlugin.java` — wiring and `/ignore`, `/staffchat` commands
## Build Setup
See [`references/paper-api-platform.md`](references/paper-api-platform.md). Only `paper-api` (`compileOnly`); Adventure and MiniMessage ship with Paper. The template is Folia-safe; add `folia-supported: true` only if the rest of the plugin is.
## Code Template
### `Channel.java`
```java
package com.example.chat;
import org.bukkit.entity.Player;
/** A chat channel. GLOBAL is readable by everyone; the others need a permission. */
public enum Channel {
GLOBAL(null),
STAFF("chat.channel.staff");
private final String readPermission;
Channel(String readPermission) {
this.readPermission = readPermission;
}
public boolean canUse(Player player) {
return readPermission == null || player.hasPermission(readPermission);
}
}
```
### `ChatStyle.java`
```java
package com.example.chat;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import java.util.Objects;
/**
* Chat lines written by server admins, in full MiniMessage. Players never write these, so every tag is allowed;
* `<name>` and `<message>` are filled in as components and never parsed again.
*/
public record ChatStyle(String globalFormat, String staffFormat, TextColor mentionColor) {
public static final ChatStyle DEFAULT = new ChatStyle(
"<gray><name></gray> <dark_gray>»</dark_gray> <message>",
"<red>[Staff]</red> <name> <dark_gray>»</dark_gray> <aqua><message></aqua>",
NamedTextColor.YELLOW);
public ChatStyle {
requireMessageTag(globalFormat, "globalFormat");
requireMessageTag(staffFormat, "staffFormat");
Objects.requireNonNull(mentionColor, "mentionColor");
}
public String format(Channel channel) {
return channel == Channel.STAFF ? staffFormat : globalFormat;
}
private static void requireMessageTag(String format, String field) {
Objects.requireNonNull(format, field);
if (!format.contains("<message>")) {
throw new IllegalArgumentException(field + " must contain <message>, otherwise the text is dropped");
}
}
}
```
### `ChatState.java`
```java
package com.example.chat;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Who talks in which channel, who ignores whom, who is muted. Read on the async chat thread and written by
* commands on the main (or region) thread, so every map is concurrent. In memory only: persist it with
* paper-sqlite-repository if it must survive restarts.
*/
public final class ChatState {
private final Map<UUID, Channel> channels = new ConcurrentHashMap<>();
private final Map<UUID, Set<UUID>> ignored = new ConcurrentHashMap<>();
private final Map<UUID, Instant> mutedUntil = new ConcurrentHashMap<>();
public Channel channel(UUID player) {
return channels.getOrDefault(player, Channel.GLOBAL);
}
public void setChannel(UUID player, Channel channel) {
if (channel == Channel.GLOBAL) {
channels.remove(player);
} else {
channels.put(player, channel);
}
}
/** @return true when the target is now ignored, false when the ignore was removed */
public boolean toggleIgnore(UUID player, UUID target) {
Set<UUID> set = ignored.computeIfAbsent(player, k -> ConcurrentHashMap.newKeySet());
if (set.remove(target)) {
return false;
}
set.add(target);
return true;
}
public boolean ignores(UUID viewer, UUID sender) {
Set<UUID> set = ignored.get(viewer);
return set != null && set.contains(sender);
}
public void mute(UUID player, Duration duration) {
if (duration.isNegative() || duration.isZero()) {
throw new IllegalArgumentException("Mute duration must be positive");
}
mutedUntil.put(player, Instant.now().plus(duration));
}
public void unmute(UUID player) {
mutedUntil.remove(player);
}
/** Remaining mute time; expired mutes are removed on read. */
public Optional<Duration> muteRemaining(UUID player) {
Instant until = mutedUntil.get(player);
if (until == null) {
return Optional.empty();
}
Duration left = Duration.between(Instant.now(), until);
if (left.isNegative() || left.isZero()) {
mutedUntil.remove(player, until);
return Optional.empty();
}
return Optional.of(left);
}
/** Channel choice ends with the session; ignores and mutes stay. */
public void onQuit(UUID player) {
channels.remove(player);
}
}
```
### `ChatInput.java`
```java
package com.example.chat;
import io.papermc.paper.event.player.AsyncChatDecorateEvent;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
import net.kyori.adventure.text.minimessage.tag.standard.StandardTags;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
/**
* Turns what a player typed into styled text, with only the tags their permissions grant. Players never get
* click, hover, insertion, selector or translatable tags: `<click:run_command:...>` would let them make
* other players run commands. Only styling changes, so the plain text stays equal to what was signed and
* clients show no "modified" indicator for it.
*/
public final class ChatInput implements Listener {
public static final String PERMISSION_COLOR = "chat.format.color";
public static final String PERMISSION_FANCY = "chat.format.fancy";
private static final MiniMessage COLOR = MiniMessage.builder()
.tags(TagResolver.resolver(StandardTags.color(), StandardTags.decorations(), StandardTags.reset()))
.build();
private static final MiniMessage FANCY = MiniMessage.builder()
.tags(TagResolver.resolver(StandardTags.color(), StandardTags.decorations(), StandardTags.reset(),
StandardTags.gradient(), StandardTags.rainbow()))
.build();
/** Async chat pool. Only reads the player's permissions; no world access. */
@EventHandler(ignoreCancelled = true)
public void onDecorate(AsyncChatDecorateEvent event) {
Player player = event.player();
if (player == null) {
return;
}
MiniMessage parser = player.hasPermission(PERMISSION_FANCY) ? FANCY
: player.hasPermission(PERMISSION_COLOR) ? COLOR
: null;
if (parser == null) {
return; // the typed text stays literal: "<red>" shows as "<red>"
}
String typed = PlainTextComponentSerializer.plainText().serialize(event.originalMessage());
event.result(parser.deserialize(typed));
}
}
```
### `ChatFormatter.java`
```java
package com.example.chat;
import io.papermc.paper.chat.ChatRenderer;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
import java.time.Duration;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* Mutes, channels, ignore lists and the chat line. Everything here runs on the async chat pool: it reads
* ChatState and permissions, never the world.
*/
public final class ChatFormatter implements Listener {
private static final MiniMessage MINI_MESSAGE = MiniMessage.miniMessage();
private static final Map<String, Pattern> MENTION_PATTERNS = new ConcurrentHashMap<>();
private final ChatState state;
private final ChatStyle style;
public ChatFormatter(ChatState state, ChatStyle style) {
this.state = state;
this.style = style;
}
/** Lowest priority: a muted message is cancelled before anyone formats, logs or relays it. */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onMuted(AsyncChatEvent event) {
Player sender = event.getPlayer();
Optional<Duration> left = state.muteRemaining(sender.getUniqueId());
if (left.isPresent()) {
event.setCancelled(true);
sender.sendMessage(Component.text("You are muted for another " + minutes(left.get()) + " min.", NamedTextColor.RED));
}
}
/** High priority: runs after plugins that only add or remove viewers, so this renderer is the one used. */
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onChat(AsyncChatEvent event) {
Player sender = event.getPlayer();
UUID senderId = sender.getUniqueId();
Channel channel = state.channel(senderId);
if (!channel.canUse(sender)) { // lost the permission since choosing the channel
state.setChannel(senderId, Channel.GLOBAL);
channel = Channel.GLOBAL;
}
Channel target = channel;
// The console stays a viewer, so the chat is still logged.
event.viewers().removeIf(viewer -> viewer instanceof Player player
&& !player.getUniqueId().equals(senderId)
&& (!target.canUse(player) || state.ignores(player.getUniqueId(), senderId)));
event.renderer(new Renderer(style.format(target), style.mentionColor()));
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
state.onQuit(event.getPlayer().getUniqueId());
}
/** Called once per viewer (console included). Pure and cheap: no I/O, no world, no side effects. */
private record Renderer(String format, TextColor mentionColor) implements ChatRenderer {
@Override
public Component render(Player source, Component sourceDisplayName, Component message, Audience viewer) {
Component body = viewer instanceof Player player && !player.equals(source)
? highlightMention(message, player.getName(), mentionColor)
: message;
return MINI_MESSAGE.deserialize(format,
Placeholder.component("name", sourceDisplayName),
Placeholder.component("message", body));
}
}
/** Highlights the viewer's name ("Steve" or "@Steve", whole word, any case) in the message. */
static Component highlightMention(Component message, String viewerName, TextColor color) {
Pattern pattern = MENTION_PATTERNS.computeIfAbsent(viewerName.toLowerCase(),
name -> Pattern.compile("(?i)(?<![A-Za-z0-9_])@?" + Pattern.quote(name) + "(?![A-Za-z0-9_])"));
return message.replaceText(TextReplacementConfig.builder()
.match(pattern)
.replacement(match -> match.color(color).decorate(TextDecoration.BOLD))
.build());
}
private static long minutes(Duration duration) {
return Math.max(1, (duration.toSeconds() + 59) / 60);
}
}
```
### `ChatPlugin.java`
```java
package com.example.chat;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import io.papermc.paper.command.brigadier.CommandSourceStack;
import io.papermc.paper.command.brigadier.Commands;
import io.papermc.paper.command.brigadier.argument.ArgumentTypes;
import io.papermc.paper.command.brigadier.argument.resolvers.selector.PlayerSelectorArgumentResolver;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public final class ChatPlugin extends JavaPlugin {
private static final String ARG_TARGET = "target";
private final ChatState state = new ChatState();
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(new ChatInput(), this);
getServer().getPluginManager().registerEvents(new ChatFormatter(state, ChatStyle.DEFAULT), this);
getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> {
event.registrar().register(Commands.literal("ignore")
.requires(source -> source.getExecutor() instanceof Player)
.then(Commands.argument(ARG_TARGET, ArgumentTypes.player()).executes(this::ignore))
.build(), "Hide or show a player's chat messages");
event.registrar().register(Commands.literal("staffchat")
.requires(source -> source.getExecutor() instanceof Player player && Channel.STAFF.canUse(player))
.executes(this::toggleStaffChat)
.build(), "Switch between staff and global chat");
});
}
private int ignore(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
if (!(context.getSource().getExecutor() instanceof Player player)) {
return 0;
}
Player target = context.getArgument(ARG_TARGET, PlayerSelectorArgumentResolver.class)
.resolve(context.getSource()).getFirst();
if (target.equals(player)) {
player.sendMessage(Component.text("You cannot ignore yourself.", NamedTextColor.RED));
return 0;
}
boolean nowIgnored = state.toggleIgnore(player.getUniqueId(), target.getUniqueId());
player.sendMessage(Component.text((nowIgnored ? "Ignoring " : "No longer ignoring ") + target.getName() + ".",
NamedTextColor.GRAY));
return Command.SINGLE_SUCCESS;
}
private int toggleStaffChat(CommandContext<CommandSourceStack> context) {
if (!(context.getSource().getExecutor() instanceof Player player)) {
return 0;
}
Channel next = state.channel(player.getUniqueId()) == Channel.STAFF ? Channel.GLOBAL : Channel.STAFF;
state.setChannel(player.getUniqueId(), next);
player.sendMessage(Component.text("Now talking in " + next.name().toLowerCase() + " chat.", NamedTextColor.GRAY));
return Command.SINGLE_SUCCESS;
}
}
```
`plugin.yml` (no `commands:` section; the commands are registered with Brigadier):
```yaml
name: ChatExample
version: 1.0.0
main: com.example.chat.ChatPlugin
api-version: '26.3'
permissions:
chat.channel.staff:
default: op
chat.format.color:
default: false
chat.format.fancy:
default: op
```
## Recommended Directory Structure
```
src/main/java/com/example/chat/
├── Channel.java <- channels and read permissions
├── ChatStyle.java <- admin formats (immutable)
├── ChatState.java <- channel choice, ignores, mutes (concurrent)
├── ChatInput.java <- AsyncChatDecorateEvent: player tags by permission
├── ChatFormatter.java <- AsyncChatEvent: mute, viewers, renderer
└── ChatPlugin.java <- wiring, /ignore, /staffchat
```
## Thread Safety
- `AsyncChatDecorateEvent`, `AsyncChatEvent` and every `ChatRenderer#render` call run on the async chat pool. Allowed there: the event's own data, `Player#getName` / `getUniqueId` / `hasPermission`, `sendMessage`, concurrent plugin state. Not allowed: reading or changing the world, entities, inventories or locations (`getLocation`, `getWorld().getBlockAt`, `teleport`), the Bukkit scheduler's sync results, blocking I/O
- Need world data (local chat radius, region names)? Keep a snapshot updated on the player's own thread and read the snapshot (see examples.md, Example 2)
- Need a side effect (sound on mention, quest progress)? Schedule it from the event handler with `player.getScheduler().run(...)`, never from the renderer: the renderer runs once per viewer and may run for messages that end up cancelled by a later handler
- The same handlers may run on the main thread when a plugin calls `Player#chat`; code written for the async case works there too
- See [`references/paper-threading.md`](references/paper-threading.md)
### Key Techniques
| Topic | Approach |
|------|------|
| Whole line under your control | `event.renderer(...)` with a non-default renderer → chat type `paper:raw`; include the name yourself |
| Same output for everyone | `ChatRenderer.viewerUnaware((source, name, message) -> ...)` renders once instead of once per viewer |
| Different output per viewer | Viewer-aware `ChatRenderer`; check `viewer instanceof Player` (the console is a viewer too) |
| Admin format + player text | `MiniMessage#deserialize(format, Placeholder.component("message", message))`: the message is inserted as a component and never parsed as MiniMessage |
| Player color codes | `AsyncChatDecorateEvent` with a `MiniMessage` built from `StandardTags.color()` / `decorations()` only |
| Channels / ignore | `event.viewers().removeIf(...)`; keep the sender and the console |
| Mute | Cancel at `EventPriority.LOWEST` so formatters, loggers and bridges with `ignoreCancelled = true` skip it |
| Delete messages later | Keep `event.signedMessage().signature()` when `canDelete()`; `Bukkit.getServer().deleteMessage(signature)` removes it from every client (examples.md, Example 1) |
| Plugin-sent chat | `player.chat("text")` runs the whole pipeline as if the player typed it; use `sendMessage` for system text |
## Fallback
| Error | Cause | Fix |
|------|------|------|
| Name appears twice or not at all | Renderer replaced (chat type `paper:raw` draws only your output) but the format lacks or duplicates `<name>` | Put the name in your format exactly once |
| Your format is ignored | Another plugin sets the renderer at a later priority, or a legacy `AsyncPlayerChatEvent` plugin sets a format | Set the renderer at `HIGH`; ask the other plugin to use `AsyncChatEvent`, or disable its formatting |
| Players run commands or show fake text through chat | Player text parsed with `MiniMessage.miniMessage()` (all tags, including `<click:run_command>`) | Parse player text only with a `MiniMessage` built from color / decoration tags; insert it with `Placeholder.component` |
| Format tags appear literally, e.g. `<gray>` | Admin format inserted with `Placeholder.unparsed` or `Component.text` | Deserialize the admin format; use `Placeholder.component` only for the parts that come from players |
| Gray bar on the left of every chat line, original visible on hover | The client marks signed messages whose plain text the server changed (custom renderer or edited `message()`) | Expected with server-side formats. Only styling changes (decorate event colors) keep the plain text and show no bar. Do not rely on editing `message()` to hide words: the original stays readable on hover; cancel the message instead |
| `IllegalStateException: Asynchronous ... !` or random world corruption | World or entity access from the chat pool | Use snapshots or schedule onto the player's thread |
| Staff messages visible to everyone | Viewers not filtered, or filtered in a handler that ran before another plugin re-added viewers | Filter at `HIGH`; never call `viewers().addAll(Bukkit.getOnlinePlayers())` |
| Console log shows nothing | Console removed from `viewers()` (e.g. `viewers().clear()`) | Remove only `Player` viewers |
| `deleteMessage` does nothing | Message was unsigned (`canDelete()` false: offline mode, `enforce-secure-profile: false`, or the client did not sign) or the client already dropped it | Check `canDelete()` and tell the moderator; nothing else can remove it from clients |
| `/me` and `/say` keep raw tags | Command messages fire `AsyncChatCommandDecorateEvent` (its own handler list), not `AsyncChatDecorateEvent` | Listen to `AsyncChatCommandDecorateEvent` too if commands should get the same formatting |