DialogAPI

插件

· 作者 AlepandoCR

DialogAPI 是一个面向开发者的 API,用于轻松测试和扩展 Minecraft 的新原生对话框。

0 本站下载 0 关注 更新于 1 年前

最新 1.0.8 · 1.21.6 · Paper

一键开服(送7天)

DialogAPI – Minecraft 1.21.6 自定义对话框 API

JitPack

DialogAPI 是一个面向开发者的 API,用于轻松测试和扩展 Minecraft 原生新对话框(1.21.6),特别是利用 ServerboundCustomClickActionPacket。它为 Paper 插件提供了完整的 Kotlin 封装,用于创建带有按钮、输入框和自定义操作的丰富交互式对话框。

❗ 注意: 此 API 主要作为开发者工具使用。虽然功能完备,但不保证会持续维护以支持未来的 Minecraft 版本。欢迎 Fork、改编并在此基础上构建你自己的功能。

⚠️ 重要提示: PaperMC 正在开发其官方的对话框 API。虽然 DialogAPI 目前很有用,但对于长期项目,开发者应关注 Paper 的原生解决方案,因为它很可能成为标准。


目录


✨ 功能

  • 采用 Kotlin 优先的构建器模式,使对话框创建直观易懂。
  • 支持所有原版对话框类型:MultiAction、List、Links、Notice。
  • 通过 Mojang 原生的 ServerboundCustomClickActionPacket 系统实现自定义操作。
  • 强大的输入读取功能:文本、数字(包括范围)、多行文本、布尔切换和单选选项。
  • 灵活的对话框主体:纯文本消息和项目展示。
  • 与 Paper 事件和插件生命周期轻松集成。

? 使用方法

? 添加 API

要将 DialogAPI 添加到你的项目中,请在你的 build.gradle.kts(或 Maven 或 Gradle Groovy 等其他构建系统的等效文件)中包含以下内容:

repositories {
    maven("https://jitpack.io") 
}

dependencies {
    implementation("com.github.AlepandoCR:DialogAPI:v1.1.1") 
}

? 提示: 请始终查看 JitPack 或 GitHub Releases 页面 以获取最新版本号。

? API 初始化

在你的插件的 onEnable 方法中调用此函数,以初始化 API 内部结构并注册所需的包监听器。这将启用 CustomActions 和 InputReaders 等功能,这些功能依赖于包级别的数据。

⚠️ 关键步骤: 如果你不调用 DialogApi.initialize(this),对话框仍然可以正常打开和渲染,但按钮操作 (CustomAction) 和输入字段处理 (InputReader) 等核心功能将无法工作。

// In your main plugin class
override fun onEnable() {
    // Initialize DialogAPI, passing your plugin instance
    DialogApi.initialize(this) 
    
    // Your other onEnable logic...
    logger.info("MyPlugin has been enabled and DialogAPI is initialized!")
}

?️ 构建简单对话框

本节将指导你创建一个包含标题、主体和按钮的基本对话框。

? 对话框数据

首先,使用 DialogDataBuilder 定义对话框的核心数据:

val dialogData = DialogDataBuilder()
    .title(Component.text("Test Menu")) // 显示在对话框窗口顶部的标题
    .externalTitle(Component.text("Menu Test")) // 打开对话框时在服务器日志中显示的标题(对调试有用)
    .canCloseWithEscape(true) // 允许玩家使用 ESC 键关闭对话框
    .afterAction(DialogAction.CLOSE) // 对话框关闭或按钮点击后的操作(默认:CLOSE,可设置为 KEEP_OPEN)
    .addBody(
        PlainMessageDialogBody( // 简单的文本主体部分
            100, // 此主体部分的高度
            Component.text("Hello from DialogAPI! This is a basic dialog example.")
        )
    )
    // 如有需要,你可以添加更多主体部分,例如 ItemDialogBody
    .build()

? DialogDataBuilder 新功能:

  • .afterAction(DialogAction.KEEP_OPEN):指示对话框在按钮的 CustomAction 执行后尝试保持打开状态。默认为 DialogAction.CLOSE。这对于需要自我更新或具有多个步骤的对话框非常有用。

?️ 对话框主体类型

