Creating Commands - TheSourceCodeLLC/Source GitHub Wiki

Creating Commands

  1. Create a new class, i.e MyCommand
  2. Extend RootCommand:
class MyCommand : RootCommand()
  1. Override name and description at the bare minimum: IntelliJ: For a full list of open members, click the class name and press Ctrl + O
class MyCommand : RootCommand() {
  override val name = "mycommand"
  override val description = "Perform my command"
}
  1. To add functionality to this command, override execute(message: Message, arguments: Arguments): Response:
class MyCommand : RootCommand() {
  override val name = "mycommand"
  override val description = "Perform my command"

  //See net.sourcebot.api.response package for a list of predefined Responses
  override fun execute(message: Message, arguments: Arguments) = InfoResponse("MyCommand", "You just ran my command!")
}
  1. Command registration is done inside the main class, in onEnable:
class MyModule : SourceModule() {
  override fun onEnable() {
    registerCommands(
      MyCommand()
    )
  }
}

Creating Subcommands

  1. Create a class that extends Command for your subcommand, overriding the values: Note: We use inner classes for encapsulation purposes but it is not necessary.
class FirstCommand : RootCommand() {
  override val name = "first"
  override val description = "The first command"
  override fun execute(message: Message, arguments: Arguments) = InfoResponse("First")

  private class SecondCommand : Command() {
    override val name = "second"
    override val description = "The second command"
    override fun execute(message: Message, arguments: Arguments) = InfoResponse("Second")
  }
}
  1. Register the subcommand inside the relevant RootCommand:
class FirstCommand : RootCommand() {
  override val name = "first"
  override val description = "The first command"
  override fun execute(message: Message, arguments: Arguments) = InfoResponse("First")

  private class SecondCommand : Command() {
    override val name = "second"
    override val description = "The second command"
    override fun execute(message: Message, arguments: Arguments) = InfoResponse("Second")
  }

  //Register subcommands in init
  init {
    addChildren(
      SecondCommand()
    )
  }
}