? Prism - THE 命令框架
目录
Why Prism?
大多数命令框架依赖于注解和反射:你用一堆注解来描述一个命令,然后框架在运行时自行解析其余部分。Prism 采取了相反的方法。命令是纯 Java 代码,通过流畅的构建器构建,因此你可以获得:
- 编译时安全性。参数、执行器和要求都是真实的类型化对象,而不是埋在注解中的字符串。
- 组合性。命令是值。你可以在循环中构建它们,共享参数定义,并以编程方式组装树。
- 可发现性。IDE 的自动补全就是文档。所有内容都挂在一个构建器上。
- 一套 API,多个平台。核心与平台无关;Spigot、Paper(具有原生 Brigadier 支持)、Velocity 和其他平台可以在此基础上进行插件集成。
new PrismBukkitCommand("heal")
.withDescription("Heal a player")
.withPermission("myplugin.heal")
.withArguments(new PlayerArgument("target"))
.executes((sender, args) -> {
Player target = args.get("target");
target.setHealth(20);
sender.sendMessage("Healed " + target.getName());
})
.register(platform);
Features
- ? 流畅、类型安全的构建器 API,无需注解
- ? 子命令和参数树,用于任意嵌套的命令结构
- ? 丰富的内置参数,适用于玩家、世界、材料、位置、实体选择器、范围、颜色、附魔、药水效果等
- ? 同步和异步的 Tab 补全,带有可选的工具提示
- ? 标志支持 (
-c red -e),通过 FlagArgument 实现
- ? 权限和使用要求,可在命令和参数级别设置
- ? 按发送者类型的执行器,适用于玩家、控制台、远程控制台、命令方块和代理发送者
- ⚡ 原生 Brigadier 集成(客户端验证、彩色语法、原生建议),并带有自动的旧版回退机制
- ?️ Velocity 支持,基于相同的 Brigadier 树构建器
- ? 内置帮助生成器,渲染命令树的 clickable 用法
- ♻️ 运行时注册和注销命令
- ? 阴影包 (Shaded bundles),以便你只需分发一个依赖项
- ? 独立插件,如果你不想将 Prism 阴影打包到你的 jar 中
Supported platforms
| 平台 |
模块 |
状态 |
| Spigot(及衍生版) |
prism-spigot |
支持 |
| Paper(及衍生版) |
prism-paper |
支持 |
| Brigadier(Minecraft 1.13 → 26.x) |
包含在 Spigot 和 Paper 构建中 |
支持 |
| Velocity |
platform/velocity |
? 实验性 |
| JDA(Discord) |
platform/jda |
? 开发中 |
Prism 基于 Spigot 1.13.2 API 进行编译,且 Brigadier 层针对 Minecraft 1.13 至 1.21 以及 26.x 提供了每个版本的适配器。如果你的服务器版本无法初始化 Brigadier,Prism 会记录警告并回退到传统注册方式,以确保命令仍能正常工作。
Velocity 模块面向 Java 25 和 Velocity 4.x API。Velocity 没有旧版回退机制:命令始终通过 Brigadier 进行注册。
安装
Prism 目前处于 beta 阶段(1.0.0-beta.4)。API 在 beta 版本之间仍可能发生变化。
Group ID: dev.gurwi
| 服务端软件 |
Artifact ID |
| Paper |
prism-paper |
| Spigot |
prism-spigot |
每个 Artifact 都是一个自包含的捆绑包,其中已包含核心、Bukkit 层以及匹配的 Brigadier 适配器,因此你只需添加一个依赖项即可。
Gradle (Kotlin DSL)
repositories {
mavenCentral()
}
dependencies {
implementation("dev.gurwi:prism-paper:1.0.0-beta.4")
}
Gradle (Groovy DSL)
repositories {
mavenCentral()
}
dependencies {
implementation 'dev.gurwi:prism-paper:1.0.0-beta.4'
}
Maven
<dependency>
<groupId>dev.gurwi</groupId>
<artifactId>prism-paper</artifactId>
<version>1.0.0-beta.4</version>
</dependency>
如果你目标是 Spigot,请将 prism-paper 替换为 prism-spigot。各个独立模块(prism-core、prism-bukkit、prism-brigadier 和 prism-brigadier-minecraft)也已发布,但大多数项目应使用捆绑包。
Prism 是一个库,而非独立插件,因此请将其 Shade(阴影化/重定位)到你的插件 jar 中(例如使用 Shadow 插件),并进行重定位以避免与其他捆绑了 Prism 的插件发生冲突。
不想 Shade?可以改为将 Prism 作为独立插件安装,请参阅 独立插件。
独立插件
与其在每个插件中 Shade Prism,不如将 Prism 作为名为 prism 的插件一次性安装在服务器上。你的插件随后将其作为依赖项,共享同一份库副本,并通过 Prism API 注册命令。这是位于 plugin/bukkit-plugin 中的 Bukkit 插件,基于 Paper 平台构建。
安装插件
- 将
prism-<version>.jar 放入服务器的 plugins 文件夹。
- 启动服务器一次。插件会创建
plugins/prism/config.yml。
- 将所有使用该库的插件都将 Prism 设为其依赖项。
该插件还会添加一个 /prism 命令,显示基本信息并链接到此仓库。可以在配置文件中关闭此命令。
在你的插件中使用它
在你的 plugin.yml 中声明依赖项,以确保 Prism 优先加载:
name: MyPlugin
main: com.example.myplugin.MyPlugin
version: 1.0.0
depend: [prism]
在不 Shade 的情况下针对 Prism 进行编译。API 类来自 api 模块,构建后生成 prism-<version>-API.jar;命令类则来自对应的 Prism 模块:
dependencies {
compileOnly("dev.gurwi:prism-paper:1.0.0-beta.4")
compileOnly(files("libs/prism-1.0.0-beta.4-API.jar"))
}
所有内容均为 compileOnly:在运行时,类来自已安装的 Prism 插件,因此无需 Shade 或重定位。
有两种注册命令的方式:让 Prism 从 command provider 中拾取它们,或者使用 API 和注册表自行处理。这里先介绍注册表方式。
通过 PrismPluginAPI.getAPI() 获取 API。如果未安装 Prism 或其服务尚未注册,它将返回 null。
public class MyPlugin extends JavaPlugin {
@Override
public void onEnable() {
PrismPluginAPI api = PrismPluginAPI.getAPI();
if (api == null) {
getLogger().severe("Prism is not installed");
getServer().getPluginManager().disablePlugin(this);
return;
}
BukkitCommandsRegistry<?> registry = api.createRegistry(this);
registry.register(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.build()
);
}
}
命令使用与 指南 中相同的 PrismBukkitCommand API 构建。你不再调用 .register(platform),而是将构建好的定义传递给注册表。
| 方法 |
描述 |
PrismPluginAPI.getAPI() |
API 实例,如果缺少 Prism 则返回 null。 |
createRegistry(plugin) |
为你的插件创建一个注册表,配置源自 Prism 的 config.yml。 |
getDefaultRegistry() |
Prism 自身平台的注册表,所有插件共享。 |
registerProvider(plugin, provider, registry) |
注册一个 command provider。registry 可以为 null。 |
getRegistriesManager() |
包含 createRegistry、getRegistry(plugin) 和 unloadRegistry(plugin)。 |
推荐使用 createRegistry(this),以便按插件跟踪你的命令。
命令提供者
如果你只想注册命令,请在主类中实现 PrismCommandProvider 并从 getCommands() 返回它们。当你的插件启用时,Prism 会检测到该提供程序,构建所有命令并注册它们。你的插件中无需包含任何注册代码。
public class MyPlugin extends JavaPlugin implements PrismCommandProvider {
@Override
public Collection<? extends PrismBukkitCommand> getCommands() {
return List.of(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!")),
new PrismBukkitCommand("ping")
.executes((sender, args) -> sender.sendMessage("Pong!"))
);
}
}
请返回构建器而非已构建的定义:Prism 会自行调用 build()。
默认情况下,每个插件都拥有自己的注册表,由 Prism 的 config.yml 创建,且当插件禁用时会注销其命令。若要自行选择注册表,请重写 getRegistry():
@Override
public BukkitCommandsRegistry<?> getRegistry() {
return PrismPluginAPI.getAPI().getDefaultRegistry();
}
提供程序不必是你的主类。使用 registerProvider 可以手动注册任意提供程序:
PrismPluginAPI.getAPI().registerProvider(this, () -> List.of(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
), null);
传入 null 作为注册表参数时,将使用提供程序的 getRegistry(),若未定义则回退到每插件独立的注册表。你的插件仍需在插件描述文件中声明 depend: [prism];对于未声明此依赖的提供程序,Prism 会记录一条警告日志。
插件配置
plugins/prism/config.yml 控制 Prism 如何创建其平台以及分发的注册表:
| 选项 |
默认值 |
描述 |
disableInfoCommand |
false |
不注册 /prism 信息命令。 |
disableBrigadierRegistrar |
false |
跳过 Brigadier,仅通过旧版系统注册。 |
disableLegacyRegistrar |
false |
禁用旧版注册器。 |
disableAsyncSuggestions |
false |
不注册异步标签补全监听器。 |
registerPermissions |
false |
向服务器注册命令权限。 |
这些选项映射自 平台配置,适用于使用独立 Prism 的所有插件。
快速开始
1. 创建平台
在 onEnable 中执行一次。
Paper
public class MyPlugin extends JavaPlugin {
private PaperPlatform platform;
@Override
public void onEnable() {
this.platform = PaperPlatform.configure(this).init();
}
}
Spigot
public class MyPlugin extends JavaPlugin {
private SpigotPlatform platform;
@Override
public void onEnable() {
this.platform = SpigotPlatform.configure(this).init();
}
}
Velocity 的设置方式不同,请参阅 Velocity。
2. 构建并注册命令
new PrismBukkitCommand("teleport", "tp")
.withDescription("Teleport yourself to a location")
.withPermission("myplugin.teleport")
.withArguments(new LocationArgument("location"))
.executesPlayer((player, args) -> {
Location location = args.get("location");
player.teleport(location);
player.sendMessage("Teleported!");
})
.register(platform);
就是这样。第一个参数是命令名称;后续字符串均为别名。标签补全、参数解析和错误提示均自动提供。
指南
本指南使用 Bukkit API(PrismBukkitCommand)。构建器方法(withArguments、withOptionalArguments、withSubCommands、then、withPermission、withRequirement、register)继承自跨平台核心,在所有平台上行为一致。只有执行器、发送者、参数和权限辅助工具因平台而异。
参数
必需参数通过 withArguments(...) 添加。它们按顺序解析,并通过传递给执行器的 CommandArguments 对象按名称读取值。
new PrismBukkitCommand("give")
.withArguments(
new PlayerArgument("target"),
new MaterialArgument("material"),
new IntegerArgument("amount", 1, 64)
)
.executes((sender, args) -> {
Player target = args.get("target");
Material material = args.get("material");
int amount = args.get("amount");
target.getInventory().addItem(new ItemStack(material, amount));
})
.register(platform);
args.get(...) 是泛型的,因此目标类型会根据你赋值给它变量推断得出。你也可以直接传递参数对象本身而非其名称:
IntegerArgument amount = new IntegerArgument("amount", 1, 64);
// ...
int value = args.get(amount);
可选参数
可选参数通过 withOptionalArguments(...) 声明,且必须始终位于必需参数之后。
new PrismBukkitCommand("number")
.withArguments(new IntegerArgument("number", 0, 10))
.withOptionalArguments(new FloatArgument("float", 0.1f, 9.9f))
.executes((sender, args) -> {
int number = args.get("number");
float scale = args.getOptional("float", 1.0f); // 带默认值
sender.sendMessage(number + " x " + scale);
})
.register(platform);
getOptional(key) 返回一个 Optional<T>,而 getOptional(key, defaultValue) 返回值或你提供的默认值。
子命令
使用 withSubCommands(...) 嵌套命令。子命令只是另一个 PrismBukkitCommand。
new PrismBukkitCommand("team", "t")
.withDescription("Team management")
.withSubCommands(
new PrismBukkitCommand("create")
.withArguments(new StringArgument("name"))
.executes((sender, args) -> {
sender.sendMessage("Created team " + args.get("name"));
}),
new PrismBukkitCommand("join")
.withArguments(new StringArgument("name"))
.executesPlayer((player, args) -> {
player.sendMessage("Joined team " + args.get("name"));
})
)
.register(platform);
子命令可以通过路径从父级读取参数,使用带有 ../ 风格路径的 getAt:
new PrismBukkitCommand("paint")
.withArguments(new ColorArgument("color"))
.withSubCommands(
new PrismBukkitCommand("call")
.executes((sender, args) -> {
// 从父命令读取 "color"
sender.sendMessage("Color: " + args.getAt("../", "color"));
})
)
.register(platform);
如果需要在树结构中检查当前位置,CommandArguments 还暴露了定义链(getParent()、getRoot()、getChain()、getChildDefinitions())。
参数树
当命令需要根据所走路径提供不同的后续参数时,使用 then(...)。每个分支都可以携带自己的执行器。
new PrismBukkitCommand("prism", "pri")
.withArguments(new ItemStackPredicateArgument("predicate"))
.then(
new MaterialArgument("material")
.executes((sender, args) -> {
Material material = args.get("material");
sender.sendMessage("Selected material " + material);
})
)
.then(
new GameModeArgument("gamemode")
.executes((sender, args) -> {
GameMode gameMode = args.get("gamemode");
sender.sendMessage("Selected game mode " + gameMode);
})
)
.register(platform);
可以通过在参数上调用 .then(...) 来进一步嵌套分支。参数名称必须在同级中唯一,如果你重用了一个名称或尝试在它自己下面添加一个参数,Prism 会抛出 IllegalArgumentException。
未列出的参数(通过 setListed(false) 设置,如 LiteralArgument)会被匹配但不会存储在 CommandArguments 中。
执行器和发送者
选择与谁可以运行命令相匹配的执行器。Prism 只会调用适合发送者的执行器,因此你不需要进行 instanceof 检查。
| 方法 |
发送者类型 |
executes(...) |
任何 CommandSender |
executesPlayer(...) |
Player |
executesConsole(...) |
ConsoleCommandSender |
executesRemoteConsole(...) |
RemoteConsoleCommandSender |
executesProxy(...) |
ProxiedCommandSender |
executesBlock(...) |
BlockCommandSender |
你可以在同一个命令上注册多个执行器,每种发送者类型一个:
new PrismBukkitCommand("whoami")
.executesPlayer((player, args) -> player.sendMessage("You are " + player.getName()))
.executesConsole((console, args) -> console.sendMessage("You are the console"))
.register(platform);
使用 clearExecutors() 移除构建器中的所有执行器。
没有匹配执行器的发送者会在 Brigadier 平台上收到“此命令无法由该发送者运行”的消息,并且该命令会从建议列表中隐藏。
权限和要求
权限是针对发送者进行检查的(在 Bukkit 平台上,操作员始终通过):
new PrismBukkitCommand("admin")
.withPermission("myplugin.admin", "myplugin.staff")
// ...
对于通配符风格的检查,BukkitPermission.startsWith("myplugin.") 将匹配具有该前缀的任何有效权限。Velocity 没有等效项,请参阅 Velocity permissions。
要求是对发送者的任意谓词。提供了特定于发送者的快捷方式:
new PrismBukkitCommand("fly")
.withPlayerRequirement(player -> player.getWorld().getName().equals("lobby"))
.executesPlayer((player, args) -> player.setAllowFlight(true))
.register(platform);
可用的辅助方法有:withRequirement、withPlayerRequirement、withConsoleRequirement、withRemoteConsoleRequirement、withProxyRequirement 和 withBlockRequirement。要求也可以通过 withRequirement(...) 附加到单个参数上,并且可以使用 setListed(false) 从列表隐藏参数。
建议和 Tab 补全
每个内置参数都附带合理的默认建议。使用 replaceSuggestions(...) 替换它们。
静态字符串
new IntegerArgument("number", 0, 10).replaceSuggestions("5", "10");
同步计算的提示(带工具提示)
new StringArgument("kit").replaceSuggestions(
BukkitSuggestionsSupplier.sync(ctx -> List.of(
ArgumentSuggestion.of("starter", "The default starter kit"),
ArgumentSuggestion.of("vip", "Perks for VIP players")
))
);
异步建议(用于数据库或网络查找)返回一个 CompletableFuture:
new StringArgument("player").replaceSuggestions(
BukkitSuggestionsSupplier.async(ctx -> CompletableFuture.supplyAsync(() ->
List.of(ArgumentSuggestion.of("alpha", "first async value"))
))
);
传入的 SuggestionContext 允许你获取当前原始输入(ctx.getCurrentRawArg()),从而对结果进行过滤。辅助方法 BukkitSuggestionsSupplier.strings(...) 和 stringsAsync(...) 涵盖了纯字符串类型的场景。
在 Brigadier 平台上,Prism 还会根据已输入的文本(不区分大小写的前缀匹配)对建议进行过滤,因此供应商可以返回其完整列表。
在 Paper 上,异步建议通过专用监听器处理。你可以使用 disableAsyncSuggestions() 关闭此功能(参见 平台配置)。
标志位(Flags)
FlagArgument 以任意顺序解析 -x 风格的标志位。标志位可以携带值(使用任何其他参数类型),也可以作为简单的开/关开关。
new PrismBukkitCommand("flagger")
.withArguments(
new FlagArgument("flags").flags(
Flag.valued(new ColorArgument("color"), 'c'),
Flag.presence("enable", 'e')
)
)
.executesPlayer((player, args) -> {
ParsedFlags flags = args.get("flags");
Optional<ChatColor> color = flags.get("color");
color.ifPresent(c -> player.sendMessage("Color: " + c.name()));
})
.register(platform);
内置帮助
CommandHelp 为当前命令渲染一个可点击的使用说明列表,包括其子命令和参数树分支。它仅显示发送者实际有权执行的条目。
new PrismBukkitCommand("myplugin")
.withSubCommands(/* ... */)
.executesPlayer((player, args) -> CommandHelp.help(player, args))
.register(platform);
向 CommandHelp.help(sender, args, primary, secondary) 传递两个额外的 ChatColor 值以重新设置样式。
注册与注销
命令可以通过两种等价的方式进行注册:
// 1. 直接从构建器注册
BukkitCommandDefinition definition = new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.register(platform);
// 2. 先构建,稍后注册
BukkitCommandDefinition built = new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.build();
platform.getCommandsRegistry().register(built);
platform.getCommandsRegistry().unregister(built);
getRegisteredCommands() 返回平台上所有已注册命令的不可修改视图。
Velocity
Velocity 平台(platform/velocity)复用了核心构建器和 Brigadier 树构建器,因此命令、子命令、参数树、可选参数和建议的工作方式与指南中描述的一致。命令类为 VelocityCommand,发送者为 Velocity 的 CommandSource。
设置
在你的插件构造函数中创建平台实例,并从你的 ProxyInitializeEvent 处理器或更晚的时机注册命令。
@Plugin(id = "my-plugin")
public class MyPlugin {
private final ProxyServer server;
private final VelocityPlatform platform;
@Inject
public MyPlugin(ProxyServer server) {
this.server = server;
this.platform = VelocityPlatform.configure(this, server).init();
}
@Subscribe
public void onProxyInit(ProxyInitializeEvent event) {
new VelocityCommand("hello")
.executes((source, args) -> {
source.sendPlainMessage("Hello World!");
})
.register(platform);
}
}
VelocityPlatform.configure(plugin, server) 接受你的插件实例作为普通的 Object。Velocity 没有插件句柄:@Plugin 是一个注解,你的主类的实例即为插件。
- Prism 不会注册任何 Velocity 事件监听器。
register(...) 会立即与 Velocity 的 CommandManager 通信,因此请避免在 ProxyInitializeEvent 之前调用它。
- Velocity 注入的是 SLF4J
Logger,而非 java.util.logging.Logger。
权限
Velocity 没有操作员(operator)系统,因此不存在 OP 权限。权限通过 CommandSource#hasPermission 进行处理,且 ConsoleCommandSource 始终通过验证。
VelocityPermission.of("myplugin.admin");
VelocityPermission.of("myplugin.admin", "myplugin.staff");
如果没有安装如 LuckPerms 这样的权限插件,Velocity 的默认提供者会对每次 hasPermission 调用返回 true,这意味着任何玩家都能通过任何权限检查。除非已安装权限插件,否则不要依赖权限来执行任何敏感操作。
Velocity 无法枚举源拥有的权限,因此前缀检查是针对已知节点集合进行的,而不是针对发送者的有效权限:
VelocityPermission.startsWith("myplugin.admin.", knownPermissions);
knownPermissions 是你声明命令所使用的节点集合。仅在该集合中的节点会被测试,并且每个节点都会通过 hasPermission 进行检查。如果你需要在运行时匹配任意节点,请直接使用 LuckPerms API。
与 Bukkit 的差异
| 主题 |
Bukkit 平台 |
Velocity |
| 命令类 |
PrismBukkitCommand |
VelocityCommand |
| 发送者 |
CommandSender |
CommandSource |
| 插件句柄 |
JavaPlugin |
Object(你的插件实例) |
| 注册时机 |
onEnable |
ProxyInitializeEvent 或之后 |
| 操作员 |
始终通过权限检查 |
无操作员概念 |
startsWith 权限 |
匹配有效权限 |
匹配提供的已知节点集合 |
| Brigadier 回退 |
传统注册器 |
无,仅支持 Brigadier |
| 建议工具提示 |
LiteralMessage |
VelocityBrigadierMessage |
平台配置
PaperPlatform.configure(plugin) 和 SpigotPlatform.configure(plugin) 均返回一个构建器。以 .init() 结束。VelocityPlatform.configure(plugin, server) 的工作方式相同。
| 选项 |
平台 |
描述 |
disableBrigadier() |
Paper, Spigot |
跳过 Brigadier,仅通过传统命令系统进行注册。 |
disableLegacyRegistrar() |
Paper, Spigot |
禁用传统注册器。 |
disableAsyncSuggestions() |
Paper |
不注册异步 Tab 补全监听器。 |
registerPermissions(boolean) |
Paper, Spigot |
切换命令权限注册。默认为 true。 |
withGlobalLegacyCommandErrorHandler(handler) |
Paper, Spigot |
设置传统注册命令的参数解析错误的默认处理程序。 |
PaperPlatform platform = PaperPlatform.configure(this)
.disableAsyncSuggestions()
.registerPermissions(false)
.init();
单个命令可以使用 replaceErrorHandler(...) 覆盖错误处理程序。Prism 提供了 LegacyCommandExecutionErrorHandler.defaultHandler() 和 consoleHandler(),你也可以自行实现该接口。
内置参数类型
所有这些类型都位于 dev.gurwi.prism.bukkit.argument 包中。
| 类别 |
参数 |
| 基本类型 |
StringArgument, GreedyStringArgument, MultiStringArgument, CharacterArgument, BooleanArgument, ByteArgument, ShortArgument, IntegerArgument, LongArgument, FloatArgument, DoubleArgument, UUIDArgument |
| 范围 |
ByteRangeArgument, ShortRangeArgument, IntegerRangeArgument, LongRangeArgument, FloatRangeArgument, DoubleRangeArgument, NumberRangeArgument |
| 玩家与实体 |
PlayerArgument, OfflinePlayerArgument, EntityTypeArgument, EntitySelectorArgument(例如 ManyEntities) |
| 世界与位置 |
WorldArgument, LocationArgument, ColumnLocationArgument, BlockPositionArgument, ColumnBlockPositionArgument, VectorArgument, RotationArgument, AngleArgument, AxesArgument |
| 方块与物品 |
MaterialArgument, BlockStateArgument, BlockPredicateArgument, ItemStackPredicateArgument, EnchantmentArgument |
| 游戏枚举与注册表 |
GameModeArgument, DifficultyArgument, WeatherArgument, BiomeArgument, PotionEffectTypeArgument, ParticleArgument, SoundArgument, DisplaySlotArgument, NamespacedKeyArgument, MirrorArgument, StructureRotationArgument, EnumArgument |
| 文本与颜色 |
ColorArgument, HexColorArgument, MessageArgument, TimeArgument |
| 结构体 |
LiteralArgument, FlagArgument |
Velocity 参数位于 dev.gurwi.prism.velocity.argument 包中,并继承自 VelocityArgument。每个参数都封装了一个 Brigadier ArgumentType。
需要自定义内容?扩展 BukkitArgument(或在 Velocity 上扩展 VelocityArgument,或其中一个 base 参数类),实现 parse(...) 方法,并可选择提供默认建议。
贪婪参数必须是命令的最后一个参数,且不能有子节点。
实现你自己的平台
core 对 Minecraft、Discord 或任何其他宿主环境一无所知。平台是一个薄层,在其之上提供六项内容,其余一切(流畅构建器、参数树、子命令、要求、CommandArguments)都会自动获得。platform/bukkit 模块是功能齐全的参考实现,platform/velocity 是一个仅包含 Brigadier 的精简参考实现,而 platform/jda 则是一个遵循相同布局的最小化骨架。
添加 core 模块(它已单独发布):
dependencies {
api("dev.gurwi:prism-core:1.0.0-beta.4")
}
以下示例使用一个虚构的聊天服务,其中命令源为 AcmeUser。
1. 执行器
执行器是针对你的源类型和定义类型的函数式接口。
@FunctionalInterface
public interface AcmeExecutor extends CommandExecutor<AcmeUser, AcmeCommandDefinition> {
}
如果你的宿主有多种类型的发送者(例如 Bukkit 的玩家、控制台和命令方块),请为每种类型声明一个执行器接口,并像 BukkitExecutorContainerBuilder 那样将它们注册到各自的类下。
2. 权限
实现 PermissionNode<Permission, Source>。permission() 返回你宿主环境的原生权限值,而 hasPermission(...) 用于判断给定源是否拥有该权限。
public record AcmePermission(String node) implements PermissionNode<String, AcmeUser> {
@Override
public String permission() {
return node;
}
@Override
public boolean hasPermission(AcmeUser user) {
return user.hasPermission(node);
}
}
3. 参数与建议
将你的源类型和 SuggestionsSupplier 扩展至 AbstractArgument。你必须实现的方法是 parse。对于无效输入,抛出 ArgumentParseException。
@FunctionalInterface
public interface AcmeSuggestions<T> extends SuggestionsSupplier<AcmeUser, Collection<T>> {
}
public abstract class AcmeArgument<Impl extends AcmeArgument<Impl, T>, T>
extends AbstractArgument<Impl, T, AcmeUser, AcmeSuggestions<T>> {
public AcmeArgument(String name, AcmeSuggestions<T> defaultSuggestions) {
super(name, defaultSuggestions);
}
}
public class AcmeIntegerArgument extends AcmeArgument<AcmeIntegerArgument, Integer> {
public AcmeIntegerArgument(String name) {
super(name, ctx -> List.of());
}
@Override
public Integer parse(AcmeUser source, String value) throws ArgumentParseException {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ArgumentParseException(this, value, "'" + value + "' is not a number");
}
}
}
如果你希望在你的平台上使用 then(...) 参数树,请在后续步骤中扩展 AbstractTreeArgument 以及 AbstractTreeCommandBuilder / AbstractTreeCommandDefinition(这正是 Bukkit 模块所做的操作)。
参数还暴露了 canUse(source),平台必须尊重此方法;以及 isListed(),该方法决定解析后的值是否存储在 CommandArguments 中。
4. 命令定义
定义是命令的不可变构建形式。继承 AbstractCommandDefinition 并绑定其类型参数(自身类型、源、执行器、参数、权限)。构建器是唯一构造它的地方。
public class AcmeCommandDefinition extends AbstractCommandDefinition<
AcmeCommandDefinition, AcmeUser, AcmeExecutor, AcmeArgument<?, ?>, AcmePermission> {
protected AcmeCommandDefinition(@Nullable AcmeCommandDefinition parent, String name, List<String> aliases,
String description, UsageRequirement<AcmeUser> requirement,
Set<AcmePermission> permissions,
List<AcmeArgument<?, ?>> requiredArguments,
List<AcmeArgument<?, ?>> optionalArguments,
Map<Class<? extends AcmeExecutor>, AcmeExecutor> executors,
CommandChildrenFactory<AcmeCommandDefinition> childrenFactory) {
super(parent, name, aliases, description, requirement, permissions,
requiredArguments, optionalArguments, executors, childrenFactory);
}
}
基类已经为你提供了 getName()、getAliases()、getChildren()、getChild(name)、getParent()、getExecutors()、hasExecutor(source) 和 canExecute(source)(要求加上所有权限)。
5. 构建器
扩展 AbstractCommandBuilder,实现 build(parent),并根据你的执行器需要添加任何便捷方法。
public class AcmeCommandBuilder extends AbstractCommandBuilder<
AcmeCommandBuilder, AcmeCommandDefinition, AcmeUser, AcmeExecutor, AcmeArgument<?, ?>, AcmePermission> {
public AcmeCommandBuilder(String name, String... aliases) {
super(name, aliases);
}
public AcmeCommandBuilder executes(AcmeExecutor executor) {
return executes(AcmeExecutor.class, executor);
}
@Override
public AcmeCommandDefinition build(@Nullable AcmeCommandDefinition parent) {
return new AcmeCommandDefinition(parent, name, aliases, description, requirement, permissions,
requiredArguments, optionalArguments, executors, CommandChildrenFactory.create(children));
}
}
withDescription、withArguments、withOptionalArguments、withPermission、withRequirement、withSubCommands 和 register(...) 均为继承而来。register(...) 将构建好的定义传递给你的注册表,因此定义绝不能为 null。
6. 平台和注册表
平台标识自身并暴露其注册表。注册表是工作的发生地:它存储定义并将它们连接到你的宿主环境。
public class AcmePlatform implements Platform<AcmeCommandsRegistry> {
private final AcmeCommandsRegistry registry = new AcmeCommandsRegistry(this);
@Override
public String getIdentifier() {
return "acme";
}
@Override
public AcmeCommandsRegistry getCommandsRegistry() {
return registry;
}
}
public class AcmeCommandsRegistry implements CommandsRegistry<AcmePlatform, AcmeCommandDefinition> {
private final AcmePlatform platform;
private final Set<AcmeCommandDefinition> commands = new HashSet<>();
public AcmeCommandsRegistry(AcmePlatform platform) {
this.platform = platform;
}
@Override
public void register(AcmeCommandDefinition definition) {
commands.add(definition);
// 告知主机有关命令的信息(名称、别名、描述等)
}
@Override
public void unregister(AcmeCommandDefinition definition) {
commands.remove(definition);
// 从主机中移除该命令
}
@Override
public @Unmodifiable Set<AcmeCommandDefinition> getRegisteredCommands() {
return Set.copyOf(commands);
}
@Override
public AcmePlatform getPlatform() {
return platform;
}
}
注册表不应自行注册主机事件监听器。请将此留给平台的使用者,就像 Velocity 注册表所做的那样。
7. 分发输入
如果你的主机没有自己的命令系统,Prism 不会自行解析或执行任何内容。当你的主机接收到针对已注册命令的输入时,你的注册表(或其拥有的辅助工具)将执行以下操作:
- 遍历定义树,通过
getChild(...) 匹配子命令名称。
- 检查
definition.canExecute(source),如果失败则报告“无权限”错误。
- 使用每个参数的
parse(source, token) 解析原始令牌,遵循 canUse(source) 的限制,并将值收集到以参数名称为键的两个映射中(分别对应必需和可选参数)。捕获 ArgumentParseException 并将其转换为用户可见的消息。
- 将值封装进
CommandArguments,传入父级的 CommandArguments,以便 getAt("../", "key") 等方法能正常工作。
- 检查
definition.hasExecutor(source),然后对 definition.getExecutors() 中的每个执行器调用 tryInvoke(source, args)。
CommandArguments<AcmeCommandDefinition, AcmeUser> args =
new CommandArguments<>(definition, requiredValues, optionalValues, parentArgs);
if (!definition.hasExecutor(user)) {
user.sendMessage("This command cannot be run here.");
return;
}
definition.getExecutors().forEach(executor -> executor.tryInvoke(user, args));
对于建议项,调用每个参数的 getSuggestionsSupplier().getSuggestions(new SuggestionContext<>(source, currentInput, currentRawArg)),并将结果转换为主机所期望的格式。
8. Brigadier 主机(可选)
如果您的主机已经支持 Brigadier(Minecraft 服务器、Velocity),请跳过第 7 步。实现 BrigadierAdapter<Source, Definition>,并让 BrigadierTreeBuilder 构建命令树、解析层级结构以及连接补全建议。
| Method |
Purpose |
visible(definition, source) |
该源是否完全可见此命令。 |
available(argument, source) |
该源是否可以使用某个参数节点。 |
forcedValues(argument) |
某参数展开的固定值。默认为无。 |
accepts(argument, source, word) |
单个词是否可被解析为该参数。 |
nativeType(argument) |
支撑该参数的 Brigadier ArgumentType,字面量则为 null。 |
tokens(argument) |
该参数消耗多少个输入词。 |
greedy(argument) / literal(argument) |
节点类型。 |
branches(definition) / children(argument) |
命令或参数的 then(...) 树结构。 |
command(...) |
对应定义或其参数树中某路径的 Brigadier Command。 |
suggestions(argument, nativeType) |
该参数的 SuggestionProvider,回退到 nativeType。 |
您的注册表随后将每个定义转换为 Brigadier 节点:
for (String label : adapter.getBuilder().labels(definition)) {
LiteralCommandNode<CommandSource> node = adapter.getBuilder().build(definition, label);
BrigadierCommand command = new BrigadierCommand(node);
CommandMeta meta = manager.metaBuilder(command)
.plugin(platform.getPlugin())
.build();
manager.register(meta, command);
}
阅读 BukkitCommandDefinitionAdapter (platform/brigadier/minecraft) 和 VelocityCommandDefinitionAdapter (platform/velocity) 以获取两个完整的适配器示例。
使用方式
一旦这些组件存在,您平台的使用者将获得与其他人相同的流畅 API:
AcmePlatform platform = new AcmePlatform();
new AcmeCommandBuilder("greet")
.withArguments(new AcmeIntegerArgument("times"))
.executes((user, args) -> {
int times = args.get("times");
user.sendMessage("Hello! ".repeat(times));
})
.register(platform);
提示: 阅读 platform/bukkit 中的 BukkitCommandsRegistry、LegacyCommandRegistrar 和 LegacyArgumentsParser,以查看第 6 步和第 7 步的完整实现,包括选项卡补全、标志位和贪婪参数。
项目结构
Prism 是一个多模块 Gradle 构建:
prism
├── core/ 平台无关的命令模型:构建器、参数、执行器、权限
├── reflection/ 跨平台模块共享的小型反射辅助工具
├── platform/
│ ├── bukkit/ 共享 Bukkit API 层:PrismBukkitCommand、参数、执行器、旧版注册器
│ ├── spigot/ Spigot 平台与注册表
│ ├── paper/ Paper 平台与注册表(异步建议、Paper 原生 Brigadier)
│ ├── velocity/ Velocity 平台与注册表(VelocityCommand、VelocityPermission、Brigadier 适配器)
│ ├── brigadier/ 平台无关的 Brigadier 树构建器与适配器
│ │ └── minecraft/ 面向 Minecraft 的 Brigadier 桥接
│ │ ├── V1_13 … V1_21, V26 各版本适配器
│ │ └── brigadier-paper Paper 原生适配器
│ └── jda/ Discord (JDA) 平台,开发中
├── publish/
│ ├── paper/ 将模块聚合为 `prism-paper` 包
│ └── spigot/ 将模块聚合为 `prism-spigot` 包
├── gradle-plugin/
│ └── spigot-nms/ 用于 Spigot NMS 重新混淆的 Gradle 插件
├── buildSrc/ 共享发布约定
├── plugin/
│ └── bukkit-plugin/ 独立 Prism 插件(`api/` 供依赖项使用,`plugin/` 供 jar 使用)
├── examples/
│ ├── paper-plugin/ Paper 示例插件
│ └── velocity-plugin/ Velocity 示例插件
└── test/plugin/ 用于在真实服务器上测试 API 的 Paper 测试插件
从源代码构建
要求
- 一个 Gradle 可用于工具链的 JDK。库本身针对 Java 17,测试在 Java 21 上运行,而 Paper 测试插件、Velocity 模块和 CI 使用 Java 25。Gradle 的工具链解析器可以自动下载缺失的 JDK。
- 当 Velocity 模块包含在构建中时,Gradle 本身必须在 JDK 25 或更高版本上运行。请在 IDE 中相应地设置 Gradle JVM。
- 无需单独安装 Gradle。请使用随附的包装器。
git clone https://github.com/AthlasStudios/prism.git
cd prism
# 编译所有内容并构建 jars
./gradlew build
# 运行测试套件
./gradlew test
在 Windows 上,请改用 gradlew.bat 代替 ./gradlew。
测试使用 JUnit 配合 MockBukkit。
在服务器上试用
examples 模块是一个示例插件,它使用了大部分 API(子命令、参数树、标志、异步和同步建议以及许多内置参数类型)。启动一个安装了该插件的本地 Paper 服务器:
./gradlew :test:plugin:runServer
若要生成插件 jar,请执行以下操作:
./gradlew :test:plugin:shadowJar
其源代码 TestPlugin.java 同时充当一套便捷的使用示例。
对于 Velocity,examples/velocity-plugin 会启动一个带有最小化插件的本地 Velocity 代理:
./gradlew :examples:velocity-plugin:runVelocity
贡献
欢迎提交贡献、错误报告和建议。
- 打开一个问题 以在开始之前讨论较大的更改。
- Fork 仓库并从
main 创建分支。
- 进行修改,并在适当的地方添加或更新测试。
- 运行
./gradlew test 并确保其通过。CI 会在每次推送和拉取请求时运行相同的检查。
- 打开一个拉取请求,描述更改了什么以及原因。
许可证
Prism 根据 MIT License 发布。
? Prism - THE Command Framework
A code-first command framework that lets you build commands directly in Java with a fluent, type-safe API.
No annotations required.