对话框可以包含不同类型的主体内容。你使用 DialogDataBuilder().addBody(...) 来添加它们。

纯文本消息主体

这是最简单的文本主体,在前面的示例中已经展示过。

.addBody(PlainMessageDialogBody(100, Component.text("Your message here.")))

物品展示主体 (ItemDialogBody)

你可以在对话框中展示 Minecraft 物品,包括其名称、描述、附魔以及可选的说明文字。

// --- Example: Using ItemDialogBody ---
// First, prepare your ItemStack
val diamondSword = ItemStack(Material.DIAMOND_SWORD)

// 现在,创建 ItemDialogBody
val itemBody = ItemDialogBodyBuilder()
    .width(200) // 在对话框布局中为此身体部分分配的宽度
    .height(100) // 为此身体部分分配的高度
    .item(diamondSword) // 要显示的 ItemStack
    .showDecorations(true) // 显示附魔光泽等(默认值:true)
    .showTooltip(true) // 悬停时显示物品名称、描述和附魔信息(默认值:true)
    .description("This is a special item found deep within the Obsidian Caves. It is said to possess immense power.", 180) // 可选的文本描述,显示在物品附近,以及该描述的宽度。
    .build()

// 将其添加到你的 DialogData 中
val itemShowcaseData = DialogDataBuilder()
    .title(Component.text("Item Showcase"))
    .addBody(itemBody) // 添加 ItemDialogBody
    .addBody(PlainMessageDialogBody(50, Component.text("What will you do with it?"))) // 你可以混合使用不同类型的 Body
    // ... 添加按钮或其他输入 ...
    .build()

// 然后,将此 DialogData 与对话框构建器一起使用(例如 MultiActionDialogBuilder)
val keyedAction = KeyedAction(ResourceLocation("key", "close_dialog_action")) // 你也可以添加一个可选的 DataContainer
val exitButton = Button(ButtonDataBuilder().label(Component.text("Close")).width(80).build(), Optional.of(keyedAction))
val itemShowcaseDialog = MultiActionDialogBuilder()
    .data(itemShowcaseData)
    .addButton(exitButton)
    .columns(1)
    .build()

player.openDialog(itemShowcaseDialog)

? 添加带有动作的按钮

接下来,创建按钮并将动作与它们关联。当点击按钮时会触发这些动作。KeyedAction 将按钮链接到已注册的 CustomAction。

// 定义自定义动作键(命名空间和路径)
val customActionNamespace = "key" // 可以是你的插件名称或任何键 
val customActionPath = "custom_action"
val resourceLocation = ResourceLocation(customActionNamespace, customActionPath)

// 创建带有相关动作的按钮
val testButton = Button(
    ButtonDataBuilder()
        .label(Component.text("Click Me!"))
        .width(100) // 按钮的宽度
        .build(),
    Optional.of(KeyedAction(resourceLocation)) // 将按钮与自定义动作关联
)

ℹ️ 注意: 要使此按钮生效,你需要注册一个具有上述 resourceLocation 的 CustomAction。详细信息请参阅 Registering an Action 部分。

? 创建对话框

现在,使用特定的对话框类型构建器来组装对话框(例如,对于包含多个按钮的对话框,使用 MultiActionDialogBuilder)。

// 假设 'exitButton' 已在别处定义(例如,用于关闭对话框的按钮)
// val exitButton = ...

val dialog = MultiActionDialogBuilder() // 根据你的对话框类型使用适当的构建器
    .data(dialogData) // 设置核心对话框数据
    .columns(1) // 按钮布局的列数
    .exitButton(exitButton) // 可选:专用的退出按钮
    .addButton(testButton) // 添加你的自定义按钮
    .build()

? 提示: DialogAPI 支持各种对话框类型,如 ListDialog、LinksDialog 和 NoticeDialog。选择最适合你需求的构建器。

? 打开对话框

打开对话框的方法取决于你使用的是 Kotlin 还是 Java:

Kotlin

如果你使用 Kotlin 编码,请使用提供的扩展函数:

player.openDialog(dialog)

Java

如果你使用 Java,请使用工具方法:

PlayerOpener.INSTANCE.openDialog(player, dialog);

ℹ️ 这两种方法在底层的工作方式相同——请根据你选择的语言使用相应的方法。


