Skip to content

Command Interceptors

Miu edited this page Aug 15, 2023 · 10 revisions

Command interceptors, like middlewares and afterwares, can be established through two primary approaches:

  1. Creating an Interceptor Repository.
  2. Directly Registering Interceptors within the Framework.

Let's start by examining the second approach. Nexus aggregates all interceptors within a global container accessible by name. All interceptors are stored within NexusCommandInterceptor. You can add them using the following methods:

// Example One: Reducing code duplication
NexusCommandInterceptor.addMiddleware("nexus.auth.server") { event -> event.stopIf(event.server.isEmpty) }

// Example Two: Creating quick middlewares (not recommended)
// This uses UUID as a namespace instead of a user-defined one.
NexusCommandInterceptor.middleware { event -> event.stopIf(event.server.isEmpty) }

Middlewares implement the NexusMiddleware interface, utilizing the NexusMiddlewareEvent, which contains more methods compared to the traditional NexusCommandEvent:

  • next: Instructs Nexus to proceed to the next middleware. Does not require being called as a middleware's response.
  • stop: Directs Nexus to halt the command's execution, resulting in a "Interaction has failed" outcome in the user's Discord client.
  • stop(NexusMessage): Halts the command's execution and sends a specified message.
  • stopIf(boolean, NexusMessage?): Stops command execution if the boolean is true, sending a message if provided.
  • stopIf(Predicate, NexusMessage?): Similar to the previous method but accepts a predicate.

Deferred Middleware Responses

Nexus introduces two primary methods for deferring responses in middlewares. However, neither method will automatically defer commands. Responsibility for using deferred responses in commands remains with you. Let's explore the two main ways to defer responses in middlewares:

Manual Deferring

You can manually defer middlewares by utilizing defer or deferEphemeral, followed by a response such as stop(NexusMessage). Here's an example of a middleware that defers:

NexusInterceptor.middleware { event -> 
    event.deferEphemeral().join()
    event.stop(NexusMessage.from("I have deferred the response!"))
}
Automatic Deferring

Automatic deferring is a newer Nexus feature where deferring middlewares is automated. To use this, you need to enable it in the configuration:

Nexus.configuration.interceptors.autoDeferMiddlewareResponses = true

Once enabled, middleware responses will automatically defer if their execution time exceeds 2.5 seconds, like this:

NexusInterceptor.middleware { event -> 
    Thread.sleep(3000)
    event.stop(NexusMessage.from("I have deferred the response!"))
}

You can further configure properties such as whether deferred responses should be ephemeral or when to automatically defer. Adjust these properties:

// Default values
Nexus.configuration.global.autoDeferAfterMilliseconds = 2350
Nexus.configuration.interceptors.autoDeferAsEphemeral = true

Note

As previously mentioned, you need to manually use deferred responses in commands after enabling this feature. Nexus will not automatically defer command responses. Utilize methods like event.respondLater() or event.respondLaterAsEphemeral() to handle these cases, or you can enable Nexus to auto-defer for you.

For more details on auto-deferring responses, refer to Auto-deferring Commands.

Creating Interceptor Repositories

An alternative way to establish interceptors is by utilizing a repository approach. To do this, create a class that extends NexusInterceptorRepository. This class provides default methods that facilitate the creation of interceptors in a more streamlined manner. Following this method is recommended:

object SampleInterceptorRepository: NexusInterceptorRepository() {
    val SERVER_ONLY = "nexus.auth.server"
    
    override fun define() {
        middleware(SERVER_ONLY) { event -> event.stopIf(event.server.isEmpty) }
    }
}

Next, you can instruct Nexus to register all the defined interceptors like this:

NexusCommandInterceptor.addRepository(SampleInterceptorRepository)

The recommended use of repositories helps simplify the process of including middlewares. Here's an example demonstrating how to immediately include a middleware using the defined variable:

object PingCommand: NexusHandler {
    val name: String = "ping"
    val description: String = "Ping, Pong!"
    val middlewares = NexusCommand.createMiddlewares(SampleInterceptorRepository.SERVER_ONLY)

    override fun onEvent(event: NexusCommandEvent) {
        val server = event.server.orElseThrow()
        event.respondNowWith("Hello ${server.name}!")
    }
}

Now, this command is guaranteed to execute only when the server is present. But there's more to interceptors – you can add custom properties to commands that interceptors can access using the @Share annotation. Here's how you can achieve that:

object PingCommand: NexusHandler {
    val name: String = "ping"
    val description: String = "Ping, Pong!"
    val middlewares = NexusCommand.createMiddlewares(SampleInterceptorRepository.SERVER_ONLY, SampleInterceptorRepository.DEVELOPER_LOCK)
    @Share val DEVELOPER_ONLY = false

    override fun onEvent(event: NexusCommandEvent) {
        val server = event.server.orElseThrow()
        event.respondNowWith("Hello ${server.name}!")
    }
}

object SampleInterceptorRepository: NexusInterceptorRepository() {
    val SERVER_ONLY = "nexus.auth.server"
    val DEVELOPER_LOCK = "nexus.auth.developer"

    override fun define() {
        middleware(SERVER_ONLY) { event -> event.stopIf(event.server.isEmpty) }
        middleware(DEVELOPER_LOCK) { event -> 
            val locked = event.command.get("DEVELOPER_ONLY", Boolean::class.java).orElse(false)
            event.stopIf(locked)
        }
    }
}

In this way, you can create powerful and flexible command structures that interact seamlessly with interceptors.

To get started with Nexus, we recommend reading the following in chronological:

  1. Installation & Preparing Nexus
  2. Designing Commands
  3. Command Interceptors
  4. Additional Features (Subcommand Router, Option Validation)
  5. Context Menus
  6. Command Synchronization

You may want to read a specific part of handling command and middleware responses:

You can also read about additional features of Nexus:

You can read about synchronizing commands to Discord:

For more additional performance:

Additional configurations:

Clone this wiki locally