Documentation · Issues
Table of contents
Why Prism?
Most command frameworks lean on annotations and reflection: you describe a command with a pile of annotations, and the framework figures out the rest at runtime. Prism takes the opposite approach. A command is plain Java code built with a fluent builder, so you get:
- Compile-time safety. Arguments, executors and requirements are real typed objects, not strings buried in annotations.
- Composability. Commands are values. Build them in loops, share argument definitions, and assemble trees programmatically.
- Discoverability. Your IDE's autocomplete is the documentation. Everything hangs off one builder.
- One API, many platforms. The core is platform-agnostic; Spigot, Paper (with native Brigadier support), Velocity and others plug in on top.
new PrismBukkitCommand("heal")
.withDescription("Heal a player")
.withPermission("myplugin.heal")
.withArguments(new PlayerArgument("target"))
.executes((sender, args) -> {
Player target = args.get("target");
target.setHealth(20);
sender.sendMessage("Healed " + target.getName());
})
.register(platform);
Features
- ? Fluent, type-safe builder API with no annotations
- ? Subcommands and argument trees for arbitrarily nested command structures
- ? Rich built-in arguments for players, worlds, materials, locations, entity selectors, ranges, colors, enchantments, potion effects and more
- ? Sync and async tab completion with optional tooltips
- ? Flag support (
-c red -e) via FlagArgument
- ? Permissions and usage requirements at the command and argument level
- ? Per-sender-type executors for players, console, remote console, command blocks and proxied senders
- ⚡ Native Brigadier integration (client-side validation, colored syntax, native suggestions) with an automatic legacy fallback
- ?️ Velocity support built on the same Brigadier tree builder
- ? Built-in help generator that renders clickable usage for a command tree
- ♻️ Runtime registration and unregistration of commands
- ? Shaded bundles so you ship a single dependency
- ? Standalone plugin if you would rather not shade Prism into your jar
Supported platforms
| Platform |
Module |
Status |
| Spigot (and forks) |
prism-spigot |
Supported |
| Paper (and forks) |
prism-paper |
Supported |
| Brigadier (Minecraft 1.13 → 26.x) |
bundled in the Spigot and Paper builds |
Supported |
| Velocity |
platform/velocity |
? Experimental |
| JDA (Discord) |
platform/jda |
? In development |
Prism compiles against the Spigot 1.13.2 API, and the Brigadier layer has per-version adapters for Minecraft 1.13 through 1.21 and 26.x. If Brigadier can't be initialized on your server version, Prism logs a warning and falls back to legacy registration, so commands keep working.
The Velocity module targets Java 25 and the Velocity 4.x API. Velocity has no legacy fallback: commands are always registered through Brigadier.
Installation
Prism is currently in beta (1.0.0-beta.4). APIs may still change between beta releases.
Group ID: dev.gurwi
| Server software |
Artifact ID |
| Paper |
prism-paper |
| Spigot |
prism-spigot |
Each artifact is a self-contained bundle that already includes the core, Bukkit layer and the matching Brigadier adapters, so you only add one dependency.
Gradle (Kotlin DSL)
repositories {
mavenCentral()
}
dependencies {
implementation("dev.gurwi:prism-paper:1.0.0-beta.4")
}
Gradle (Groovy DSL)
repositories {
mavenCentral()
}
dependencies {
implementation 'dev.gurwi:prism-paper:1.0.0-beta.4'
}
Maven
<dependency>
<groupId>dev.gurwi</groupId>
<artifactId>prism-paper</artifactId>
<version>1.0.0-beta.4</version>
</dependency>
Swap prism-paper for prism-spigot if you target Spigot. The individual modules (prism-core, prism-bukkit, prism-brigadier and prism-brigadier-minecraft) are published too, but most projects should use a bundle.
Prism is a library, not a standalone plugin, so shade it into your own plugin jar (for example with the Shadow plugin) and relocate it to avoid conflicts with other plugins that bundle Prism.
Don't want to shade? Install Prism as a standalone plugin instead, see Standalone plugin.
Standalone plugin
Instead of shading Prism into every plugin, you can install it once on the server as a plugin named prism. Your plugins then depend on it, use one shared copy of the library and get their commands registered through the Prism API. This is the Bukkit plugin in plugin/bukkit-plugin, built on the Paper platform.
Install the plugin
- Drop
prism-<version>.jar into the server's plugins folder.
- Start the server once. The plugin creates
plugins/prism/config.yml.
- Add Prism as a dependency of every plugin that uses it.
The plugin also adds a /prism command that shows basic info and links to this repository. It can be turned off in the config.
Use it from your plugin
Declare the dependency in your plugin.yml, so Prism always loads first:
name: MyPlugin
main: com.example.myplugin.MyPlugin
version: 1.0.0
depend: [prism]
Compile against Prism without shading it. The API classes come from the api module, which builds to prism-<version>-API.jar, and the command classes come from the matching Prism module:
dependencies {
compileOnly("dev.gurwi:prism-paper:1.0.0-beta.4")
compileOnly(files("libs/prism-1.0.0-beta.4-API.jar"))
}
Everything is compileOnly: at runtime the classes come from the installed Prism plugin, so there is nothing to shade or relocate.
There are two ways to register commands: let Prism pick them up from a command provider, or use the API and a registry yourself. The registry route comes first.
Get the API through PrismPluginAPI.getAPI(). It returns null when Prism is not installed or has not registered its service yet.
public class MyPlugin extends JavaPlugin {
@Override
public void onEnable() {
PrismPluginAPI api = PrismPluginAPI.getAPI();
if (api == null) {
getLogger().severe("Prism is not installed");
getServer().getPluginManager().disablePlugin(this);
return;
}
BukkitCommandsRegistry<?> registry = api.createRegistry(this);
registry.register(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.build()
);
}
}
Commands are built with the same PrismBukkitCommand API as in the Guide. Instead of .register(platform) you pass the built definition to a registry.
| Method |
Description |
PrismPluginAPI.getAPI() |
The API instance, or null if Prism is missing. |
createRegistry(plugin) |
Creates a registry for your plugin, configured from Prism's config.yml. |
getDefaultRegistry() |
The registry of Prism's own platform, shared by all plugins. |
registerProvider(plugin, provider, registry) |
Registers a command provider. registry may be null. |
getRegistriesManager() |
createRegistry, getRegistry(plugin) and unloadRegistry(plugin). |
Prefer createRegistry(this) so your commands are tracked per plugin.
Command providers
If you only want commands registered, implement PrismCommandProvider on your main class and return them from getCommands(). Prism detects the provider when your plugin enables, builds every command and registers it. There is no registry code in your plugin.
public class MyPlugin extends JavaPlugin implements PrismCommandProvider {
@Override
public Collection<? extends PrismBukkitCommand> getCommands() {
return List.of(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!")),
new PrismBukkitCommand("ping")
.executes((sender, args) -> sender.sendMessage("Pong!"))
);
}
}
Return the builders, not built definitions: Prism calls build() itself.
By default each plugin gets its own registry, created from Prism's config.yml, and its commands are unregistered when the plugin disables. To choose the registry yourself, override getRegistry():
@Override
public BukkitCommandsRegistry<?> getRegistry() {
return PrismPluginAPI.getAPI().getDefaultRegistry();
}
A provider does not have to be your main class. Register any provider by hand with registerProvider:
PrismPluginAPI.getAPI().registerProvider(this, () -> List.of(
new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
), null);
Passing null as the registry uses the provider's getRegistry(), then falls back to a per-plugin registry. Your plugin must still declare depend: [prism]; Prism logs a warning for providers that don't.
Plugin configuration
plugins/prism/config.yml controls how Prism creates its platform and the registries it hands out:
| Option |
Default |
Description |
disableInfoCommand |
false |
Don't register the /prism info command. |
disableBrigadierRegistrar |
false |
Skip Brigadier and register through the legacy system only. |
disableLegacyRegistrar |
false |
Disable the legacy registrar. |
disableAsyncSuggestions |
false |
Don't register the async tab-completion listener. |
registerPermissions |
false |
Register command permissions with the server. |
These map to the options in Platform configuration and apply to every plugin using the standalone Prism.
Quick start
1. Create the platform
Do this once, in onEnable.
Paper
public class MyPlugin extends JavaPlugin {
private PaperPlatform platform;
@Override
public void onEnable() {
this.platform = PaperPlatform.configure(this).init();
}
}
Spigot
public class MyPlugin extends JavaPlugin {
private SpigotPlatform platform;
@Override
public void onEnable() {
this.platform = SpigotPlatform.configure(this).init();
}
}
Velocity is set up differently, see Velocity.
2. Build and register a command
new PrismBukkitCommand("teleport", "tp")
.withDescription("Teleport yourself to a location")
.withPermission("myplugin.teleport")
.withArguments(new LocationArgument("location"))
.executesPlayer((player, args) -> {
Location location = args.get("location");
player.teleport(location);
player.sendMessage("Teleported!");
})
.register(platform);
That's it. The first argument is the command name; any further strings are aliases. Tab completion, argument parsing and error messages come for free.
Guide
The guide uses the Bukkit API (PrismBukkitCommand). The builder methods (withArguments, withOptionalArguments, withSubCommands, then, withPermission, withRequirement, register) are inherited from the platform-agnostic core and work the same on every platform. Only the executors, senders, arguments and permission helpers differ.
Arguments
Required arguments are added with withArguments(...). They are parsed in order, and values are read back by name from the CommandArguments object passed to your executor.
new PrismBukkitCommand("give")
.withArguments(
new PlayerArgument("target"),
new MaterialArgument("material"),
new IntegerArgument("amount", 1, 64)
)
.executes((sender, args) -> {
Player target = args.get("target");
Material material = args.get("material");
int amount = args.get("amount");
target.getInventory().addItem(new ItemStack(material, amount));
})
.register(platform);
args.get(...) is generic, so the target type is inferred from the variable you assign it to. You can also pass the argument object itself instead of its name:
IntegerArgument amount = new IntegerArgument("amount", 1, 64);
// ...
int value = args.get(amount);
Optional arguments
Optional arguments are declared with withOptionalArguments(...) and always come after the required ones.
new PrismBukkitCommand("number")
.withArguments(new IntegerArgument("number", 0, 10))
.withOptionalArguments(new FloatArgument("float", 0.1f, 9.9f))
.executes((sender, args) -> {
int number = args.get("number");
float scale = args.getOptional("float", 1.0f); // with a default
sender.sendMessage(number + " x " + scale);
})
.register(platform);
getOptional(key) returns an Optional<T>, and getOptional(key, defaultValue) returns the value or your default.
Subcommands
Nest commands with withSubCommands(...). A subcommand is just another PrismBukkitCommand.
new PrismBukkitCommand("team", "t")
.withDescription("Team management")
.withSubCommands(
new PrismBukkitCommand("create")
.withArguments(new StringArgument("name"))
.executes((sender, args) -> {
sender.sendMessage("Created team " + args.get("name"));
}),
new PrismBukkitCommand("join")
.withArguments(new StringArgument("name"))
.executesPlayer((player, args) -> {
player.sendMessage("Joined team " + args.get("name"));
})
)
.register(platform);
A subcommand can read arguments from its parents by path, using getAt with a ../-style path:
new PrismBukkitCommand("paint")
.withArguments(new ColorArgument("color"))
.withSubCommands(
new PrismBukkitCommand("call")
.executes((sender, args) -> {
// Read "color" from the parent command
sender.sendMessage("Color: " + args.getAt("../", "color"));
})
)
.register(platform);
CommandArguments also exposes the definition chain (getParent(), getRoot(), getChain(), getChildDefinitions()) if you need to inspect where you are in the tree.
Argument trees
When a command needs different follow-up arguments depending on the path taken, use then(...). Each branch can carry its own executor.
new PrismBukkitCommand("prism", "pri")
.withArguments(new ItemStackPredicateArgument("predicate"))
.then(
new MaterialArgument("material")
.executes((sender, args) -> {
Material material = args.get("material");
sender.sendMessage("Selected material " + material);
})
)
.then(
new GameModeArgument("gamemode")
.executes((sender, args) -> {
GameMode gameMode = args.get("gamemode");
sender.sendMessage("Selected game mode " + gameMode);
})
)
.register(platform);
Branches can be nested further by calling .then(...) on an argument. Argument names must be unique among siblings, and Prism throws an IllegalArgumentException if you reuse one or try to add an argument beneath itself.
Arguments that are not listed (setListed(false), as LiteralArgument is) are matched but never stored in CommandArguments.
Executors and senders
Pick the executor that matches who may run the command. Prism only invokes the executor that fits the sender, so you don't need instanceof checks.
| Method |
Sender type |
executes(...) |
Any CommandSender |
executesPlayer(...) |
Player |
executesConsole(...) |
ConsoleCommandSender |
executesRemoteConsole(...) |
RemoteConsoleCommandSender |
executesProxy(...) |
ProxiedCommandSender |
executesBlock(...) |
BlockCommandSender |
You can register several executors on the same command, one per sender type:
new PrismBukkitCommand("whoami")
.executesPlayer((player, args) -> player.sendMessage("You are " + player.getName()))
.executesConsole((console, args) -> console.sendMessage("You are the console"))
.register(platform);
Use clearExecutors() to remove all executors from a builder.
A sender that has no matching executor gets "This command cannot be run by this sender" on Brigadier platforms, and the command is hidden from its suggestions.
Permissions and requirements
Permissions are checked against the sender (operators always pass on Bukkit platforms):
new PrismBukkitCommand("admin")
.withPermission("myplugin.admin", "myplugin.staff")
// ...
For wildcard-style checks, BukkitPermission.startsWith("myplugin.") matches any effective permission with that prefix. Velocity has no equivalent, see Velocity permissions.
Requirements are arbitrary predicates on the sender. Sender-specific shortcuts are available:
new PrismBukkitCommand("fly")
.withPlayerRequirement(player -> player.getWorld().getName().equals("lobby"))
.executesPlayer((player, args) -> player.setAllowFlight(true))
.register(platform);
Available helpers: withRequirement, withPlayerRequirement, withConsoleRequirement, withRemoteConsoleRequirement, withProxyRequirement and withBlockRequirement. Requirements can also be attached to individual arguments with withRequirement(...), and arguments can be hidden from listings with setListed(false).
Suggestions and tab completion
Every built-in argument ships with sensible default suggestions. Replace them with replaceSuggestions(...).
Static strings
new IntegerArgument("number", 0, 10).replaceSuggestions("5", "10");
Synchronous, computed suggestions (with tooltips)
new StringArgument("kit").replaceSuggestions(
BukkitSuggestionsSupplier.sync(ctx -> List.of(
ArgumentSuggestion.of("starter", "The default starter kit"),
ArgumentSuggestion.of("vip", "Perks for VIP players")
))
);
Asynchronous suggestions (for database or network lookups) return a CompletableFuture:
new StringArgument("player").replaceSuggestions(
BukkitSuggestionsSupplier.async(ctx -> CompletableFuture.supplyAsync(() ->
List.of(ArgumentSuggestion.of("alpha", "first async value"))
))
);
The SuggestionContext passed in gives you access to the current raw input (ctx.getCurrentRawArg()) so you can filter results. Helpers BukkitSuggestionsSupplier.strings(...) and stringsAsync(...) cover the plain-string cases.
On Brigadier platforms Prism also filters suggestions by the text already typed (case-insensitive prefix match), so suppliers can return their full list.
On Paper, async suggestions are handled through a dedicated listener. You can turn this off with disableAsyncSuggestions() (see Platform configuration).
Flags
FlagArgument parses -x-style flags in any order. Flags can carry a value (using any other argument type) or act as simple on/off switches.
new PrismBukkitCommand("flagger")
.withArguments(
new FlagArgument("flags").flags(
Flag.valued(new ColorArgument("color"), 'c'),
Flag.presence("enable", 'e')
)
)
.executesPlayer((player, args) -> {
ParsedFlags flags = args.get("flags");
Optional<ChatColor> color = flags.get("color");
color.ifPresent(c -> player.sendMessage("Color: " + c.name()));
})
.register(platform);
Built-in help
CommandHelp renders a clickable usage list for the current command, including its subcommands and argument-tree branches. It only shows entries the sender is actually allowed to run.
new PrismBukkitCommand("myplugin")
.withSubCommands(/* ... */)
.executesPlayer((player, args) -> CommandHelp.help(player, args))
.register(platform);
Pass two extra ChatColor values to CommandHelp.help(sender, args, primary, secondary) to restyle it.
Registering and unregistering
A command can be registered in two equivalent ways:
// 1. Directly from the builder
BukkitCommandDefinition definition = new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.register(platform);
// 2. Build first, register later
BukkitCommandDefinition built = new PrismBukkitCommand("hello")
.executes((sender, args) -> sender.sendMessage("Hello!"))
.build();
platform.getCommandsRegistry().register(built);
platform.getCommandsRegistry().unregister(built);
getRegisteredCommands() returns an unmodifiable view of everything registered on the platform.
Velocity
The Velocity platform (platform/velocity) reuses the core builder and the Brigadier tree builder, so commands, subcommands, argument trees, optional arguments and suggestions work as described in the guide. The command class is VelocityCommand, and the sender is Velocity's CommandSource.
Setup
Create the platform in your plugin constructor and register commands from your ProxyInitializeEvent handler or later.
@Plugin(id = "my-plugin")
public class MyPlugin {
private final ProxyServer server;
private final VelocityPlatform platform;
@Inject
public MyPlugin(ProxyServer server) {
this.server = server;
this.platform = VelocityPlatform.configure(this, server).init();
}
@Subscribe
public void onProxyInit(ProxyInitializeEvent event) {
new VelocityCommand("hello")
.executes((source, args) -> {
source.sendPlainMessage("Hello World!");
})
.register(platform);
}
}
VelocityPlatform.configure(plugin, server) takes your plugin instance as a plain Object. Velocity has no plugin handle: @Plugin is an annotation, and the instance of your main class is the plugin.
- Prism does not register any Velocity event listener.
register(...) talks to Velocity's CommandManager immediately, so calling it before ProxyInitializeEvent is your responsibility to avoid.
- Velocity injects the SLF4J
Logger, not java.util.logging.Logger.
Permissions
Velocity has no operator system, so there is no OP permission. Permissions go through CommandSource#hasPermission, and ConsoleCommandSource always passes.
VelocityPermission.of("myplugin.admin");
VelocityPermission.of("myplugin.admin", "myplugin.staff");
Without a permission plugin such as LuckPerms, Velocity's default provider returns true for every hasPermission call, so any player passes any permission check. Don't rely on permissions for anything sensitive unless a permission plugin is installed.
Velocity cannot enumerate the permissions a source holds, so a prefix check works against a known set of nodes instead of the sender's effective permissions:
VelocityPermission.startsWith("myplugin.admin.", knownPermissions);
knownPermissions is the collection of nodes your commands declare. Only nodes in that collection are tested, and each one is checked with hasPermission. Use the LuckPerms API directly if you need to match arbitrary nodes at runtime.
Differences from Bukkit
| Topic |
Bukkit platforms |
Velocity |
| Command class |
PrismBukkitCommand |
VelocityCommand |
| Sender |
CommandSender |
CommandSource |
| Plugin handle |
JavaPlugin |
Object (your plugin instance) |
| Registration timing |
onEnable |
ProxyInitializeEvent or later |
| Operators |
Always pass permission checks |
No operator concept |
startsWith permission |
Matches effective permissions |
Matches a supplied set of known nodes |
| Brigadier fallback |
Legacy registrar |
None, Brigadier only |
| Suggestion tooltips |
LiteralMessage |
VelocityBrigadierMessage |
Platform configuration
Both PaperPlatform.configure(plugin) and SpigotPlatform.configure(plugin) return a builder. Finish with .init(). VelocityPlatform.configure(plugin, server) works the same way.
| Option |
Platform |
Description |
disableBrigadier() |
Paper, Spigot |
Skip Brigadier and register through the legacy command system only. |
disableLegacyRegistrar() |
Paper, Spigot |
Disable the legacy registrar. |
disableAsyncSuggestions() |
Paper |
Don't register the async tab-completion listener. |
registerPermissions(boolean) |
Paper, Spigot |
Toggle command permission registration. Defaults to true. |
withGlobalLegacyCommandErrorHandler(handler) |
Paper, Spigot |
Set the default handler for argument-parse errors on legacy-registered commands. |
PaperPlatform platform = PaperPlatform.configure(this)
.disableAsyncSuggestions()
.registerPermissions(false)
.init();
Individual commands can override the error handler with replaceErrorHandler(...). Prism ships LegacyCommandExecutionErrorHandler.defaultHandler() and consoleHandler(), and you can implement the interface yourself.
Built-in argument types
All of these live in dev.gurwi.prism.bukkit.argument.
| Category |
Arguments |
| Primitives |
StringArgument, GreedyStringArgument, MultiStringArgument, CharacterArgument, BooleanArgument, ByteArgument, ShortArgument, IntegerArgument, LongArgument, FloatArgument, DoubleArgument, UUIDArgument |
| Ranges |
ByteRangeArgument, ShortRangeArgument, IntegerRangeArgument, LongRangeArgument, FloatRangeArgument, DoubleRangeArgument, NumberRangeArgument |
| Players and entities |
PlayerArgument, OfflinePlayerArgument, EntityTypeArgument, EntitySelectorArgument (e.g. ManyEntities) |
| World and position |
WorldArgument, LocationArgument, ColumnLocationArgument, BlockPositionArgument, ColumnBlockPositionArgument, VectorArgument, RotationArgument, AngleArgument, AxesArgument |
| Blocks and items |
MaterialArgument, BlockStateArgument, BlockPredicateArgument, ItemStackPredicateArgument, EnchantmentArgument |
| Game enums and registries |
GameModeArgument, DifficultyArgument, WeatherArgument, BiomeArgument, PotionEffectTypeArgument, ParticleArgument, SoundArgument, DisplaySlotArgument, NamespacedKeyArgument, MirrorArgument, StructureRotationArgument, EnumArgument |
| Text and color |
ColorArgument, HexColorArgument, MessageArgument, TimeArgument |
| Structure |
LiteralArgument, FlagArgument |
Velocity arguments live in dev.gurwi.prism.velocity.argument and extend VelocityArgument. Each one wraps a Brigadier ArgumentType.
Need something custom? Extend BukkitArgument (or VelocityArgument on Velocity, or one of the base argument classes) and implement parse(...), and optionally provide default suggestions.
Greedy arguments must be the last argument of a command and cannot have children.
Implementing your own platform
core knows nothing about Minecraft, Discord or any other host. A platform is a thin layer that supplies six things on top of it, and everything else (the fluent builder, argument trees, subcommands, requirements, CommandArguments) comes for free. The platform/bukkit module is the full-featured reference, platform/velocity is a compact Brigadier-only reference, and platform/jda is a minimal skeleton that follows the same layout.
Add the core module (it is published on its own):
dependencies {
api("dev.gurwi:prism-core:1.0.0-beta.4")
}
The examples below use an imaginary chat service where the command source is an AcmeUser.
1. Executor
An executor is a functional interface over your source type and your definition type.
@FunctionalInterface
public interface AcmeExecutor extends CommandExecutor<AcmeUser, AcmeCommandDefinition> {
}
If your host has several kinds of senders (like Bukkit's player, console and command block), declare one executor interface per kind and register them under their own class, as BukkitExecutorContainerBuilder does.
2. Permissions
Implement PermissionNode<Permission, Source>. permission() returns your host's native permission value, and hasPermission(...) answers for a given source.
public record AcmePermission(String node) implements PermissionNode<String, AcmeUser> {
@Override
public String permission() {
return node;
}
@Override
public boolean hasPermission(AcmeUser user) {
return user.hasPermission(node);
}
}
3. Arguments and suggestions
Extend AbstractArgument with your source type and a SuggestionsSupplier. The one method you must implement is parse. Throw ArgumentParseException for invalid input.
@FunctionalInterface
public interface AcmeSuggestions<T> extends SuggestionsSupplier<AcmeUser, Collection<T>> {
}
public abstract class AcmeArgument<Impl extends AcmeArgument<Impl, T>, T>
extends AbstractArgument<Impl, T, AcmeUser, AcmeSuggestions<T>> {
public AcmeArgument(String name, AcmeSuggestions<T> defaultSuggestions) {
super(name, defaultSuggestions);
}
}
public class AcmeIntegerArgument extends AcmeArgument<AcmeIntegerArgument, Integer> {
public AcmeIntegerArgument(String name) {
super(name, ctx -> List.of());
}
@Override
public Integer parse(AcmeUser source, String value) throws ArgumentParseException {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ArgumentParseException(this, value, "'" + value + "' is not a number");
}
}
}
If you want then(...) argument trees on your platform, extend AbstractTreeArgument instead and AbstractTreeCommandBuilder / AbstractTreeCommandDefinition in the next steps (this is what the Bukkit module does).
Arguments also expose canUse(source), which a platform must honour, and isListed(), which decides whether a parsed value is stored in CommandArguments.
4. Command definition
The definition is the immutable, built form of a command. Subclass AbstractCommandDefinition and bind its type parameters (self type, source, executor, argument, permission). The builder is the only thing that constructs it.
public class AcmeCommandDefinition extends AbstractCommandDefinition<
AcmeCommandDefinition, AcmeUser, AcmeExecutor, AcmeArgument<?, ?>, AcmePermission> {
protected AcmeCommandDefinition(@Nullable AcmeCommandDefinition parent, String name, List<String> aliases,
String description, UsageRequirement<AcmeUser> requirement,
Set<AcmePermission> permissions,
List<AcmeArgument<?, ?>> requiredArguments,
List<AcmeArgument<?, ?>> optionalArguments,
Map<Class<? extends AcmeExecutor>, AcmeExecutor> executors,
CommandChildrenFactory<AcmeCommandDefinition> childrenFactory) {
super(parent, name, aliases, description, requirement, permissions,
requiredArguments, optionalArguments, executors, childrenFactory);
}
}
The base class already gives you getName(), getAliases(), getChildren(), getChild(name), getParent(), getExecutors(), hasExecutor(source) and canExecute(source) (requirement plus all permissions).
5. Builder
Extend AbstractCommandBuilder, implement build(parent), and add whatever convenience methods your executors need.
public class AcmeCommandBuilder extends AbstractCommandBuilder<
AcmeCommandBuilder, AcmeCommandDefinition, AcmeUser, AcmeExecutor, AcmeArgument<?, ?>, AcmePermission> {
public AcmeCommandBuilder(String name, String... aliases) {
super(name, aliases);
}
public AcmeCommandBuilder executes(AcmeExecutor executor) {
return executes(AcmeExecutor.class, executor);
}
@Override
public AcmeCommandDefinition build(@Nullable AcmeCommandDefinition parent) {
return new AcmeCommandDefinition(parent, name, aliases, description, requirement, permissions,
requiredArguments, optionalArguments, executors, CommandChildrenFactory.create(children));
}
}
withDescription, withArguments, withOptionalArguments, withPermission, withRequirement, withSubCommands and register(...) are all inherited. register(...) passes the built definition to your registry, so the definition must never be null.
6. Platform and registry
The platform identifies itself and exposes its registry. The registry is where the work happens: it stores definitions and connects them to your host.
public class AcmePlatform implements Platform<AcmeCommandsRegistry> {
private final AcmeCommandsRegistry registry = new AcmeCommandsRegistry(this);
@Override
public String getIdentifier() {
return "acme";
}
@Override
public AcmeCommandsRegistry getCommandsRegistry() {
return registry;
}
}
public class AcmeCommandsRegistry implements CommandsRegistry<AcmePlatform, AcmeCommandDefinition> {
private final AcmePlatform platform;
private final Set<AcmeCommandDefinition> commands = new HashSet<>();
public AcmeCommandsRegistry(AcmePlatform platform) {
this.platform = platform;
}
@Override
public void register(AcmeCommandDefinition definition) {
commands.add(definition);
// Tell your host about the command (name, aliases, description, ...)
}
@Override
public void unregister(AcmeCommandDefinition definition) {
commands.remove(definition);
// Remove it from your host
}
@Override
public @Unmodifiable Set<AcmeCommandDefinition> getRegisteredCommands() {
return Set.copyOf(commands);
}
@Override
public AcmePlatform getPlatform() {
return platform;
}
}
A registry should not register host event listeners on its own. Leave that to the user of your platform, as the Velocity registry does.
7. Dispatching input
If your host has no command system of its own, Prism does not parse or run anything by itself. When your host receives input for a registered command, your registry (or a helper it owns) does the following:
- Walk the definition tree, matching subcommand names with
getChild(...).
- Check
definition.canExecute(source) and report a "no permission" error if it fails.
- Parse the raw tokens with each argument's
parse(source, token), honouring canUse(source), and collect the values into two maps keyed by argument name (required and optional). Catch ArgumentParseException and turn it into a user-facing message.
- Wrap the values in a
CommandArguments, passing the parent's CommandArguments so that getAt("../", "key") and friends work.
- Check
definition.hasExecutor(source), then call tryInvoke(source, args) on each executor from definition.getExecutors().
CommandArguments<AcmeCommandDefinition, AcmeUser> args =
new CommandArguments<>(definition, requiredValues, optionalValues, parentArgs);
if (!definition.hasExecutor(user)) {
user.sendMessage("This command cannot be run here.");
return;
}
definition.getExecutors().forEach(executor -> executor.tryInvoke(user, args));
For suggestions, call each argument's getSuggestionsSupplier().getSuggestions(new SuggestionContext<>(source, currentInput, currentRawArg)) and translate the result into whatever your host expects.
8. Brigadier hosts (optional)
If your host already speaks Brigadier (Minecraft servers, Velocity), skip step 7. Implement BrigadierAdapter<Source, Definition> and let BrigadierTreeBuilder build the command tree, parse the hierarchy and wire up suggestions.
| Method |
Purpose |
visible(definition, source) |
Whether the source may see the command at all. |
available(argument, source) |
Whether the source may use an argument node. |
forcedValues(argument) |
Fixed values an argument expands to. Defaults to none. |
accepts(argument, source, word) |
Whether a single word parses for the argument. |
nativeType(argument) |
The Brigadier ArgumentType backing the argument, or null for literals. |
tokens(argument) |
How many input words the argument consumes. |
greedy(argument) / literal(argument) |
Node kind. |
branches(definition) / children(argument) |
The then(...) tree of a command or an argument. |
command(...) |
The Brigadier Command for a definition or a path inside its argument tree. |
suggestions(argument, nativeType) |
The SuggestionProvider for an argument, falling back to nativeType. |
Your registry then turns each definition into Brigadier nodes:
for (String label : adapter.getBuilder().labels(definition)) {
LiteralCommandNode<CommandSource> node = adapter.getBuilder().build(definition, label);
BrigadierCommand command = new BrigadierCommand(node);
CommandMeta meta = manager.metaBuilder(command)
.plugin(platform.getPlugin())
.build();
manager.register(meta, command);
}
Read BukkitCommandDefinitionAdapter (platform/brigadier/minecraft) and VelocityCommandDefinitionAdapter (platform/velocity) for two complete adapters.
Using it
Once those pieces exist, users of your platform get the same fluent API as everyone else:
AcmePlatform platform = new AcmePlatform();
new AcmeCommandBuilder("greet")
.withArguments(new AcmeIntegerArgument("times"))
.executes((user, args) -> {
int times = args.get("times");
user.sendMessage("Hello! ".repeat(times));
})
.register(platform);
Tip: read BukkitCommandsRegistry, LegacyCommandRegistrar and LegacyArgumentsParser in platform/bukkit to see a complete implementation of steps 6 and 7, including tab completion, flags and greedy arguments.
Project structure
Prism is a multi-module Gradle build:
prism
├── core/ Platform-agnostic command model: builders, arguments, executors, permissions
├── reflection/ Small reflection helpers shared across platform modules
├── platform/
│ ├── bukkit/ Shared Bukkit API layer: PrismBukkitCommand, arguments, executors, legacy registrar
│ ├── spigot/ Spigot platform and registry
│ ├── paper/ Paper platform and registry (async suggestions, Paper-native Brigadier)
│ ├── velocity/ Velocity platform and registry (VelocityCommand, VelocityPermission, Brigadier adapter)
│ ├── brigadier/ Platform-independent Brigadier tree builder and adapter
│ │ └── minecraft/ Minecraft-facing Brigadier bridge
│ │ ├── V1_13 … V1_21, V26 Per-version adapters
│ │ └── brigadier-paper Paper-native adapter
│ └── jda/ Discord (JDA) platform, in development
├── publish/
│ ├── paper/ Aggregates modules into the `prism-paper` bundle
│ └── spigot/ Aggregates modules into the `prism-spigot` bundle
├── gradle-plugin/
│ └── spigot-nms/ Gradle plugin for Spigot NMS reobfuscation
├── buildSrc/ Shared publishing conventions
├── plugin/
│ └── bukkit-plugin/ Standalone Prism plugin (`api/` for dependents, `plugin/` for the jar)
├── examples/
│ ├── paper-plugin/ Paper example plugin
│ └── velocity-plugin/ Velocity example plugin
└── test/plugin/ Paper test plugin used to exercise the API on a live server
Building from source
Requirements
- A JDK that Gradle can use for toolchains. The library itself targets Java 17, tests run on Java 21, and the Paper test plugin, the Velocity module and CI use Java 25. Gradle's toolchain resolver can download missing JDKs automatically.
- Gradle itself must run on JDK 25 or newer while the Velocity module is part of the build. Set the Gradle JVM in your IDE accordingly.
- No separate Gradle install is needed. Use the included wrapper.
git clone https://github.com/AthlasStudios/prism.git
cd prism
# Compile everything and build the jars
./gradlew build
# Run the test suite
./gradlew test
On Windows, use gradlew.bat instead of ./gradlew.
Tests use JUnit with MockBukkit.
Trying it out on a server
The examples module is a sample plugin that exercises most of the API (subcommands, argument trees, flags, async and sync suggestions, and many built-in argument types). Start a local Paper server with it installed:
./gradlew :test:plugin:runServer
To produce the plugin jar instead:
./gradlew :test:plugin:shadowJar
Its source, TestPlugin.java, doubles as a handy set of usage examples.
For Velocity, examples/velocity-plugin starts a local Velocity proxy with a minimal plugin:
./gradlew :examples:velocity-plugin:runVelocity
Contributing
Contributions, bug reports and ideas are welcome.
- Open an issue to discuss larger changes before starting.
- Fork the repository and create a branch from
main.
- Make your change and add or update tests where it makes sense.
- Run
./gradlew test and make sure it passes. The same check runs in CI on every push and pull request.
- Open a pull request describing what changed and why.
License
Prism is released under the MIT License.
评论 0
登录后参与评分
还没有评论,来抢沙发吧