Skip to content

Kotlin DSL Commands

Roman Makeev edited this page Jan 30, 2023 · 2 revisions

Safe commands

Have you ever been tired of spigot command api? Well, this will help you A LOT!

First things first - you need to add your command into plugins.yml

commands:
  giveitem:
    description: Gives player an item.. or items
    usage: /<command>

Now it's time to create command. You need to register it in your plugin. Do it anywhere you want

// Registering command
AstraLibs.instance.registerCommand("giveitem") {
    // Getting player as an argument
    val player = argument(0) {
        // Here player is parsed
        it?.let(Bukkit::getPlayer)
    }.onFailure {
        // If null is returned - onFailure will be called
        sender.sendMessage("Player not exists: $it")
    }.successOrNull()?.value ?: return@registerCommand

    val itemStack = argument(1) {
        it?.let(Material::getMaterial)?.let(::ItemStack)
    }.onFailure {
        sender.sendMessage("ItemStack not exists: $it")
    }.successOrNull()?.value ?: return@registerCommand

    val amount = argument(2) {
        it?.toIntOrNull() ?: 1
    }.onSuccess {
        val amount = it.value
        sender.sendMessage("Player ${player.name} received ${amount} ${itemStack.type.name}")
        player.inventory.addItem(itemStack.apply { this.amount = amount })
    }
}

Of course it looks a little bit huge, but with it can be improved!

Also you can do arguments in TabCompleter too!

Clone this wiki locally