更多对话框类型

DialogAPI 提供了多种专门的对话框类型,超出了灵活的 MultiActionDialog 的范围。

Notice Dialog

NoticeDialog 是一种简单的对话框,用于显示一条消息和一个确认按钮。

// --- 示例:创建 Notice Dialog ---
val noticeData = DialogDataBuilder()
    .title(Component.text("Important Notice!"))
    .addBody(PlainMessageDialogBody(100, Component.text("Server restarting in 5 minutes.")))
    .build()

val noticeOkButton = Button(
    ButtonDataBuilder().label(Component.text("OK")).width(80).build(),
    Optional.of(KeyedAction(ResourceLocation("key", "action_path")))
)

val noticeDialog = NoticeDialogBuilder()
    .data(noticeData)
    .button(noticeOkButton)
    .build()

player.openDialog(noticeDialog)

Confirmation Dialog

ConfirmationDialog 向用户提供二元选择,通常是“是”和“否”按钮,用于确认操作。

// --- 示例:创建 Confirmation Dialog ---
val confirmData = DialogDataBuilder()
    .title(Component.text("Confirm Purchase"))
    .addBody(PlainMessageDialogBody(120, Component.text("Are you sure you want to buy the Legendary Sword for 1000 Gems?")))
    .externalTitle(Component.text("Player Purchase Confirmation"))
    .build()


val yesButton = Button(
    ButtonDataBuilder().label(Component.text("Yes, Buy It!")).width(100).build(),
    Optional.of(KeyedAction(ResourceLocation("key", "confirm_action_path")))
)
val noButton = Button(
    ButtonDataBuilder().label(Component.text("No, Cancel")).width(100).build(),
    Optional.of(KeyedAction(ResourceLocation("key", "cancel_action_path")))
)

val confirmationDialog = ConfirmationDialogBuilder()
    .data(confirmData)
    .yesButton(yesButton) 
    .noButton(noButton)
    .build()

player.openDialog(confirmationDialog)

高级对话框类型

DialogAPI 还支持更专门的对话框类型,以应对高级用例:

  • LinksDialog:

    • 此对话框类型的用法更为高级,可能需要对 API 和原始 NMS 类有深入的理解。
  • ListDialog:

    • 允许你将其他对话框以列表形式显示为可选项。点击某个选项将打开对应的子对话框。
    • 这对于创建嵌套菜单结构非常有用。
    • 这是一个高级功能,需要你提供 API Dialog 的实例。

创建自定义操作

自定义操作是交互式对话框的核心。它们允许你在玩家与对话框元素(例如点击按钮)交互时执行特定的服务端逻辑。

注册操作

首先,你需要使用唯一的 ResourceLocation 键来注册你的自定义操作。这个键至关重要,因为它将客户端的对话框交互(如按钮点击)链接到你服务端的 CustomAction 实现。

val killPlayerNamespace = "dialog" // 示例命名空间
val killPlayerPath = "damage_player" // 示例路径
val killPlayerKey = ResourceLocation(killPlayerNamespace, killPlayerPath)

try {
    CustomKeyRegistry.register(
        killPlayerKey,        // 此操作的唯一键
        KillPlayerAction,     // 你的 CustomAction 实现(见下文)
        PlayerReturnValueReader // 你的 InputReader 实现;你也可以在不注册 Reader 的情况下注册操作,尽管这样可能无法稍后将该 Reader 注册到相同的键上
    )
} catch (e: IllegalStateException) {
    // 处理键可能已被注册的情况
    // 这条消息在开发期间用于调试非常有用
    player.sendMessage("注意:杀死玩家键已被注册,可能是由插件的其他部分或另一个插件注册的:${e.message}")
}

? 最佳实践: 在插件的 onEnable 阶段注册所有自定义键,以确保它们在需要时可用,并尽早处理任何注册冲突。

⚙️ 操作实现

创建一个类(或单例对象),继承自 CustomAction 并实现 task 方法。该方法包含当操作被触发时将执行的服务器端逻辑。

object KillPlayerAction : CustomAction() {
    override fun task(player: Player, plugin: Plugin) {
        // 可选:如果需要为此操作启动动态监听器
        dynamicListener?.start()
        // 可选:在延迟后或操作完成后停止动态监听器
        dynamicListener?.stopListenerAfter(20L) // 时间基于刻
        
        player.damage(5.0) // 示例操作:伤害玩家
    }

    // 可选:定义专属于此操作的 Bukkit 事件监听器
    // 自定义监听器对于 CustomActions 并非必需,但这是一个可选方案。
    // 监听器还包含触发该操作的玩家
    override fun listener(dialogPlayer: Player): Listener {
        return object : Listener {
            @EventHandler
            fun onPlayerDeath(event: PlayerDeathEvent) {
                if (event.player == dialogPlayer) {
                    dialogPlayer.sendMessage("你在对话过程中死亡了")
                }
            }
        }
    }
}

ℹ️ task 中的 plugin: Plugin 参数引用你的主插件实例,允许你访问插件特定的资源或调度器;该插件实例与你初始化 DialogAPI 时使用的实例相同。

? 输入读取器

当对话框包含输入字段(如文本框、数字输入等)时,输入读取器 (InputReader) 是必不可少的。它们负责处理玩家从这些字段提交的数据。每个处理带有输入的对话框提交的 CustomAction 都可以关联一个 InputReader。

object PlayerReturnValueReader : InputReader {
    // InputValueList 提供基于键的 getter。
    // 对于通过创建输入时设置的键获取特定值非常有用(见下文)。
    override fun task(player: Player, values: InputValueList) {
        for (input in values.list) {
            player.sendMessage("收到输入 - 键: ${input.key}, 值: ${input.value}") // 修正以显示 input.value
        }
    }
}

⌨️ 创建输入字段

DialogAPI 提供了各种输入字段类型的构建器,允许你收集来自玩家的不同类型数据。每个输入字段都应赋予一个唯一的 key(字符串),以便你在 InputReader 中识别其值。

数字范围输入 (NumberRangeInputBuilder)

val numberRangeInput = NumberRangeInputBuilder()
    .label(Component.text("输入一个数字 (1-10)"))
    .key("number_input") // 此输入字段的唯一键
    .width(150)
    .rangeInfo(RangeInfo(1.0f, 10.0f)) // 定义最小值和最大值
    .labelFormat("") // 可选:标签的自定义格式
    .build()

文本输入 (TextInputBuilder)

val stringInput = TextInputBuilder()
    .label(Component.text("输入反馈 (最多 300 个字符)"))
    .width(256) // 输入字段的宽度
    .key("feedback_text") // 此输入的唯一键
    .initial("It was great!") // 可选:预填充输入字段
    .labelVisible(true) // 是否在输入上方显示标签
    .maxLength(300) // 允许的最大字符数
    // 对于多行:MultilineOptions(visibleLines, maxCharactersPerLineForWrapping)
    .multiline(MultilineOptions(5, 40)) // 使其成为具有 5 行可见区域的多行输入,在 40 个字符处换行
    .build() 
// 注意:对于 TextInput,必须在调用 .build() 之前使用有效的 MultilineOptions 对象调用 .multiline()。

数字范围输入 (NumberRangeInputBuilder)

val numberRangeInput = NumberRangeInputBuilder()
    .label(Component.text("输入一个数字(1.0-10.0,步长 0.5)"))
    .key("quantity_input") // 此输入字段的唯一键
    .width(150)
    // labelFormat 允许指定数字的显示方式,使用类似 printf 的格式说明符。
    .labelFormat("已选择: %.1f 个物品") // 示例:"已选择: 5.0 个物品"
    // RangeInfo(min, max, step, initialValue)
    .rangeInfo(RangeInfo(1.0f, 10.0f, 0.5f, 2.5f)) // 定义最小值、最大值、步长和初始值
    .build()
// 注意:在调用 NumberRangeInput 的 .build() 之前,必须先用有效的 RangeInfo 对象调用 .rangeInfo()。

单选项输入 (SingleOptionInputBuilder - 下拉/单选样式)

val singleOptionInput = SingleOptionInputBuilder()
    .label(Component.text("选择你的职业"))
    .key("player_class_choice")
    .width(150) // 如果选项文本过长,会影响其显示方式
    .labelVisible(true)
    .addEntry( // 将每个选择项作为条目添加
        EntryBuilder()
            //ℹ️ 必须始终有一个初始条目
            .initial(true) // 将此设为默认选中的选项(每个输入字段只允许一个 'initial(true)') 
            .id("warrior_class") // 该 ID 字符串是选中此选项时返回的实际值
            .display(Component.text("战士 ?").color(NamedTextColor.RED)) // 向玩家显示的文本
            .build()
    )
    .addEntry(
        EntryBuilder() // 'initial' 默认为 false
            .id("mage_class") // 该 ID 字符串是值,InputReader 将从 player_class_choice 键读取该值
            .display(Component.text("法师 ?").color(NamedTextColor.BLUE))
            .build()
    )
    .addEntry(
        EntryBuilder()
            .id("archer_class")
            .display(Component.text("弓箭手 ?").color(NamedTextColor.GREEN))
            .build()
    )
    .build()

ℹ️ SingleOptionInput 的重要提示: 你在 EntryBuilder().id("your_id_here") 中提供的 id 字符串,就是当玩家选择该特定选项时,你的 InputReader 接收到的 SingleOptionInput 字段的值。

布尔值输入 (BooleanInputBuilder - 复选框/开关样式)

val booleanInput = BooleanInputBuilder()
    .label(Component.text("启用超级能力?"))
    .key("boolean_super_powers") // 唯一键
    .initial(false) // 初始状态:false(未选中),true(已选中)
    .build()

ℹ️ 关键提醒: 要从这些输入字段中获取值,你必须:

  1. 在创建每个输入字段时为其分配一个唯一的 key。
  2. 确保处理对话框提交的 CustomAction 已注册了 InputReader(如前文所示的 PlayerReturnValueReader)。
  3. 在你的 InputReader 的 task 方法中,使用 values.getValue("your_input_key") 或遍历 values.list 来通过这些键访问提交的数据。

? 寻找更多示例?

查看官方配套项目:DialogApiTest ?。 这是一个功能完整的示例插件,展示了如何在真实的 Paper 服务器环境中使用 DialogAPI(兼容顶部提到的 Minecraft 版本)。它包含了以下实用示例:

  • 带有按钮的自定义对话框
  • 动作注册
  • 输入读取
  • 基于 Kotlin 的构建器语法

非常适合学习、测试或启动你自己的对话框插件!你可以克隆仓库并在测试服务器上运行它。


? 扩展 API

DialogAPI 旨在支持可扩展性。你可以通过以下方式增强其功能:

  • 创建更多的 CustomAction 实现: 定义新动作以处理各种交互元素。
  • 开发专用的 InputReaders: 如果你有复杂的输入处理逻辑,可以创建针对特定数据结构的阅读器。
  • 添加新的 UI 组件构建器: 虽然更高级,但理论上你可以扩展系统以支持新类型的 UI 元素(如果 Minecraft 协议允许)。这将涉及理解底层数据包结构。
  • Fork 并适配: 欢迎 Fork 仓库以添加重要功能或将 API 定制为满足非常特定需求的版本。

核心构建器和注册表模式(例如 CustomKeyRegistry)是你添加功能的主要工具。


? 贡献

欢迎贡献者!如果你想帮助改进 DialogAPI,请遵循以下步骤:

  1. ? Fork the Repository: Click the 'Fork' button at the top right of the GitHub page.
  2. ? Clone Your Fork: git clone https://github.com/YourUsername/DialogAPI.git (Replace YourUsername)
  3. ? Create a Branch: git checkout -b feature/YourAmazingFeature or fix/IssueBeingFixed. Descriptive branch names are helpful!
  4. ✍️ Make Your Changes: Implement your feature, bug fix, or documentation improvement.
    • Adhere to the existing code style (primarily Kotlin conventions).
    • Add KDoc comments for new public APIs or clarify existing ones.
    • If adding new functionality, consider if unit tests are applicable.
  5. ? Test Thoroughly:
    • Run the API in a development server environment (Paper/Spigot) with the relevant Minecraft version(s).
    • Test with various dialog configurations, especially if your changes affect core functionality.
    • Ensure no new issues or console errors are introduced.
  6. ? Commit Your Changes: Use clear and descriptive commit messages. We recommend following the Conventional Commits specification.
    • Example: git commit -m "feat: Add support for ItemDialogBody tooltips"
    • Example: git commit -m "fix: Correctly handle null inputs in PlayerReturnValueReader"
  7. ? Push to Your Branch: git push origin feature/YourAmazingFeature.
  8. ? Open a Pull Request (PR):
    • Navigate to the original DialogAPI repository on GitHub.
    • Click on "Pull requests" and then "New pull request".
    • Choose your fork and the branch containing your changes to compare with the main repository's master or main branch.
    • Provide a clear title for your PR (e.g., "Feature: Add Item Tooltips" or "Fix: Null Pointer in Input Handling").
    • In the PR description, detail the changes you made, the reasoning behind them, and any specific testing instructions. Link to any relevant issues.

Your contributions, big or small, are highly appreciated and help make DialogAPI better for everyone!


❓ Troubleshooting / FAQ

Q: My dialog opens, but buttons with CustomAction or input fields don't work. What's wrong? A: ⚠️ The most common reason is forgetting to call DialogApi.initialize(this) in your plugin's onEnable() method. This step is crucial for registering the necessary packet listeners that handle custom actions and input data. Without it, the API won't process clicks or input submissions from the client.

Q: I'm getting an IllegalStateException: Key [your_key] is already registered when trying to register a CustomKey. A: This error means the ResourceLocation (the key, composed of a namespace and path, e.g., yourplugin:some_action) you're trying to use for your CustomAction is already in use. This could be by another part of your plugin, or rarely, a different plugin (if namespaces aren't unique).

  • Solution: Ensure your ResourceLocation is unique.
  • Namespace: Use your plugin's unique ID (e.g., myplugin).
  • Path: Use a descriptive name for the action (e.g., open_main_menu, submit_player_report).
  • You can defensively check if a key is registered before attempting to register it, or wrap the registration call in a try-catch block to handle this specific exception gracefully (perhaps logging a warning).

Q: How do I choose a good ResourceLocation for my custom actions? A: A ResourceLocation has two string parts: namespace and path.

  • Namespace: This should ideally be your plugin's unique ID (e.g., mycoolplugin, superutils). This helps prevent conflicts with other plugins. Avoid generic namespaces like minecraft, dialog, or custom.
  • Path: This should be a descriptive name for the action, typically using snake_case (e.g., open_shop_menu, confirm_teleport_request, process_player_settings_form).
  • Example: ResourceLocation("myplugin", "open_level_selector")

Q: Is DialogAPI compatible with Java-based plugins? A: ✅ Yes, absolutely! DialogAPI is written in Kotlin but is designed to be fully interoperable with Java. You can use all its builders, classes, and methods from your Java plugin code without any issues. The README provides Java examples for crucial parts like opening dialogs, and the Kotlin builder syntax (method chaining) translates very directly and naturally to Java.

Q: Where can I find the most up-to-date version number for the dependency? A: ? The best places to check for the latest version are:

问:我的输入字段(文本、数字等)在 InputReader 中返回的值不符合预期。我应该检查什么? 答:?️‍♀️ 请仔细检查以下常见要点:

  1. 唯一的输入键: 确保对话框中的每个输入字段都使用唯一的 key 字符串创建(例如 TextInputBuilder().key("player_name_input"),NumberRangeInputBuilder().key("item_quantity"))。这个 key 是你用来识别输入值的依据。
  2. 正确的 InputReader 注册: 验证负责处理对话框提交的 CustomAction 是否已在 CustomKeyRegistry.register() 调用中正确注册到相应的 InputReader 实例。
  3. 在 Reader 中访问值: 在你的 InputReader 的 task(player: Player, values: InputValueList) 方法中,确保使用正确的键来检索值:values.getValue("your_exact_input_key")。你也可以遍历 values.list 并检查 input.key 和 input.value 以进行调试。
  4. 数据类型: 确保你期望的值类型与输入字段提供的类型相匹配(例如,NumberRangeInput 会提供数字,BooleanInput 会提供布尔值)。

你是这个资源的作者?登录后可认领此资源。

评论 0

0.0
暂无评分
5 星
0
4 星
0
3 星
0
2 星
0
1 星
0
我的评分

登录后参与评分

还没有评论,来抢沙发吧

评论配图

相似资源