# Bus (https://nyx-discord.github.io/nyx/guide/extend/commands/command-bus) The `CommandBus` is the [`EventBus`](/use/events/busses) used for emitting command events. ## Overriding [#overriding] ## Creation and Registration [#creation-and-registration] Create your own bus [in any way](/use/events/buses) and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { type CommandEventArgs, type NyxBot } from '@nyx-discord/djs'; import { Client, type ClientEvents } from 'discord.js'; declare const client: Client; declare const bot: NyxBot; // ---cut--- import { BasicEventBus } from '@nyx-discord/djs'; class MyCommandBus extends BasicEventBus { /** Your overrides */ } const commandBus = MyCommandBus.createAsync(); await bot.getCommandManager().setEventBus(commandBus); ``` ```ts twoslash import { type CommandEventArgs, type NyxBot } from '@nyx-discord/djs-core'; import { Client, type ClientEvents } from 'discord.js'; declare const client: Client; declare const bot: NyxBot; // ---cut--- import { BasicEventBus } from '@nyx-discord/djs-core'; class MyCommandBus extends BasicEventBus { /** Your overrides */ } const commandBus = MyCommandBus.createAsync(); await bot.getCommandManager().setEventBus(commandBus); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type CommandEventArgs, type NyxBot } from '@nyx-discord/http'; import { Client, type ClientEvents } from 'discord.js'; declare const client: Client; declare const bot: NyxBot; // ---cut--- import { BasicEventBus } from '@nyx-discord/http'; class MyCommandBus extends BasicEventBus { /** Your overrides */ } const commandBus = MyCommandBus.createAsync(); await bot.getCommandManager().setEventBus(commandBus); ``` The (or ) method instantiates your custom bus, not the default one. # CustomId Codec (https://nyx-discord.github.io/nyx/guide/extend/commands/command-customidcodec) The is responsible for de/serializing commands to/from customId strings, for the [Command Components](/use/commands/components) feature. The default implementation () uses the [`@sapphire/string-store`](https://www.npmjs.com/package/@sapphire/string-store) package to efficiently de/serialize the data. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |--------------------------------------|----------------------------------------------------------------------------------------------------------------| | Use a custom de/serialization logic. | De/serialize your extra data. You should do that on sending/receiving instead, as it'll be easier to maintain. | ## Overriding [#overriding] ### Creation [#creation] Create a custom codec by either: * Extending ('s implementation, recommended for less work). * Implementing ('s interface). ```ts twoslash import { DefaultCommandCustomIdCodec } from '@nyx-discord/djs'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec {} ``` ```ts twoslash import { DefaultCommandCustomIdCodec } from '@nyx-discord/djs-core'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandCustomIdCodec } from '@nyx-discord/http'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec {} ``` ### Registration [#registration] Create it and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash // ---cut--- import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { DefaultCommandCustomIdCodec } from '@nyx-discord/djs'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec { /** Your overrides */ } const customIdCodec = MyCommandCustomIdCodec.create(); bot.getCommandManager().setCustomIdCodec(customIdCodec); ``` ```ts twoslash // ---cut--- import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { DefaultCommandCustomIdCodec } from '@nyx-discord/djs-core'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec { /** Your overrides */ } const customIdCodec = MyCommandCustomIdCodec.create(); bot.getCommandManager().setCustomIdCodec(customIdCodec); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut--- import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { DefaultCommandCustomIdCodec } from '@nyx-discord/http'; class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec { /** Your overrides */ } const customIdCodec = MyCommandCustomIdCodec.create(); bot.getCommandManager().setCustomIdCodec(customIdCodec); ``` The method instantiates your custom codec, not the default one. # Deployer (https://nyx-discord.github.io/nyx/guide/extend/commands/command-deployer) The `CommandDeployer` is responsible for deploying commands to Discord and storing the [ApplicationCommand](https://discord.js.org/docs/packages/discord.js/stable/ApplicationCommand:Class) mappings. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |-------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| | Deploy commands in a different way. | Change command serialization. That is done in the command itself, you can override your `data` property or `getData()` method instead. | | | Deploy commands conditionally or manually. Instead, return `deployCommands: false` on `Bot.create()` and call `CommandManager#deploy()` when you want. | ## Overriding [#overriding] ### Creation [#creation] Create a custom deployer by either: * Extending `DefaultCommandDeployer` (recommended, less work). * Implementing `CommandDeployer`. ```ts twoslash import { DefaultCommandDeployer } from '@nyx-discord/djs'; class MyCommandDeployer extends DefaultCommandDeployer {} ``` ```ts twoslash import { DefaultCommandDeployer } from '@nyx-discord/djs-core'; class MyCommandDeployer extends DefaultCommandDeployer {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandDeployer } from '@nyx-discord/http'; class MyCommandDeployer extends DefaultCommandDeployer {} ``` ### Registration [#registration] Create it and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { DefaultCommandDeployer } from '@nyx-discord/djs'; import { Client } from 'discord.js'; import type { Bot } from '@nyx-discord/djs'; declare const client: Client; declare const bot: Bot; // ---cut--- class MyCommandDeployer extends DefaultCommandDeployer { /** Your overrides */ } bot.getCommandManager().setDeployer(MyCommandDeployer.create(client)); ``` The method instantiates your custom deployer, not the default one. ```ts twoslash import { DefaultCommandDeployer, type Bot } from '@nyx-discord/djs-core'; import type { API, Snowflake } from '@discordjs/core'; declare const api: API; declare const applicationId: Snowflake; declare const bot: Bot; // ---cut--- class MyCommandDeployer extends DefaultCommandDeployer { /** Your overrides */ } bot.getCommandManager().setDeployer(MyCommandDeployer.create(api, applicationId)); ``` The method instantiates your custom deployer, not the default one. Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandDeployer, type Bot } from '@nyx-discord/http'; import type { API, Snowflake } from '@discordjs/core'; declare const api: API; declare const applicationId: Snowflake; declare const bot: Bot; // ---cut--- class MyCommandDeployer extends DefaultCommandDeployer { /** Your overrides */ } bot.getCommandManager().setDeployer(MyCommandDeployer.create(api, applicationId)); ``` The method instantiates your custom deployer, not the default one. # Manager (https://nyx-discord.github.io/nyx/guide/extend/commands/command-manager) The `CommandManager` is the object that holds together the nyx command system. At a glance: - Core services: owns the command building blocks, creating defaults in `create()` while still allowing targeted injections. - State and deployment sync: add/remove operations update repository and deployer together with rollback on deploy failures, while edit/set keep both layers aligned for bulk updates. - Interaction routing and execution: resolves incoming interactions to executable commands (including `customId` decoding for component interactions), then runs execute/autocomplete through the executor. - Manager events: emits `CommandAdd`, `CommandRemove`, `CommandRun`, and `CommandAutocomplete` so other parts of the system can react to lifecycle and runtime actions. In practice, this makes it the boundary where command registration, resolution, execution, deployment, subscriptions, events, and runtime metadata are coordinated. ## Overriding [#overriding] ### Creation [#creation] Create a custom command manager by either: * Extending `DefaultCommandManager`. * Implementing `CommandManager`. ```ts twoslash import { DefaultCommandManager } from '@nyx-discord/djs'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` ```ts twoslash import { DefaultCommandManager } from '@nyx-discord/djs-core'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandManager } from '@nyx-discord/http'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` ### Registration [#registration] Then you can pass it to your bot: ```ts twoslash import { Client } from 'discord.js'; import { DefaultCommandManager } from '@nyx-discord/djs'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { Bot, type NyxBot } from '@nyx-discord/djs'; const myBot = Bot.create((bot: NyxBot) => ({ // ---cut-start--- token: 'TOKEN', client: new Client({ intents: [] }), logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options commandManager: new MyCommandManager(/** ... */), })); const manager = myBot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? ``` ```ts twoslash import { Client, GatewayIntentBits } from '@discordjs/core'; import { REST } from '@discordjs/rest'; import { WebSocketManager } from '@discordjs/ws'; import { DefaultCommandManager } from '@nyx-discord/djs-core'; const rest = new REST({ version: '10' }).setToken('TOKEN'); const gateway = new WebSocketManager({ token: 'TOKEN', intents: GatewayIntentBits.Guilds, rest }); const client = new Client({ rest, gateway }); class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { Bot, CoreNyxClient, type NyxBot } from '@nyx-discord/djs-core'; const myBot = Bot.create((bot: NyxBot) => ({ // ---cut-start--- token: 'TOKEN', client: new CoreNyxClient(client, gateway, 'APPLICATION_ID'), logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options commandManager: new MyCommandManager(/** ... */), })); const manager = myBot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? ``` ```ts twoslash import { DefaultCommandManager } from '@nyx-discord/http'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { HttpBot, type NyxBot } from '@nyx-discord/http'; const myBot = HttpBot.create((bot: NyxBot) => ({ // ---cut-start--- applicationId: 'APPLICATION_ID', publicKey: 'PUBLIC_KEY', token: 'TOKEN', logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options commandManager: new MyCommandManager(/** ... */), })); const manager = myBot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? ``` The class is able to infer the type of your custom manager, so accessing any custom method or property will work without errors. If you ever want to use this custom bot type with your injected manager somewhere else, you can do so via the generic: ```ts twoslash import { Client } from 'discord.js'; import { DefaultCommandManager } from '@nyx-discord/djs'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/djs'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` ```ts twoslash import { Client } from 'discord.js'; import { DefaultCommandManager } from '@nyx-discord/djs-core'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/djs-core'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { Client } from 'discord.js'; import { DefaultCommandManager } from '@nyx-discord/http'; class MyCommandManager extends DefaultCommandManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/http'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getCommandManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` For readability purposes, we recommend storing the type with the generic in a separate type, like in the example. # Repository (https://nyx-discord.github.io/nyx/guide/extend/commands/command-repository) The `CommandRepository` is responsible for storing all the currently registered commands. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---------------------------------|----------------------------------------------------------------------------------------------------------------------| | Change how commands are stored. | Do something when commands are added, including decorating them. Use [Command Events](/use/commands/events) instead. | | | Change how commands are deployed. Override the [CommandDeployer](/extend/commands/command-deployer) instead. | ## Overriding [#overriding] ### Creation [#creation] Create a custom command repository by either: * Extending `DefaultCommandRepository` (recommended, less work). * Implementing `CommandRepository`. ``` ts twoslash import { DefaultCommandRepository } from '@nyx-discord/djs'; class MyCommandRepository extends DefaultCommandRepository {} ``` ```ts twoslash import { DefaultCommandRepository } from '@nyx-discord/djs-core'; class MyCommandRepository extends DefaultCommandRepository {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandRepository } from '@nyx-discord/http'; class MyCommandRepository extends DefaultCommandRepository {} ``` ### Registration [#registration] Create it and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { DefaultCommandRepository } from '@nyx-discord/djs'; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- class MyCommandRepository extends DefaultCommandRepository { /** Your overrides */ } bot.getCommandManager().setRepository(MyCommandRepository.create()); ``` ```ts twoslash import { DefaultCommandRepository } from '@nyx-discord/djs-core'; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- class MyCommandRepository extends DefaultCommandRepository { /** Your overrides */ } bot.getCommandManager().setRepository(MyCommandRepository.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandRepository } from '@nyx-discord/http'; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- class MyCommandRepository extends DefaultCommandRepository { /** Your overrides */ } bot.getCommandManager().setRepository(MyCommandRepository.create()); ``` The method instantiates your custom repository, not the default one. # Resolver (https://nyx-discord.github.io/nyx/guide/extend/commands/command-resolver) The `CommandResolver` is responsible for locating commands given an interaction or `customId` context. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |-----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------| | Customize how commands are located from the repository when an interaction is received. | Introduce other localization methods. It's easier to make your own method that uses the `CommandRepository`. | | You need to perform extra logic while locating a command. | Deserialize `customIds` in different ways. That would be the [`CommandCustomIdCodec`](./command-customid-codec)'s job. | ## Overriding [#overriding] ### Creation [#creation] Create a custom command resolver by either: * Extending `DefaultCommandResolver` (recommended, less work). * Implementing `CommandResolver`. ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/djs'; class MyCommandResolver extends DefaultCommandResolver {} ``` ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/djs-core'; class MyCommandResolver extends DefaultCommandResolver {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/http'; class MyCommandResolver extends DefaultCommandResolver {} ``` ### Registration [#registration] Create it and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/djs'; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- class MyCommandResolver extends DefaultCommandResolver { /** Your overrides */ } bot.getCommandManager().setResolver(MyCommandResolver.create()); ``` ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/djs-core'; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- class MyCommandResolver extends DefaultCommandResolver { /** Your overrides */ } bot.getCommandManager().setResolver(MyCommandResolver.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandResolver } from '@nyx-discord/http'; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- class MyCommandResolver extends DefaultCommandResolver { /** Your overrides */ } bot.getCommandManager().setResolver(MyCommandResolver.create()); ``` The method instantiates your custom resolver, not the default one. # Subscriptions Container (https://nyx-discord.github.io/nyx/guide/extend/commands/command-subscriptions-container) The `CommandSubscriptionsContainer` is responsible for storing the subscribers that are subscribed to the [Client's `EventBus`](/use/events) to listen for command interactions. ## Overriding [#overriding] ## Creation and Registration [#creation-and-registration] Create your own container by extending `DefaultCommandSubscriptionsContainer` and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { DefaultCommandSubscriptionsContainer } from '@nyx-discord/djs'; import type { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut--- import { DefaultCommandInteractionSubscriber, DefaultCommandAutocompleteSubscriber } from '@nyx-discord/djs'; class MySubscriptionsContainer extends DefaultCommandSubscriptionsContainer { /** Your overrides */ } const container = MySubscriptionsContainer.create( bot.getClientEventBus(), new DefaultCommandInteractionSubscriber(), new DefaultCommandAutocompleteSubscriber(), ); bot.getCommandManager().setSubscriptions(container); ``` ```ts twoslash import { DefaultCommandSubscriptionsContainer } from '@nyx-discord/djs-core'; import type { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut--- import { DefaultCommandInteractionSubscriber, DefaultCommandAutocompleteSubscriber } from '@nyx-discord/djs-core'; class MySubscriptionsContainer extends DefaultCommandSubscriptionsContainer { /** Your overrides */ } const container = MySubscriptionsContainer.create( bot.getClientEventBus(), new DefaultCommandInteractionSubscriber(), new DefaultCommandAutocompleteSubscriber(), ); bot.getCommandManager().setSubscriptions(container); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandSubscriptionsContainer } from '@nyx-discord/http'; import type { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut--- import { DefaultCommandInteractionSubscriber, DefaultCommandAutocompleteSubscriber } from '@nyx-discord/http'; class MySubscriptionsContainer extends DefaultCommandSubscriptionsContainer { /** Your overrides */ } const container = MySubscriptionsContainer.create( bot.getClientEventBus(), new DefaultCommandInteractionSubscriber(), new DefaultCommandAutocompleteSubscriber(), ); bot.getCommandManager().setSubscriptions(container); ``` The method instantiates your custom container, not the default one. # Error Handler (https://nyx-discord.github.io/nyx/guide/extend/commands/executor/command-error-handler) The `CommandErrorHandler` is responsible for handling errors thrown by middlewares and commands. It's inside the [`CommandExecutor`](/extend/commands/executor) object, and will be used by it. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |-------------------------------------------|------------------------------------------------------------------------------------| | Resolve consumers with a different logic. | Add new consumers or a fallback one. The object already supports these operations. | ## Overriding [#overriding] ### Creation [#creation] Create a custom error handler by either: * Extending `BasicErrorHandler` (recommended, less work). * Implementing `CommandErrorHandler`. ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/djs'; class MyErrorHandler extends BasicErrorHandler {} ``` ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/djs-core'; class MyErrorHandler extends BasicErrorHandler {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/http'; class MyErrorHandler extends BasicErrorHandler {} ``` ### Registration [#registration] Create it and set it to the [`CommandExecutor`](/extend/commands/executor), then set the executor on the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/djs'; import type { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/djs'; class MyErrorHandler extends BasicErrorHandler {} const executor = DefaultCommandExecutor.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/djs-core'; import type { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/djs-core'; class MyErrorHandler extends BasicErrorHandler {} const executor = DefaultCommandExecutor.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, type AnyExecutableCommand, type CommandExecutionArgs } from '@nyx-discord/http'; import type { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/http'; class MyErrorHandler extends BasicErrorHandler {} const executor = DefaultCommandExecutor.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` The `create()` method instantiates your custom error handler, not the default one. The default error handler will use `console.error` as a fallback consumer. If you want to change it to the bot's logger, instantiate it this way: ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/djs'; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { TypedFields } from '@nyx-discord/djs'; import type { AnyExecutableCommand, CommandExecutionArgs } from '@nyx-discord/djs'; const myHandler = MyErrorHandler.createWithFallbackLogger( (_error, _command, [_interaction, metadata]) => TypedFields.getLogger(metadata), ); ``` ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/djs-core'; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { TypedFields } from '@nyx-discord/djs-core'; import type { AnyExecutableCommand, CommandExecutionArgs } from '@nyx-discord/djs-core'; const myHandler = MyErrorHandler.createWithFallbackLogger( (_error, _command, [_interaction, metadata]) => TypedFields.getLogger(metadata), ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/http'; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { TypedFields } from '@nyx-discord/http'; import type { AnyExecutableCommand, CommandExecutionArgs } from '@nyx-discord/http'; const myHandler = MyErrorHandler.createWithFallbackLogger( (_error, _command, [_interaction, metadata]) => TypedFields.getLogger(metadata), ); ``` # Middleware List (https://nyx-discord.github.io/nyx/guide/extend/commands/executor/command-middleware-list) The `CommandMiddlewareList` is responsible for holding and executing the middlewares that run before a command is executed. It's inside the [`CommandExecutor`](/extend/commands/executor) object, and will be executed by it. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |-----------------------------------------------------------|---------------------------------------------------------------------------| | Do something before, while or after checking middlewares. | Add new middlewares. The list already supports add and remove operations. | | Check middlewares in a different way or order. | | ## Overriding [#overriding] ### Creation [#creation] Create a custom middleware list by either: * Extending `CommandMiddlewareList` (recommended, less work). * Implementing `MiddlewareList`. ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/djs'; class MyMiddlewareList extends CommandMiddlewareList {} ``` ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/djs-core'; class MyMiddlewareList extends CommandMiddlewareList {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/http'; class MyMiddlewareList extends CommandMiddlewareList {} ``` ### Registration [#registration] Create it and set it to the [`CommandExecutor`](/extend/commands/executor), then set the executor on the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/djs'; import type { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/djs'; class MyMiddlewareList extends CommandMiddlewareList {} const executor = DefaultCommandExecutor.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/djs-core'; import type { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/djs-core'; class MyMiddlewareList extends CommandMiddlewareList {} const executor = DefaultCommandExecutor.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CommandMiddlewareList } from '@nyx-discord/http'; import type { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut--- import { DefaultCommandExecutor } from '@nyx-discord/http'; class MyMiddlewareList extends CommandMiddlewareList {} const executor = DefaultCommandExecutor.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bot.getCommandManager().setExecutor(executor); ``` The `create()` method instantiates your custom middleware list, not the default one. # Executor (https://nyx-discord.github.io/nyx/guide/extend/commands/executor) The `CommandExecutor` is responsible for executing commands, making sure the middleware passes and handling errors. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |--------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | Customize how commands are executed. | Listen for command runs. [Use the `EventBus` in the `CommandManager` instead](/use/commands/events). | | Add advanced logic while executing a command, like delaying calls. | Add new middlewares or error consumers. You can interact with the [`MiddlewareList`](/use/commands/middlewares) and [`ErrorHandler`](/use/other/error-handling) objects directly, using the getter on the executor. | | | Override the default `MiddlewareList` or `ErrorHandler`. You can do that already from the `DefaultCommandExecutor.create()` options, as shown in the respective guide of the object you want to override. | ## Overriding [#overriding] ### Creation [#creation] Create a custom executor by either: * Extending `DefaultCommandExecutor` (recommended, less work). * Implementing `CommandExecutor`. ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/djs'; class MyCommandExecutor extends DefaultCommandExecutor {} ``` ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/djs-core'; class MyCommandExecutor extends DefaultCommandExecutor {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/http'; class MyCommandExecutor extends DefaultCommandExecutor {} ``` ### Registration [#registration] Create it and set it to the [`CommandManager`](/extend/commands/command-manager). ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/djs'; import type { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut--- class MyCommandExecutor extends DefaultCommandExecutor {} bot.getCommandManager().setExecutor(MyCommandExecutor.create()); ``` ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/djs-core'; import type { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut--- class MyCommandExecutor extends DefaultCommandExecutor {} bot.getCommandManager().setExecutor(MyCommandExecutor.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultCommandExecutor } from '@nyx-discord/http'; import type { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut--- class MyCommandExecutor extends DefaultCommandExecutor {} bot.getCommandManager().setExecutor(MyCommandExecutor.create()); ``` The `create()` method instantiates the executor with the default `ErrorHandler` and `MiddlewareList` (which are overridable, as described below). It'll also instantiate your custom class, not the base one. ## Dependencies [#dependencies] You can override the executor's dependencies (`ErrorHandler` and `MiddlewareList`) by passing them as options to the `DefaultCommandExecutor.create()` method. More details in the respective guides: } external={false}> Holds and executes the command middlewares. } external={false}> Handles command-related errors. # Command Internals (https://nyx-discord.github.io/nyx/guide/extend/commands) The commands system is made up of several components that work together to store, resolve, execute commands and more. ## Command system components [#command-system-components] Specifically, these components are: - [`CommandManager`](/extend/commands/command-manager): The entry point for the command system, holding all the command-related objects and methods that use all of these objects. All objects below are contained here. - [`CommandResolver`](/extend/commands/command-resolver): Resolves the command that a given command interaction refers to. - [`CommandExecutor`](/extend/commands/executor): Executes commands, checking its `MiddlewareList` and passing errors to the `ErrorHandler`. - [`CommandRepository`](/extend/commands/command-repository): Stores all the currently registered commands. - [`CommandCustomIdCodec`](/extend/commands/command-customidcodec): De/serializes commands names to/from customId strings, for the [Command Components](/use/commands/components) feature. - [`CommandDeployer`](/extend/commands/command-deployer): Deploys commands to Discord and stores the [ApplicationCommand](https://discord.js.org/docs/packages/discord.js/stable/ApplicationCommand:Class) mappings. - [`Command EventBus`](/extend/commands/command-bus): An [`EventBus`](../events/event-bus) that emits command related events. - [`CommandSubscriptionsContainer`](/extend/commands/command-subscriptions-container): Stores the subscribers that are subscribed to the client's `EventBus` to listen for command interactions. ## Execution Sequence [#execution-sequence] The following diagrams show the flow of a command execution. You can check the guide of each component to see exactly how it works, or how to replace it. - You can zoom and drag on the diagrams. - A dashed step means it's executed through a non awaited (but caught) Promise, so the next one is inmediately executed if there's an I/O operation in the step. - You can hover over steps with `(?)` to see extra details. - If a step goes to a target, and that target doesn't continue the flow, then it's an immediate return, like a getter call. ### Command event [#command-event] For a command to be executed, you first receive a `interactionCreate` event, which is then passed to the [`CommandManager`](./command-manager.mdx): ### Command resolution [#command-resolution] The [`CommandResolver`](./command-resolver.mdx) then resolves the command that the interaction refers to. For component interactions, this first needs an intermediate step through the [`CommandCustomIdCodec`](./command-customid-codec.mdx) to deserialize the customId. #### Command Interactions [#command-interactions] #### Component Interactions [#component-interactions] ### Command execution [#command-execution] Once the command is resolved, it's passed to the [`CommandExecutor`](./command-executor.mdx): On which the execution ends. Next, see the documentation of each component, where you'll find what it does and how to replace it. # Error Handler (https://nyx-discord.github.io/nyx/guide/extend/events/dispatcher/event-error-handler) The `EventSubscriberErrorHandler` handles errors thrown while checking middlewares or executing event subscribers. It's inside the [`EventDispatcher`](/extend/events/dispatcher) object, and will be used by it. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Resolve error consumers with custom logic. | Add/remove subscribers from buses. That's done with `EventBus#subscribe()` and `EventBus#unsubscribe()`. | | Change fallback behavior for uncaught errors (logging, telemetry, alerting). | Change middleware order. Use the dispatcher middleware list for that. | | Route specific error classes to specialized consumers. | Replace dispatch flow entirely. If you only want custom error handling, replacing this dependency is enough. | ## Overriding [#overriding] ### Creation [#creation] Create a custom error handler by either: * Extending `BasicErrorHandler` (recommended, less work). * Implementing `EventSubscriberErrorHandler`. ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs } from '@nyx-discord/djs'; class MyErrorHandler extends BasicErrorHandler {} ``` ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs } from '@nyx-discord/djs-core'; class MyErrorHandler extends BasicErrorHandler {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs } from '@nyx-discord/http'; class MyErrorHandler extends BasicErrorHandler {} ``` ### Registration [#registration] Inject it directly when creating the dispatcher: ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/djs'; declare const bus: EventBus<{ someEvent: [string] }>; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/djs'; const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bus.setDispatcher(dispatcher); ``` ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/djs-core'; declare const bus: EventBus<{ someEvent: [string] }>; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/djs-core'; const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bus.setDispatcher(dispatcher); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/http'; declare const bus: EventBus<{ someEvent: [string] }>; class MyErrorHandler extends BasicErrorHandler {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/http'; const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler: MyErrorHandler.create(), }, }); bus.setDispatcher(dispatcher); ``` To use the bot logger as fallback, create a handler with `createWithFallbackLogger` and inject it: ```ts twoslash import { BasicSyncEventDispatcher, BasicErrorHandler, TypedFields, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/djs'; type MyEvents = { someEvent: [string]; }; declare const bus: EventBus; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _subscriber, [metadata]) => TypedFields.getLogger(metadata), ); const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler, }, }); bus.setDispatcher(dispatcher); ``` ```ts twoslash import { BasicSyncEventDispatcher, BasicErrorHandler, TypedFields, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/djs-core'; type MyEvents = { someEvent: [string]; }; declare const bus: EventBus; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _subscriber, [metadata]) => TypedFields.getLogger(metadata), ); const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler, }, }); bus.setDispatcher(dispatcher); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicSyncEventDispatcher, BasicErrorHandler, TypedFields, type AnyEventSubscriber, type EventDispatchArgs, type EventBus, } from '@nyx-discord/http'; type MyEvents = { someEvent: [string]; }; declare const bus: EventBus; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _subscriber, [metadata]) => TypedFields.getLogger(metadata), ); const dispatcher = BasicSyncEventDispatcher.create({ injections: { errorHandler, }, }); bus.setDispatcher(dispatcher); ``` # Middleware List (https://nyx-discord.github.io/nyx/guide/extend/events/dispatcher/event-middleware-list) The `SubscriberMiddlewareList` holds and executes the middlewares used by an `EventDispatcher` before each subscriber is called. It's inside the [`CommandExecutor`](/extend/commands/executor) object, and will be used by it. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Add custom behavior before/after middleware checks. | Change subscriber execution order. That's controlled by the bus and its sorter. | | Change how middleware errors are wrapped or reported. | Handle subscriber errors. Use the dispatcher's [`ErrorHandler`](/use/other/error-handling) for that. | | Replace the default middleware chain globally for a dispatcher. | Override all dispatcher logic. If only middleware behavior changes, replacing the list is enough. | ## Overriding [#overriding] ### Creation [#creation] Create a custom middleware list by either: * Extending `SubscriberMiddlewareList` (recommended, less work). * Implementing `MiddlewareList`. ```ts twoslash import { SubscriberMiddlewareList } from '@nyx-discord/djs'; class MyMiddlewareList extends SubscriberMiddlewareList {} ``` ```ts twoslash import { SubscriberMiddlewareList } from '@nyx-discord/djs-core'; class MyMiddlewareList extends SubscriberMiddlewareList {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { SubscriberMiddlewareList } from '@nyx-discord/http'; class MyMiddlewareList extends SubscriberMiddlewareList {} ``` ### Registration [#registration] Inject it directly when creating the dispatcher: ```ts twoslash import { SubscriberMiddlewareList, type EventBus, } from '@nyx-discord/djs'; declare const bus: EventBus<{ someEvent: [string] }>; class MyMiddlewareList extends SubscriberMiddlewareList {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/djs'; // Works the same with the async dispatcher const dispatcher = BasicSyncEventDispatcher.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bus.setDispatcher(dispatcher); ``` ```ts twoslash import { SubscriberMiddlewareList, type EventBus, } from '@nyx-discord/djs-core'; declare const bus: EventBus<{ someEvent: [string] }>; class MyMiddlewareList extends SubscriberMiddlewareList {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/djs-core'; // Works the same with the async dispatcher const dispatcher = BasicSyncEventDispatcher.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bus.setDispatcher(dispatcher); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { SubscriberMiddlewareList, type EventBus, } from '@nyx-discord/http'; declare const bus: EventBus<{ someEvent: [string] }>; class MyMiddlewareList extends SubscriberMiddlewareList {} // ---cut--- import { BasicSyncEventDispatcher } from '@nyx-discord/http'; // Works the same with the async dispatcher const dispatcher = BasicSyncEventDispatcher.create({ injections: { middleware: MyMiddlewareList.create(), }, }); bus.setDispatcher(dispatcher); ``` If you prefer, you can still wrap this in a custom dispatcher class and call `super.create(...)`. # Dispatcher (https://nyx-discord.github.io/nyx/guide/extend/events/dispatcher) The `EventDispatcher` is responsible for calling `EventSubscribers`, checking middlewares, and handling errors of each emitted event. It's used by every `EventBus` through `EventBus#emit()`, and can be replaced at runtime with `EventBus#setDispatcher()`. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Change how subscribers are dispatched (batching, throttling, etc). | Add/remove event middlewares only. You can do that from the dispatcher's middleware list. | | Add custom logic that modify execution (instrumentation, retries, etc). | Add/change error consumers only. You can do that from the dispatcher's error handler. | | | Tune runtime behavior like sync timeout or async concurrency. The base dispatchers implementations [already allow that](/use/events/buses#subscriber-concurrency). | ## Overriding [#overriding] ### Creation [#creation] Create a custom dispatcher by either: * Extending `BasicSyncEventDispatcher` or `BasicAsyncEventDispatcher` (recommended, less work). * Implementing `EventDispatcher`. ```ts twoslash import { BasicSyncEventDispatcher } from '@nyx-discord/djs'; class MyEventDispatcher extends BasicSyncEventDispatcher {} ``` ```ts twoslash import { BasicSyncEventDispatcher } from '@nyx-discord/djs-core'; class MyEventDispatcher extends BasicSyncEventDispatcher {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicSyncEventDispatcher } from '@nyx-discord/http'; class MyEventDispatcher extends BasicSyncEventDispatcher {} ``` ### Registration [#registration] Set your dispatcher on any bus: ```ts twoslash import { BasicSyncEventDispatcher, type EventBus } from '@nyx-discord/djs'; declare const bus: EventBus<{ someEvent: [string] }>; class MyEventDispatcher extends BasicSyncEventDispatcher {} // ---cut--- bus.setDispatcher(MyEventDispatcher.create()); ``` ```ts twoslash import { BasicSyncEventDispatcher, type EventBus } from '@nyx-discord/djs-core'; declare const bus: EventBus<{ someEvent: [string] }>; class MyEventDispatcher extends BasicSyncEventDispatcher {} // ---cut--- bus.setDispatcher(MyEventDispatcher.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicSyncEventDispatcher, type EventBus } from '@nyx-discord/http'; declare const bus: EventBus<{ someEvent: [string] }>; class MyEventDispatcher extends BasicSyncEventDispatcher {} // ---cut--- bus.setDispatcher(MyEventDispatcher.create()); ``` You can do this for built-in buses too, for example the client bus: ```ts twoslash import { Client } from 'discord.js'; import { Bot, type NyxBot, BasicAsyncEventDispatcher } from '@nyx-discord/djs'; declare const client: Client; class MyAsyncDispatcher extends BasicAsyncEventDispatcher {} // @ts-expect-error incomplete example // ---cut--- const bot = Bot.create((bot: NyxBot) => { /** options */ }); bot .getClientEventBus() .setDispatcher(MyAsyncDispatcher.create()); ``` ```ts twoslash import { Client } from 'discord.js'; import { Bot, type NyxBot, BasicAsyncEventDispatcher } from '@nyx-discord/djs-core'; declare const client: Client; class MyAsyncDispatcher extends BasicAsyncEventDispatcher {} // @ts-expect-error incomplete example // ---cut--- const bot = Bot.create((bot: NyxBot) => { /** options */ }); bot .getClientEventBus() .setDispatcher(MyAsyncDispatcher.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { Client } from 'discord.js'; import { Bot, type NyxBot, BasicAsyncEventDispatcher } from '@nyx-discord/http'; declare const client: Client; class MyAsyncDispatcher extends BasicAsyncEventDispatcher {} // @ts-expect-error incomplete example // ---cut--- const bot = Bot.create((bot: NyxBot) => { /** options */ }); bot .getClientEventBus() .setDispatcher(MyAsyncDispatcher.create()); ``` ## Dependencies [#dependencies] The dispatcher has two core dependencies you can customize: } external={false}> Holds and executes event subscriber middlewares. } external={false}> Handles middleware and subscriber execution errors. # Buses (https://nyx-discord.github.io/nyx/guide/extend/events/event-bus) The `EventBus` is the component that stores subscribers and allows events to be emitted to them. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Wrap a new event source (e.g. Redis, WebSockets). | Change how subscribers are called (use a [custom Dispatcher](/extend/events/dispatcher) instead). | | Change how subscribers are stored or retrieved. | Filter events globally (use a [Middleware](/use/events/middlewares) instead). | ## Overriding [#overriding] ### Creation [#creation] Create a custom event bus by either: * Extending `BasicEventBus` (recommended for general purpose). * Extending `BasicEventEmitterBus` (recommended if wrapping a Node.js `EventEmitter`). * Implementing `EventBus` from scratch. ```ts twoslash import { BasicEventBus } from '@nyx-discord/djs'; class MyEventBus extends BasicEventBus<{ myEvent: [string] }> {} ``` ```ts twoslash import { BasicEventBus } from '@nyx-discord/djs-core'; class MyEventBus extends BasicEventBus<{ myEvent: [string] }> {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicEventBus } from '@nyx-discord/http'; class MyEventBus extends BasicEventBus<{ myEvent: [string] }> {} ``` ### Adapting external sources [#adapting-external-sources] If you are wrapping an external source, you can listen to it and call `emit()`: ```ts twoslash import { BasicEventBus, BasicSyncEventDispatcher, DefaultMetadataFactory } from '@nyx-discord/djs'; import type { Identifier, MetadataFactory } from '@nyx-discord/djs'; // Mock external source declare const socket: { on: (event: string, cb: (data: string) => void) => void }; class MySocketBus extends BasicEventBus<{ message: [string] }> { constructor( metaFactory: MetadataFactory = new DefaultMetadataFactory(), ) { super( (a, b) => a.getPriority() - b.getPriority(), BasicSyncEventDispatcher.create(), metaFactory ); // Listen to external source and emit internally socket.on('message', (data) => { this.emit('message', [data]); }); } } ``` ```ts twoslash import { BasicEventBus, BasicSyncEventDispatcher, DefaultMetadataFactory } from '@nyx-discord/djs-core'; import type { Identifier, MetadataFactory } from '@nyx-discord/djs-core'; // Mock external source declare const socket: { on: (event: string, cb: (data: string) => void) => void }; class MySocketBus extends BasicEventBus<{ message: [string] }> { constructor( metaFactory: MetadataFactory = new DefaultMetadataFactory(), ) { super( (a, b) => a.getPriority() - b.getPriority(), BasicSyncEventDispatcher.create(), metaFactory ); // Listen to external source and emit internally socket.on('message', (data) => { this.emit('message', [data]); }); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicEventBus, BasicSyncEventDispatcher, DefaultMetadataFactory } from '@nyx-discord/http'; import type { Identifier, MetadataFactory } from '@nyx-discord/http'; // Mock external source declare const socket: { on: (event: string, cb: (data: string) => void) => void }; class MySocketBus extends BasicEventBus<{ message: [string] }> { constructor( metaFactory: MetadataFactory = new DefaultMetadataFactory(), ) { super( (a, b) => a.getPriority() - b.getPriority(), BasicSyncEventDispatcher.create(), metaFactory ); // Listen to external source and emit internally socket.on('message', (data) => { this.emit('message', [data]); }); } } ``` # Events Internals (https://nyx-discord.github.io/nyx/guide/extend/events) The events system is made up of several components that work together to detect and dispatch events. ## Event system components [#event-system-components] Specifically, these components are: - [`EventDispatcher`](/extend/events/dispatcher): Coordinates middleware checks and subscriber execution for each dispatch. - [`EventBus`](/extend/events/bus): Stores subscribers and emits events. - [`EventSubscriber`](/use/events/subscriber): Receives events and executes logic. ## Execution Sequence [#execution-sequence] The following diagrams show the event flow in focused stages. You can check the guide of each component to see exactly how it works, or how to replace it. - You can zoom and drag on the diagram. - A dashed step means it's executed through a non awaited (but caught) Promise, so the next one is inmediately executed if there's an I/O operation in the step. - You can hover over steps with `(?)` to see extra details. - If a step goes to a target, and that target doesn't continue the flow, then it's an immediate return, like a getter call. ### Event emit [#event-emit] When an object emits an event through an [`EventBus`](/use/events/buses), the bus resolves subscribers and delegates execution to the dispatcher: ### Middleware gate [#middleware-gate] Before subscribers are executed, the [`EventDispatcher`](/extend/events/dispatcher) checks the event middleware list: ### Subscriber dispatch [#subscriber-dispatch] If middleware allows the dispatch, each [`EventSubscriber`](/use/events/subscribers) is executed and thrown errors are forwarded to the error handler: Next, see the documentation of each component, where you'll find what it does and how to replace it. # Extend (https://nyx-discord.github.io/nyx/guide/extend) Welcome to the **Extend** section of the nyx guide. In this section, you'll learn how to customize internals and inject your own components into it. It's recommended you read the [Use](../use) section first to know the behavior of what you're about to modify. For every component, you'll be able to see in the below the title the: - Base definition (the interface in ). - Default implementation (also in ). Both of them linked for GitHub and the web documentation. It's strongly recommended to read the source code of which you want to use. ## Features [#features] Click on each card to go to that feature's manager docs. } external={false}> Learn how commands work and how to edit their internal behavior. } external={false}> Learn how events work and how to edit their internal behavior. } external={false}> Learn how schedules work and how to edit their internal behavior. } external={false}> Learn how sessions work and how to edit their internal behavior. } external={false}> Learn how plugins work and how to edit their internal behavior. # Schedule Internals (https://nyx-discord.github.io/nyx/guide/extend/schedules) The schedule system stores tasks, tracks when they should run, and executes them with middleware and error handling. ## Schedule system components [#schedule-system-components] Specifically, these components are: - [`ScheduleManager`](/extend/schedules/schedule-manager): The entry point for the schedule system, orchestrating the repository, executor, scheduler, and lifecycle events. - [`ScheduleRepository`](/extend/schedules/schedule-repository): Stores all the currently registered schedules. - [`ScheduleExecutionScheduler`](/extend/schedules/schedule-execution-scheduler): Determines *when* a schedule should run next and creates the job adapter. - [`ScheduleJobAdapter`](/extend/schedules/schedule-job-adapter): Wraps the underlying job instance (e.g. a croner `Cron` object, or a timeout). - [`ScheduleExecutor`](/extend/schedules/schedule-executor): Executes schedules, checking their middleware list and handling errors. - [`ScheduleMiddlewareList`](/extend/schedules/schedule-executor/schedule-middleware-list): Manages middlewares for schedule execution, including filters. - [`ScheduleErrorHandler`](/extend/schedules/schedule-executor/schedule-error-handler): Handles middleware and schedule execution errors. ## Execution flow [#execution-flow] ### Registration and lifecycle [#registration-and-lifecycle] When you add a schedule, the `ScheduleManager` stores it in the `ScheduleRepository`, asks the `ScheduleExecutionScheduler` to create a job, and then emits `ScheduleEventEnum.ScheduleAdd`. Removing a schedule follows the same coordination path in reverse and emits `ScheduleEventEnum.ScheduleRemove`. ### Runtime execution [#runtime-execution] When the job fires, the `ScheduleJobAdapter` hands control to the `ScheduleExecutor`, which checks middlewares, executes the schedule's `tick()` method, and forwards errors to the configured `ScheduleErrorHandler`. Next, see the documentation of each component, where you'll find what it does and how to replace it. # Execution Scheduler (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-execution-scheduler) The is responsible for interpreting the schedule's interval (usually a cron string) and creating/managing the that will trigger execution. It relies on the [`ScheduleJobAdapter`](/extend/schedules/schedule-job-adapter) to interface with the actual timing mechanism (e.g. `croner`), and the adapter is the one that waits for the scheduled time and invokes the execution. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Use a different timing library or job backend (e.g., not `croner`). | Just adjust the job adapter itself. Create a custom `ScheduleJobAdapter` instead. | | Support a different interval format or next-run strategy (e.g., RRULE-like scheduling). | Change schedule execution logic (try/catch, retry, middleware behavior). That belongs to `ScheduleExecutor`. | | Implement custom misfire/catch-up behavior for delayed or missed runs. | Change schedule persistence. That belongs to `ScheduleRepository`. | ## Overriding [#overriding] ### Creation [#creation] Create a custom scheduler extending . ```ts twoslash import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs'; class MyScheduler extends DefaultScheduleExecutionScheduler { // Override internal methods } ``` ```ts twoslash import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs-core'; class MyScheduler extends DefaultScheduleExecutionScheduler { // Override internal methods } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleExecutionScheduler } from '@nyx-discord/http'; class MyScheduler extends DefaultScheduleExecutionScheduler { // Override internal methods } ``` ### Registration [#registration] Create it and set it to the [`ScheduleManager`](/extend/schedules/schedule-manager). ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs'; class MyScheduler extends DefaultScheduleExecutionScheduler { /** Your overrides */ } // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs-core'; class MyScheduler extends DefaultScheduleExecutionScheduler { /** Your overrides */ } // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { DefaultScheduleExecutionScheduler } from '@nyx-discord/http'; class MyScheduler extends DefaultScheduleExecutionScheduler { /** Your overrides */ } // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` The method instantiates your custom scheduler, not the default one. # Executor (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-executor) The `ScheduleExecutor` is responsible for the actual execution of a schedule's logic. It runs the schedule's `tick()` method, and also: - Checks the [`ScheduleMiddlewareList`](/extend/schedules/schedule-executor/schedule-middleware-list). - Wraps the execution in a try-catch block. - Emits events for success or failure. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Customize execution behavior, including middleware injection or error handling. | Only change the middleware chain. Use `ScheduleMiddlewareList` for that. | | Instrument executor-owned branches such as success/failure handling. | Only change how errors are consumed. Use `ScheduleErrorHandler` for that. | | Implement custom retry/backoff or exception mapping for failed executions. | Change when schedules run. That belongs to `ScheduleExecutionScheduler` and `ScheduleJobAdapter`. | ## Overriding [#overriding] ### Creation [#creation] Create a custom executor by either: * Extending `DefaultScheduleExecutor` (recommended, less work). * Implementing . ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/djs'; class MyExecutor extends DefaultScheduleExecutor {} ``` ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/djs-core'; class MyExecutor extends DefaultScheduleExecutor {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/http'; class MyExecutor extends DefaultScheduleExecutor {} ``` ### Registration [#registration] Create it and set it to the [`ScheduleManager`](/extend/schedules/schedule-manager). ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/djs'; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- class MyExecutor extends DefaultScheduleExecutor { /** Your overrides */ } bot.getScheduleManager().setExecutor(MyExecutor.create()); ``` ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/djs-core'; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- class MyExecutor extends DefaultScheduleExecutor { /** Your overrides */ } bot.getScheduleManager().setExecutor(MyExecutor.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleExecutor } from '@nyx-discord/http'; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- class MyExecutor extends DefaultScheduleExecutor { /** Your overrides */ } bot.getScheduleManager().setExecutor(MyExecutor.create()); ``` The method instantiates your custom executor, not the default one. ## Dependencies [#dependencies] The executor has two core dependencies you can customize: } external={false}> Holds and executes schedule middlewares before `tick()` runs. } external={false}> Handles middleware and schedule execution errors. # Error Handler (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-executor/schedule-error-handler) The `ScheduleErrorHandler` handles errors thrown while checking middlewares or executing schedule ticks. It's inside the [`ScheduleExecutor`](/extend/schedules/schedule-executor) object, and will be used by it. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Resolve error consumers with custom logic. | Add or remove middlewares. That's done with the executor's middleware list. | | Change fallback behavior for uncaught errors, such as logging or telemetry. | Change when schedules run. That's done with `ScheduleExecutionScheduler` and `ScheduleJobAdapter`. | | Route specific error classes to specialized consumers. | Replace the dispatch flow entirely. If you only want custom error handling, replacing this dependency is enough. | ## Overriding [#overriding] ### Creation [#creation] Create a custom error handler by either: * Extending `BasicErrorHandler` (recommended, less work). * Implementing `ScheduleErrorHandler`. ```ts twoslash import { BasicErrorHandler, type Schedule, type ScheduleTickArgs } from '@nyx-discord/djs'; class MyErrorHandler extends BasicErrorHandler {} ``` ```ts twoslash import { BasicErrorHandler, type Schedule, type ScheduleTickArgs } from '@nyx-discord/djs-core'; class MyErrorHandler extends BasicErrorHandler {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, type Schedule, type ScheduleTickArgs } from '@nyx-discord/http'; class MyErrorHandler extends BasicErrorHandler {} ``` ### Registration [#registration] Inject it directly when creating the executor, then set that executor to the [`ScheduleManager`](/extend/schedules/schedule-manager): ```ts twoslash import { BasicErrorHandler, ScheduleMiddlewareList, DefaultScheduleExecutor, TypedFields, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/djs'; // ---cut--- import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); bot.getScheduleManager().setExecutor(executor); ``` ```ts twoslash import { BasicErrorHandler, ScheduleMiddlewareList, DefaultScheduleExecutor, TypedFields, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/djs-core'; // ---cut--- import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); bot.getScheduleManager().setExecutor(executor); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, ScheduleMiddlewareList, DefaultScheduleExecutor, TypedFields, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/http'; // ---cut--- import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); bot.getScheduleManager().setExecutor(executor); ``` To use the bot logger as fallback, create a handler with `createWithFallbackLogger` and inject it: ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields, type NyxBot, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/djs'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); ``` ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields, type NyxBot, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields, type NyxBot, type Schedule, type ScheduleTickArgs, } from '@nyx-discord/http'; declare const bot: NyxBot; const errorHandler = BasicErrorHandler.createWithFallbackLogger( (_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ); const executor = new DefaultScheduleExecutor( ScheduleMiddlewareList.create(), errorHandler, ); ``` # Middleware List (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-executor/schedule-middleware-list) The `ScheduleMiddlewareList` manages the middlewares that run before a schedule `tick()` is executed. It lives inside the [`ScheduleExecutor`](/extend/schedules/schedule-executor) and is used by it. ## Middleware Execution [#middleware-execution] Middlewares are executed sequentially. If any middleware throws an error or returns without calling `next()`, the schedule execution is aborted and the executor forwards the error to its configured handler. The `ScheduleFilterCheckMiddleware` is a built-in middleware that runs first by default (or as configured) to check if the schedule's `filter` method allows execution. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Customize how middlewares are stored or iterated. | Add middlewares to the existing list. Use a custom `ScheduleExecutor` if you only need different injections. | | Add priority/group ordering semantics beyond simple insertion order. | Change error handling around `tick()` execution. That belongs to `ScheduleErrorHandler`. | | Enforce middleware deduplication or identity-based replacement rules. | Change when schedules are triggered. That belongs to `ScheduleExecutionScheduler`. | ## Overriding [#overriding] ### Creation [#creation] Create a custom `ScheduleMiddlewareList` by either: * Extending `ScheduleMiddlewareList` (recommended, less work). * Implementing `MiddlewareList`. ```ts twoslash import { ScheduleMiddlewareList } from '@nyx-discord/djs'; class MyMiddlewareList extends ScheduleMiddlewareList {} ``` ```ts twoslash import { ScheduleMiddlewareList } from '@nyx-discord/djs-core'; class MyMiddlewareList extends ScheduleMiddlewareList {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { ScheduleMiddlewareList } from '@nyx-discord/http'; class MyMiddlewareList extends ScheduleMiddlewareList {} ``` ### Registration [#registration] Inject it into a custom `DefaultScheduleExecutor`, then set that executor to the [`ScheduleManager`](/extend/schedules/schedule-manager). ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields } from '@nyx-discord/djs'; class MyMiddlewareList extends ScheduleMiddlewareList {} // ---cut--- import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; const executor = new DefaultScheduleExecutor( MyMiddlewareList.create(), BasicErrorHandler.createWithFallbackLogger((_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ), ); bot.getScheduleManager().setExecutor(executor); ``` ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields } from '@nyx-discord/djs-core'; class MyMiddlewareList extends ScheduleMiddlewareList {} // ---cut--- import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const executor = new DefaultScheduleExecutor( MyMiddlewareList.create(), BasicErrorHandler.createWithFallbackLogger((_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ), ); bot.getScheduleManager().setExecutor(executor); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler, DefaultScheduleExecutor, ScheduleMiddlewareList, TypedFields } from '@nyx-discord/http'; class MyMiddlewareList extends ScheduleMiddlewareList {} // ---cut--- import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; const executor = new DefaultScheduleExecutor( MyMiddlewareList.create(), BasicErrorHandler.createWithFallbackLogger((_error, _schedule, [metadata]) => TypedFields.getLogger(metadata), ), ); bot.getScheduleManager().setExecutor(executor); ``` # Job Adapter (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-job-adapter) The wraps a specific scheduled job implementation so the schedule system can interact with jobs (pause, resume, destroy) without knowing the underlying library. There are two default implementations: wraps jobs created by the `croner` library for cron strings and `Date`s, and runs millisecond intervals with its own timer. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Use a different timing/job backend (not `croner`) through a custom [`ScheduleExecutionScheduler`](/extend/schedules/schedule-execution-scheduler). | Change only schedule storage or execution behavior. Those are responsibilities of `ScheduleRepository` and `ScheduleExecutor`. | | Adapt a third-party scheduler/queue API to Nyx's `pause`/`resume`/`destroy` contract. | Only change interval parsing or next-run calculation. That belongs to `ScheduleExecutionScheduler`. | | Wrap platform-specific timer handles (e.g., `setTimeout`-based jobs) behind a uniform adapter API. | Add pre-execution checks. That belongs to `ScheduleMiddlewareList`. | ## Overriding [#overriding] ### Creation [#creation] Create a custom adapter implementing `ScheduleJobAdapter`. ```ts twoslash import type { ScheduleJobAdapter, ScheduleInterval } from '@nyx-discord/djs'; class SimpleTimerAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { // NodeJS.Timeout has no built-in running-state check; illustrative only. return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } ``` ```ts twoslash import type { ScheduleJobAdapter, ScheduleInterval } from '@nyx-discord/djs-core'; class SimpleTimerAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { // NodeJS.Timeout has no built-in running-state check; illustrative only. return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { ScheduleJobAdapter, ScheduleInterval } from '@nyx-discord/http'; class SimpleTimerAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { // NodeJS.Timeout has no built-in running-state check; illustrative only. return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } ``` ### Registration [#registration] Use your adapter from a custom [`ScheduleExecutionScheduler`](/extend/schedules/schedule-execution-scheduler), then set that scheduler to the [`ScheduleManager`](/extend/schedules/schedule-manager). ```ts twoslash import type { ScheduleInterval, ScheduleJobAdapter } from '@nyx-discord/djs'; import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs'; class MyScheduleJobAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } class MyScheduler extends DefaultScheduleExecutionScheduler { // Instantiate your documented adapter in your custom scheduler flow. // @ts-expect-error Incomplete example private readonly adapter = new MyScheduleJobAdapter(/** ... */); } // ---cut--- import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` ```ts twoslash import type { ScheduleInterval, ScheduleJobAdapter } from '@nyx-discord/djs-core'; import { DefaultScheduleExecutionScheduler } from '@nyx-discord/djs-core'; class MyScheduleJobAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } class MyScheduler extends DefaultScheduleExecutionScheduler { // Instantiate your documented adapter in your custom scheduler flow. // @ts-expect-error Incomplete example private readonly adapter = new MyScheduleJobAdapter(/** ... */); } // ---cut--- import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { ScheduleInterval, ScheduleJobAdapter } from '@nyx-discord/http'; import { DefaultScheduleExecutionScheduler } from '@nyx-discord/http'; class MyScheduleJobAdapter implements ScheduleJobAdapter { constructor( private readonly timer: NodeJS.Timeout, private readonly interval: ScheduleInterval ) {} public pause() { clearTimeout(this.timer); return this; } public resume() { this.timer.refresh(); return this; } public destroy() { clearTimeout(this.timer); return this; } public isRunning() { return true; } public getRaw() { return this.timer; } public getInterval() { return this.interval; } } class MyScheduler extends DefaultScheduleExecutionScheduler { // Instantiate your documented adapter in your custom scheduler flow. // @ts-expect-error Incomplete example private readonly adapter = new MyScheduleJobAdapter(/** ... */); } // ---cut--- import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // @noErrors bot.getScheduleManager().setScheduler(MyScheduler.create()); ``` # Manager (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-manager) The `ScheduleManager` is the object that holds together the nyx schedule system. At a glance: - Registration flow: when adding a schedule, stores it in the repository and then starts its runtime job in the scheduler. - Failure safety: if schedule registration fails midway, rolls back repository state and scheduler job creation to stay consistent. - Execution boundary: `tick` resolves a schedule by ID and executes it through the executor with populated metadata. - Schedule events: emits manager-level `ScheduleAdd`/`ScheduleRemove` events and supports subscriptions for schedule lifecycle reactions. In practice, this makes it the boundary where schedule persistence, job lifecycle, execution, and manager events are coordinated. ## Overriding [#overriding] ### Creation [#creation] Create a custom schedule manager by either: * Extending ('s implementation, recommended for less work). * Implementing ('s interface). ```ts twoslash import { DefaultScheduleManager } from '@nyx-discord/djs'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` ```ts twoslash import { DefaultScheduleManager } from '@nyx-discord/djs-core'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleManager } from '@nyx-discord/http'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } ``` ### Registration [#registration] Then you can pass it to your bot: ```ts twoslash import { Client } from 'discord.js'; import { DefaultScheduleManager } from '@nyx-discord/djs'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { Bot, type NyxBot } from '@nyx-discord/djs'; const myBot = Bot.create((bot: NyxBot) => ({ // ---cut-start--- token: 'TOKEN', client: new Client({ intents: [] }), logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options scheduleManager: new MyScheduleManager(/** ... */), })); const manager = myBot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? ``` ```ts twoslash import { Client, GatewayIntentBits } from '@discordjs/core'; import { REST } from '@discordjs/rest'; import { WebSocketManager } from '@discordjs/ws'; import { DefaultScheduleManager } from '@nyx-discord/djs-core'; const rest = new REST({ version: '10' }).setToken('TOKEN'); const gateway = new WebSocketManager({ token: 'TOKEN', intents: GatewayIntentBits.Guilds, rest }); const client = new Client({ rest, gateway }); class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { Bot, CoreNyxClient, type NyxBot } from '@nyx-discord/djs-core'; const myBot = Bot.create((bot: NyxBot) => ({ // ---cut-start--- token: 'TOKEN', client: new CoreNyxClient(client, gateway, 'APPLICATION_ID'), logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options scheduleManager: new MyScheduleManager(/** ... */), })); const manager = myBot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? ``` ```ts twoslash import { DefaultScheduleManager } from '@nyx-discord/http'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import { HttpBot, type NyxBot } from '@nyx-discord/http'; const myBot = HttpBot.create((bot: NyxBot) => ({ // ---cut-start--- applicationId: 'APPLICATION_ID', publicKey: 'PUBLIC_KEY', token: 'TOKEN', logger: console, deployCommands: true, // @ts-expect-error Incomplete example // ---cut-end--- // ... other options scheduleManager: new MyScheduleManager(/** ... */), })); const manager = myBot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? ``` The class is able to infer the type of your custom manager, so accessing any custom method or property will work without errors. If you ever want to use this custom bot type with your injected manager somewhere else, you can do so via the generic: ```ts twoslash import { Client } from 'discord.js'; import { DefaultScheduleManager } from '@nyx-discord/djs'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/djs'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` ```ts twoslash import { Client } from 'discord.js'; import { DefaultScheduleManager } from '@nyx-discord/djs-core'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/djs-core'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { Client } from 'discord.js'; import { DefaultScheduleManager } from '@nyx-discord/http'; class MyScheduleManager extends DefaultScheduleManager { public myCustomPublicMethod() { return 'I work!' as const; } } // ---cut--- import type { NyxBot, InjectableBotDependencies } from '@nyx-discord/http'; type BotWithCustomManager = NyxBot; function functionOnlyForCustomManager(bot: BotWithCustomManager) { const manager = bot.getScheduleManager(); const result = manager.myCustomPublicMethod(); // ^? } ``` For readability purposes, we recommend storing the type with the generic in a separate type, like in the example. # Repository (https://nyx-discord.github.io/nyx/guide/extend/schedules/schedule-repository) The is responsible for storing all the currently registered schedules. ## When to override [#when-to-override] | ✅ Override if you want to... | ❌ Don't override if you want to... | |---|---| | Change schedule persistence (e.g., database instead of in-memory). | Adjust schedule execution or job lifecycle. Use `ScheduleExecutor` or `ScheduleJobAdapter` instead. | | Enforce custom consistency/uniqueness rules at storage level (e.g., dedup by business key). | Change middleware flow or pre-execution checks. That belongs to `ScheduleMiddlewareList`. | | Support multi-tenant partitioning or custom query/filter capabilities in storage. | Change manager event orchestration. That belongs to `ScheduleManager`. | ## Overriding [#overriding] ### Creation [#creation] Create a custom schedule repository by either: * Extending ('s implementation, recommended for less work). * Implementing ('s interface). ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/djs'; class MyScheduleRepository extends DefaultScheduleRepository { public myCustomMethod() { // Custom logic } } ``` ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/djs-core'; class MyScheduleRepository extends DefaultScheduleRepository { public myCustomMethod() { // Custom logic } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/http'; class MyScheduleRepository extends DefaultScheduleRepository { public myCustomMethod() { // Custom logic } } ``` ### Registration [#registration] Create it and set it to the [`ScheduleManager`](/extend/schedules/schedule-manager). ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/djs'; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- class MyScheduleRepository extends DefaultScheduleRepository { /** Your overrides */ } bot.getScheduleManager().setRepository(MyScheduleRepository.create()); ``` ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/djs-core'; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- class MyScheduleRepository extends DefaultScheduleRepository { /** Your overrides */ } bot.getScheduleManager().setRepository(MyScheduleRepository.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { DefaultScheduleRepository } from '@nyx-discord/http'; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- class MyScheduleRepository extends DefaultScheduleRepository { /** Your overrides */ } bot.getScheduleManager().setRepository(MyScheduleRepository.create()); ``` The method instantiates your custom repository, not the default one. # Redirecting... (https://nyx-discord.github.io/nyx/guide/) If you're not redirected, [click here](/use). # Commands (https://nyx-discord.github.io/nyx/guide/loaders/commands) It's recommended to read the [Commands Overview](../use/commands/) page first. The scans a directory for command classes and returns a [] ready for `commandManager.addCommands()`. ## Folder structure [#folder-structure] The loader expects a specific layout, following these rules: 1. Root-level commands are loaded as-is. They must be , , or . 2. A may have a children folder with the same name as its `data.name`. The children folder must contain and/or classes, which are wired to the parent. 3. A may have a nested children folder with the same name as its `data.name`. The nested children folder must contain classes, which are wired to the group. 4. Any subdirectory that does not match a parent/group `data.name` is treated as an organizational folder and recursed into as a new root, continuing the scan with the same rules above. This allows you to organize commands into subfolders without affecting the command hierarchy. 5. Files with multiple classes have each class processed independently. The filenames are completely irrelevant for the loader. The command hierarchy is determined entirely by the `data.name` of each class and the folder structure. ### Example [#example] Assuming the exported command classes have their `data.name` set the same as their file names, the loader will produce the following command hierarchy: | File | Type | Notes | |------|------|-------| | `ping.js` | | Root-level, loaded as-is | | `report-user.js` | | Root-level, loaded as-is | | `mod.js` | | `data.name === "mod"`, children folder matches name | | `mod/ban.js` | | Inside children folder, wired to parent | | `mod/settings.js` | | `data.name === "settings"`, nested folder matches name | | `mod/settings/view.js` | | Inside children folder, wired to group | | `utils/utils.js` | | Inside organizational folder, loaded as root-level | | `utils/format.js` | | Inside organizational folder, loaded as root-level | ## Usage [#usage] By default, commands are automatically registered via `commandManager.addCommands()`: ```ts twoslash import type { NyxBot, DjsInteractionTypes } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; await CommandLoader.load({ bot, path: './dist/commands' }); ``` ```ts twoslash import type { NyxBot, CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; await CommandLoader.load({ bot, path: './dist/commands' }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot, CoreInteractionTypes } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; await CommandLoader.load({ bot, path: './dist/commands' }); ``` Pass `register: false` to handle registration yourself: ```ts twoslash import type { NyxBot, DjsInteractionTypes } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` ```ts twoslash import type { NyxBot, CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot, CoreInteractionTypes } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` ## Writing commands for the loader [#writing-commands-for-the-loader] Top-level commands (standalone, parent, context menu) are instantiated with no constructor arguments: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; import type { Metadata } from '@nyx-discord/djs'; import { SlashCommandBuilder, type ChatInputCommandInteraction } from 'discord.js'; export class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong') .toJSON(); async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { await interaction.reply('Pong!'); } } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; import type { Metadata } from '@nyx-discord/djs-core'; import type { ToEventProps, APIChatInputApplicationCommandInteraction } from '@discordjs/core'; import { SlashCommandBuilder } from 'discord.js'; export class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong') .toJSON(); async execute(interaction: ToEventProps, meta: Metadata) { } } ``` Alternatively, you can specify a `static create(bot)` factory: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; import type { Metadata, NyxBot } from '@nyx-discord/djs'; import { SlashCommandBuilder } from 'discord.js'; export class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong') .toJSON(); public static create(bot: NyxBot) { return new PingCommand(); } // ... // ---cut-start--- public async execute(interaction: any, meta: Metadata) {} // ---cut-end--- } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; import type { Metadata, NyxBot } from '@nyx-discord/djs-core'; import { SlashCommandBuilder } from 'discord.js'; export class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong') .toJSON(); public static create(bot: NyxBot) { return new PingCommand(); } // ... // ---cut-start--- public async execute(interaction: any, meta: Metadata) {} // ---cut-end--- } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; import type { Metadata, NyxBot } from '@nyx-discord/http'; import { SlashCommandBuilder } from 'discord.js'; export class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong') .toJSON(); public static create(bot: NyxBot) { return new PingCommand(); } // ... // ---cut-start--- public async execute(interaction: any, meta: Metadata) {} // ---cut-end--- } ``` Child commands (subcommands and subcommand groups) must accept a `parent` argument in their constructor: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs'; import type { AbstractParentCommand, AbstractSubCommandGroup, Metadata } from '@nyx-discord/djs'; import { SlashCommandSubcommandBuilder, type ChatInputCommandInteraction } from 'discord.js'; export class BanCommand extends AbstractSubCommand { data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); constructor(parent: AbstractParentCommand | AbstractSubCommandGroup) { super(parent); } async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { // ... } } ``` ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs-core'; import type { AbstractParentCommand, AbstractSubCommandGroup, Metadata } from '@nyx-discord/djs-core'; import type { ToEventProps, APIChatInputApplicationCommandInteraction } from '@discordjs/core'; import { SlashCommandSubcommandBuilder } from 'discord.js'; export class BanCommand extends AbstractSubCommand { data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); constructor(parent: AbstractParentCommand | AbstractSubCommandGroup) { super(parent); } async execute(interaction: ToEventProps, meta: Metadata) { // ... } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/http'; import type { AbstractParentCommand, AbstractSubCommandGroup, Metadata } from '@nyx-discord/http'; import type { ToEventProps, APIChatInputApplicationCommandInteraction } from '@discordjs/core'; import { SlashCommandSubcommandBuilder } from 'discord.js'; export class BanCommand extends AbstractSubCommand { data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); constructor(parent: AbstractParentCommand | AbstractSubCommandGroup) { super(parent); } async execute(interaction: ToEventProps, meta: Metadata) { // ... } } ``` Alternatively, you can specify a `static create(bot, parent)` factory: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs'; import type { AbstractParentCommand, AbstractSubCommandGroup, NyxBot } from '@nyx-discord/djs'; import { SlashCommandSubcommandBuilder } from 'discord.js'; export class BanCommand extends AbstractSubCommand { protected readonly data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); public static create(bot: NyxBot, parent: AbstractParentCommand | AbstractSubCommandGroup) { return new BanCommand(parent); } // ... // ---cut-start--- public async execute() {} // ---cut-end--- } ``` ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs-core'; import type { AbstractParentCommand, AbstractSubCommandGroup, NyxBot } from '@nyx-discord/djs-core'; import { SlashCommandSubcommandBuilder } from 'discord.js'; export class BanCommand extends AbstractSubCommand { protected readonly data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); public static create(bot: NyxBot, parent: AbstractParentCommand | AbstractSubCommandGroup) { return new BanCommand(parent); } // ... // ---cut-start--- public async execute() {} // ---cut-end--- } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/http'; import type { AbstractParentCommand, AbstractSubCommandGroup, NyxBot } from '@nyx-discord/http'; import { SlashCommandSubcommandBuilder } from 'discord.js'; export class BanCommand extends AbstractSubCommand { protected readonly data = new SlashCommandSubcommandBuilder() .setName('ban') .setDescription('Ban a user') .toJSON(); public static create(bot: NyxBot, parent: AbstractParentCommand | AbstractSubCommandGroup) { return new BanCommand(parent); } // ... // ---cut-start--- public async execute() {} // ---cut-end--- } ``` The loader will call `static create` instead of the constructor if it exists. This allows you to access the bot instance, or add logic, for example to inject services or other dependencies with a DI container. # Events (https://nyx-discord.github.io/nyx/guide/loaders/events) It's recommended to read the [Events Overview](../use/events) and [Event Subscribers](../events/subscribers) pages first. The scans a directory for event subscriber classes and returns them grouped into six typed arrays. ## Folder structure [#folder-structure] There is no enforced folder structure, any file in any subdirectory at any depth will be classified by the subscriber class it extends: - for Discord.js client events - for command manager events - for bot service events - for plugin manager events - for event bus events - for schedule manager events A recommended convention: ## Usage [#usage] By default, events are automatically subscribed to the appropriate buses: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; await EventLoader.load({ bot, path: './dist/events' }); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; await EventLoader.load({ bot, path: './dist/events' }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; await EventLoader.load({ bot, path: './dist/events' }); ``` Pass `register: false` to handle registration yourself: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', register: false, }); await bot.subscribeToClient(...events.client); await bot.getCommandManager().subscribe(...events.command); await bot.getService().subscribe(...events.service); await bot.getPluginManager().subscribe(...events.plugin); await bot.getScheduleManager().subscribe(...events.schedule); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', register: false, }); await bot.subscribeToClient(...events.client); await bot.getCommandManager().subscribe(...events.command); await bot.getService().subscribe(...events.service); await bot.getPluginManager().subscribe(...events.plugin); await bot.getScheduleManager().subscribe(...events.schedule); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', register: false, }); await bot.subscribeToClient(...events.client); await bot.getCommandManager().subscribe(...events.command); await bot.getService().subscribe(...events.service); await bot.getPluginManager().subscribe(...events.plugin); await bot.getScheduleManager().subscribe(...events.schedule); ``` EventBus subscribers (`events.bus`) cannot be registered automatically, so you need to attach them manually ## Writing subscribers for the loader [#writing-subscribers-for-the-loader] Any class extending one of the six abstract subscriber base classes will be detected: ```ts twoslash import { AbstractDJSClientSubscriber, type Metadata } from '@nyx-discord/djs'; import type { Client } from 'discord.js'; export class ReadySubscriber extends AbstractDJSClientSubscriber<'ready'> { protected readonly event = 'ready' as const; public handleEvent(meta: Metadata, client: Client) { console.log(`Bot logged in as ${client.user.tag}`); } } ``` ```ts twoslash import { AbstractCoreClientSubscriber, type Metadata } from '@nyx-discord/djs-core'; import { type ToEventProps, type GatewayReadyDispatchData, GatewayDispatchEvents } from '@discordjs/core'; export class ReadySubscriber extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.Ready; public handleEvent(meta: Metadata, payload: ToEventProps) { console.log(`Bot logged in as ${payload.data.user.username}`); } } ``` ```ts twoslash import { AbstractCoreClientSubscriber, type Metadata } from '@nyx-discord/http'; import { type APIInteraction, type ToEventProps, GatewayDispatchEvents } from '@discordjs/core'; // gateway events like Ready never fire over HTTP, but interactions do export class InteractionLogSubscriber extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public handleEvent(meta: Metadata, payload: ToEventProps) { console.log(`Received interaction ${payload.data.id}`); } } ``` Top-level subscribers are instantiated with new Class() (no arguments). Subscribers don't receive a parent instance. Alternatively, you can specify a `static create(bot)` factory: ```ts twoslash import { AbstractDJSClientSubscriber } from '@nyx-discord/djs'; import type { NyxBot, Metadata } from '@nyx-discord/djs'; import type { Client } from 'discord.js'; export class ReadySubscriber extends AbstractDJSClientSubscriber<'ready'> { protected readonly event = 'ready' as const; public static create(bot: NyxBot) { return new ReadySubscriber(); } // ... // ---cut-start--- public handleEvent(meta: Metadata, client: Client) {} // ---cut-end--- } ``` ```ts twoslash import { AbstractCoreClientSubscriber } from '@nyx-discord/djs-core'; import type { Bot, Metadata } from '@nyx-discord/djs-core'; import { type ToEventProps, type GatewayReadyDispatchData, GatewayDispatchEvents } from '@discordjs/core'; export class ReadySubscriber extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.Ready; public static create(bot: Bot) { return new ReadySubscriber(); } // ... // ---cut-start--- public handleEvent(meta: Metadata, payload: ToEventProps) {} // ---cut-end--- } ``` ```ts twoslash import { AbstractCoreClientSubscriber } from '@nyx-discord/http'; import type { Bot, Metadata } from '@nyx-discord/http'; import { type APIInteraction, type ToEventProps, GatewayDispatchEvents } from '@discordjs/core'; export class InteractionLogSubscriber extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public static create(bot: Bot) { return new InteractionLogSubscriber(); } // ... // ---cut-start--- public handleEvent(meta: Metadata, payload: ToEventProps) {} // ---cut-end--- } ``` The loader will call this method instead of the constructor if it exists. This allows you to access the bot instance, or add logic, for example to inject services or other dependencies with a DI container. # Overview (https://nyx-discord.github.io/nyx/guide/loaders) The [`@nyx-discord/loaders`](https://www.npmjs.com/package/@nyx-discord/loaders) package provides directory-scanning loaders that automatically discover and instantiate your commands, event subscribers, and schedules from compiled output directories. Instead of manually importing and registering every project file, you point a loader at a directory and it scans `.js` / `.mjs` files, instantiates them, adds them to the Bot, and returns them. ## Installation [#installation] ### Installing [#installing] ```npm npm i @nyx-discord/loaders ``` ### Usage [#usage] Each loader is exposed as a single `load()` method: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { CommandLoader, EventLoader, ScheduleLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands' }); // ^? const events = await EventLoader.load({ bot, path: './dist/events' }); // ^? const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules' }); // ^? ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { CommandLoader, EventLoader, ScheduleLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands' }); // ^? const events = await EventLoader.load({ bot, path: './dist/events' }); // ^? const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules' }); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { CommandLoader, EventLoader, ScheduleLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands' }); // ^? const events = await EventLoader.load({ bot, path: './dist/events' }); // ^? const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules' }); // ^? ``` These returned objects are already added by the loader, they are only returned for informational purposes. ## Options [#options] All loaders share a common options interface: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; // ---cut--- type LoaderOptions = { /** The bot to load objects for. Also passed to static create() methods. */ bot: NyxBot; /** The directory to scan for .js / .mjs files. */ path: string; /** * Whether to auto-register loaded objects with the bot. * @default true */ register?: boolean; /** * Optional filter to include only specific files by their absolute path. * Files returning false are silently skipped. */ filter?: (filePath: string) => boolean; }; ``` ### `register` [#register] Set to `false` to skip automatic registration and handle it yourself: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { CommandLoader } from '@nyx-discord/loaders'; const commands = await CommandLoader.load({ bot, path: './dist/commands', register: false, }); bot.getCommandManager().addCommands(...commands); ``` ### `filter` [#filter] Filter files by their absolute path before they are imported. Useful for excluding tests, dev-only files, or selectively loading subsets: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', filter: (file) => !file.includes('.test.') && !file.includes('.spec.'), }); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', filter: (file) => !file.includes('.test.') && !file.includes('.spec.'), }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { EventLoader } from '@nyx-discord/loaders'; const events = await EventLoader.load({ bot, path: './dist/events', filter: (file) => !file.includes('.test.') && !file.includes('.spec.'), }); ``` The filter is applied before any file is imported, making it efficient for excluding large numbers of files. # Schedules (https://nyx-discord.github.io/nyx/guide/loaders/schedules) The is the simplest loader. It scans a directory recursively for any class extending , instantiates them, and returns a flat []. ## Folder structure [#folder-structure] Any `.js` or `.mjs` file at any depth that exports a class extending will be picked up: ## Usage [#usage] By default, schedules are automatically registered via `scheduleManager.addSchedule()`: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; await ScheduleLoader.load({ bot, path: './dist/schedules' }); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; await ScheduleLoader.load({ bot, path: './dist/schedules' }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; await ScheduleLoader.load({ bot, path: './dist/schedules' }); ``` Pass `register: false` to handle registration yourself: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules', register: false, }); for (const schedule of schedules) { await bot.getScheduleManager().addSchedule(schedule); } ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules', register: false, }); for (const schedule of schedules) { await bot.getScheduleManager().addSchedule(schedule); } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { ScheduleLoader } from '@nyx-discord/loaders'; const schedules = await ScheduleLoader.load({ bot, path: './dist/schedules', register: false, }); for (const schedule of schedules) { await bot.getScheduleManager().addSchedule(schedule); } ``` ## Writing schedules for the loader [#writing-schedules-for-the-loader] ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; import type { Metadata } from '@nyx-discord/djs'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; // Every day at midnight public async tick(meta: Metadata) { // Send daily report... } } ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; import type { Metadata } from '@nyx-discord/djs-core'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; // Every day at midnight public async tick(meta: Metadata) { // Send daily report... } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; import type { Metadata } from '@nyx-discord/http'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; // Every day at midnight public async tick(meta: Metadata) { // Send daily report... } } ``` Schedules are instantiated with new Class() (no arguments). They don't receive a parent instance. Alternatively, you can specify a `static create(bot)` factory: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; import type { Metadata, NyxBot } from '@nyx-discord/djs'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; public static create(bot: NyxBot) { return new DailyReport(); } // ... // ---cut-start--- async tick(meta: Metadata) {} // ---cut-end--- } ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; import type { Metadata, NyxBot } from '@nyx-discord/djs-core'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; public static create(bot: NyxBot) { return new DailyReport(); } // ... // ---cut-start--- async tick(meta: Metadata) {} // ---cut-end--- } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; import type { Metadata, NyxBot } from '@nyx-discord/http'; export class DailyReport extends AbstractSchedule { protected readonly interval = '0 0 * * *'; public static create(bot: NyxBot) { return new DailyReport(); } // ... // ---cut-start--- async tick(meta: Metadata) {} // ---cut-end--- } ``` The loader will call this method instead of the constructor if it exists. This allows you to access the bot instance, or add logic, for example to inject services or other dependencies with a DI container. # Events (https://nyx-discord.github.io/nyx/guide/session/events) It's recommended to read the [Events Overview](../events/index) and [Event Subscribers](../events/subscribers) pages first. The `SessionManager` has an `EventBus` that allows you to listen to events related to sessions. This is useful for monitoring, logging, or any other custom logic you want to execute when a session starts, updates, etc. ## Events [#events] The following events are available: ```ts twoslash import { SessionEventEnum } from '@nyx-discord/plugin-sessions/djs'; // @noErrors SessionEventEnum. // ^| ``` ```ts twoslash import { SessionEventEnum } from '@nyx-discord/plugin-sessions/djs-core'; // @noErrors SessionEventEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { SessionEventEnum } from '@nyx-discord/plugin-sessions/djs-core'; // @noErrors SessionEventEnum. // ^| ``` ## Usage [#usage] ### Subscriber creation [#subscriber-creation] Create a subscriber that will listen to a given event, use the `SessionEventArgs` type for the arguments map. Check the [Event Subscribers](../events/subscribers) page for more information. ### Subscription [#subscription] Subscribe to the event using the `SessionManager`'s `subscribe()` method. ```ts twoslash // ---cut-start--- import { EventSubscriber } from '@nyx-discord/djs'; import type { SessionEventArgs, DjsSessionPlugin } from '@nyx-discord/plugin-sessions/djs'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const sessionPlugin: DjsSessionPlugin; // ---cut-end--- await sessionPlugin.subscribe(subscriber); ``` ```ts twoslash // ---cut-start--- import { EventSubscriber } from '@nyx-discord/djs-core'; import type { SessionEventArgs, CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const sessionPlugin: CoreSessionPlugin; // ---cut-end--- await sessionPlugin.subscribe(subscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventSubscriber } from '@nyx-discord/http'; import type { SessionEventArgs, CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; declare const sessionPlugin: CoreSessionPlugin; // ---cut-end--- await sessionPlugin.subscribe(subscriber); ``` # Filters (https://nyx-discord.github.io/nyx/guide/session/filters) Filters are objects or callbacks that can restrict the execution of a given session. For example: - A [user filter](#user-filter) that restricts the interaction to the user who started the session - A [permission filter](#permission-filter) that checks if the user has the required permissions to interact. Filters receive all the information about the session, the interaction and the execution metadata, and return a boolean indicating whether the session should be executed or not. Unlike other filterable objects, a session can have two filters: the `startFilter` and the `updateFilter`. For more general information about filters, you must first read the general [Filters](/use/other/filters) guide. ## Usage [#usage] In this guide we'll use a regular session, but the same applies to the rest. ### Creation [#creation] Either: - Create a class that extends `AbstractSessionStartFilter` or `AbstractSessionUpdateFilter` and implements the `check()` method. ```ts twoslash import type { Metadata } from '@nyx-discord/djs'; import { AbstractSessionStartFilter, AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs'; import type { Session, SessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; class MyStartFilter extends AbstractSessionStartFilter { public async check(session: Session, meta: Metadata): Promise { // Do some checks return true; // or false if the session should not be executed } } class MyUpdateFilter extends AbstractSessionUpdateFilter { public async check( session: Session, interaction: SessionUpdateInteraction, meta: Metadata ): Promise { // Do some checks return true; // or false if the session should not be executed } } ``` The type argument is the return type of your session. - Create a function that returns a boolean or a Promise that resolves to a boolean. ```ts twoslash import type { SessionStartFilterResolvable, DjsSessionUpdateFilterResolvable } from '@nyx-discord/plugin-sessions/djs'; const myStartFilter: SessionStartFilterResolvable = async (session, meta) => { // Do some checks return true; // or false if the session should not be executed }; const myUpdateFilter: DjsSessionUpdateFilterResolvable = async ( session, interaction, meta, ) => { // Do some checks return true; // or false if the session should not be executed }; ``` ### Filter usage [#filter-usage] Override the `startFilter` or `updateFilter` property in your session: - If you created a class, instantiate it: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- import { AbstractSessionStartFilter, AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs'; class MyStartFilter extends AbstractSessionStartFilter { public async check() { return true; } } class MyUpdateFilter extends AbstractSessionUpdateFilter { public async check() { return true; } } // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = new MyStartFilter(); protected override readonly updateFilter = new MyUpdateFilter(); } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- import { AbstractSessionStartFilter, AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; class MyStartFilter extends AbstractSessionStartFilter { public async check() { return true; } } class MyUpdateFilter extends AbstractSessionUpdateFilter { public async check() { return true; } } // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = new MyStartFilter(); protected override readonly updateFilter = new MyUpdateFilter(); } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- import { AbstractSessionStartFilter, AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; class MyStartFilter extends AbstractSessionStartFilter { public async check() { return true; } } class MyUpdateFilter extends AbstractSessionUpdateFilter { public async check() { return true; } } // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = new MyStartFilter(); protected override readonly updateFilter = new MyUpdateFilter(); } ``` - If you created a function, assign it directly: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- import type { SessionStartFilterResolvable, DjsSessionUpdateFilterResolvable } from '@nyx-discord/plugin-sessions/djs'; declare const myStartFilter: SessionStartFilterResolvable; declare const myUpdateFilter: DjsSessionUpdateFilterResolvable; // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = myStartFilter; protected override readonly updateFilter = myUpdateFilter; } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- import type { SessionStartFilterResolvable, CoreSessionUpdateFilterResolvable } from '@nyx-discord/plugin-sessions/djs-core'; declare const myStartFilter: SessionStartFilterResolvable; declare const myUpdateFilter: CoreSessionUpdateFilterResolvable; // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = myStartFilter; protected override readonly updateFilter = myUpdateFilter; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- import type { SessionStartFilterResolvable, CoreSessionUpdateFilterResolvable } from '@nyx-discord/plugin-sessions/djs-core'; declare const myStartFilter: SessionStartFilterResolvable; declare const myUpdateFilter: CoreSessionUpdateFilterResolvable; // ---cut-end--- class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = myStartFilter; protected override readonly updateFilter = myUpdateFilter; } ``` Or use a simple arrow function directly: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = () => { return true; }; protected override readonly updateFilter = () => { return true; }; } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = () => { return true; }; protected override readonly updateFilter = () => { return true; }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected override readonly startFilter = () => { return true; }; protected override readonly updateFilter = () => { return true; }; } ``` ## Examples [#examples] ### User Filter [#user-filter] A filter that restricts the interaction to the user who started the session. This is commonly used in `updateFilter` to prevent other users from interacting with the session. ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs'; import type { Session, DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes, Metadata } from '@nyx-discord/djs'; class UserFilter extends AbstractSessionUpdateFilter { public async check( session: Session, interaction: DjsSessionUpdateInteraction, meta: Metadata ): Promise { const startInteraction = session.getStartInteraction(); if (!startInteraction) return true; // Check if the user who interacted is the same as the one who started the session return interaction.user.id === startInteraction.user.id; } } ``` ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; import type { Session, CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes, Metadata } from '@nyx-discord/djs-core'; class UserFilter extends AbstractSessionUpdateFilter { public async check( session: Session, interaction: CoreSessionUpdateInteraction, meta: Metadata ): Promise { const startInteraction = session.getStartInteraction(); if (!startInteraction) return true; const user = interaction.data.user ?? interaction.data.member?.user; const startUser = startInteraction.data.user ?? startInteraction.data.member?.user; // Check if the user who interacted is the same as the one who started the session return user?.id === startUser?.id; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; import type { Session, CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes, Metadata } from '@nyx-discord/http'; class UserFilter extends AbstractSessionUpdateFilter { public async check( session: Session, interaction: CoreSessionUpdateInteraction, meta: Metadata ): Promise { const startInteraction = session.getStartInteraction(); if (!startInteraction) return true; const user = interaction.data.user ?? interaction.data.member?.user; const startUser = startInteraction.data.user ?? startInteraction.data.member?.user; // Check if the user who interacted is the same as the one who started the session return user?.id === startUser?.id; } } ``` ### Permission Filter [#permission-filter] A permission filter that checks if the user has the required permissions to interact with the session. ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs'; import type { Session, DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes, Metadata } from '@nyx-discord/djs'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractSessionUpdateFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( session: Session, interaction: DjsSessionUpdateInteraction, meta: Metadata ): Promise { if (!interaction.member || !interaction.inCachedGuild()) { return false; } return interaction.member.permissions.has(this.requiredPermissions); } } ``` ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; import type { Session, CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes, Metadata } from '@nyx-discord/djs-core'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractSessionUpdateFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( session: Session, interaction: CoreSessionUpdateInteraction, meta: Metadata ): Promise { const member = interaction.data.member; if (!member) { return false; } const permissions = BigInt(member.permissions); return (permissions & this.requiredPermissions) === this.requiredPermissions; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionUpdateFilter } from '@nyx-discord/plugin-sessions/djs-core'; import type { Session, CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes, Metadata } from '@nyx-discord/http'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractSessionUpdateFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( session: Session, interaction: CoreSessionUpdateInteraction, meta: Metadata ): Promise { const member = interaction.data.member; if (!member) { return false; } const permissions = BigInt(member.permissions); return (permissions & this.requiredPermissions) === this.requiredPermissions; } } ``` # Overview (https://nyx-discord.github.io/nyx/guide/session) The [`@nyx-discord/plugin-sessions`](https://www.npmjs.com/package/@nyx-discord/plugin-sessions) package is an official [plugin](/use/plugins) that provides and manages user interaction sessions. These are objects that represent an open interaction "session" with a user. You can consider them as a more advanced, opinionated, OOP version of [DJS' Interaction Collectors](https://discordjs.guide/legacy/popular-topics/collectors). They can be used as an easy way to maintain a "conversation" with a user, and respond to interactions that the user makes to it. Some examples of sessions are: * A paginated message that shows a user's moderations, allowing advanced options like filtering by type. * An interactive message that guides a user step by step to accomplish something, like creating a ticket category. * A detailed settings message that allows a user to change their server's settings with buttons, modals or select menus. * In essence, any kind of situation where continuous interaction with a user is needed. ## Quick example [#quick-example] This example features many components used in the same session. Some required component properties are omitted for brevity. ```ts twoslash import { StringSelectMenuBuilder, ButtonBuilder, ActionRowBuilder, ModalBuilder } from 'discord.js'; import type { ButtonInteraction, AnySelectMenuInteraction, ModalSubmitInteraction } from 'discord.js'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { protected override readonly ttl = 5_000; // End 5 seconds after the last interaction public async onStart() { // A select menu that updates this session const selectMenuId = this.buildCustomId('select'); const selectMenu = new StringSelectMenuBuilder().setCustomId(selectMenuId); const selectRow = new ActionRowBuilder().addComponents(selectMenu); // A button that updates this session const buttonId = this.buildCustomId('button'); const button = new ButtonBuilder().setCustomId(buttonId); const buttonRow = new ActionRowBuilder().addComponents(button); await this.startInteraction.reply({ components: [buttonRow, selectRow] }); } public async onEnd() { await this.startInteraction.editReply({ content: 'Bye from session!', components: [], }); } protected async handleButton(interaction: ButtonInteraction) { const modalId = this.buildCustomId('modal'); const myModal = new ModalBuilder().setCustomId(modalId); await interaction.showModal(myModal); return true; } protected async handleSelectMenu(interaction: AnySelectMenuInteraction) { await interaction.reply('You selected: ' + interaction.values[0]); return true; } protected async handleModal(interaction: ModalSubmitInteraction) { const name = interaction.fields.getTextInputValue('name'); await interaction.reply(`Your name is ${name}`); return true; } } ``` ```ts twoslash import { StringSelectMenuBuilder, ButtonBuilder, ActionRowBuilder, ModalBuilder } from '@discordjs/builders'; import { ComponentType } from '@discordjs/core'; import type { APIMessageComponentButtonInteraction, APIMessageComponentSelectMenuInteraction, APIModalSubmitInteraction, ModalSubmitActionRowComponent, ToEventProps, } from '@discordjs/core'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { protected override readonly ttl = 5_000; // End 5 seconds after the last interaction public async onStart() { // A select menu that updates this session const selectMenuId = this.buildCustomId('select'); const selectMenu = new StringSelectMenuBuilder().setCustomId(selectMenuId); const selectRow = new ActionRowBuilder().addComponents(selectMenu); // A button that updates this session const buttonId = this.buildCustomId('button'); const button = new ButtonBuilder().setCustomId(buttonId); const buttonRow = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [buttonRow.toJSON(), selectRow.toJSON()] }, ); } public async onEnd() { await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { content: 'Bye from session!', components: [], }, ); } protected async handleButton(interaction: ToEventProps) { const modalId = this.buildCustomId('modal'); const myModal = new ModalBuilder().setCustomId(modalId); await interaction.api.interactions.createModal( interaction.data.id, interaction.data.token, myModal.toJSON(), ); return true; } protected async handleSelectMenu(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You selected: ' + interaction.data.data.values[0] }, ); return true; } protected async handleModal(interaction: ToEventProps) { const name = interaction.data.data.components .filter((row): row is ModalSubmitActionRowComponent => row.type === ComponentType.ActionRow) .flatMap(row => row.components) .find(component => component.custom_id === 'name')?.value; await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Your name is ${name}` }, ); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { StringSelectMenuBuilder, ButtonBuilder, ActionRowBuilder, ModalBuilder } from '@discordjs/builders'; import { ComponentType } from '@discordjs/core'; import type { APIMessageComponentButtonInteraction, APIMessageComponentSelectMenuInteraction, APIModalSubmitInteraction, ModalSubmitActionRowComponent, ToEventProps, } from '@discordjs/core'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { protected override readonly ttl = 5_000; // End 5 seconds after the last interaction public async onStart() { // A select menu that updates this session const selectMenuId = this.buildCustomId('select'); const selectMenu = new StringSelectMenuBuilder().setCustomId(selectMenuId); const selectRow = new ActionRowBuilder().addComponents(selectMenu); // A button that updates this session const buttonId = this.buildCustomId('button'); const button = new ButtonBuilder().setCustomId(buttonId); const buttonRow = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [buttonRow.toJSON(), selectRow.toJSON()] }, ); } public async onEnd() { await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { content: 'Bye from session!', components: [], }, ); } protected async handleButton(interaction: ToEventProps) { const modalId = this.buildCustomId('modal'); const myModal = new ModalBuilder().setCustomId(modalId); await interaction.api.interactions.createModal( interaction.data.id, interaction.data.token, myModal.toJSON(), ); return true; } protected async handleSelectMenu(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You selected: ' + interaction.data.data.values[0] }, ); return true; } protected async handleModal(interaction: ToEventProps) { const name = interaction.data.data.components .filter((row): row is ModalSubmitActionRowComponent => row.type === ComponentType.ActionRow) .flatMap(row => row.components) .find(component => component.custom_id === 'name')?.value; await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Your name is ${name}` }, ); return true; } } ``` Then somewhere in your code, like inside a command: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import { type ChatInputCommandInteraction } from 'discord.js'; declare const bot: NyxBot; // @ts-expect-error Incomplete example class MySession extends AbstractSession {} // ---cut--- // Can be a command, component or modal interaction declare const startInteraction: ChatInputCommandInteraction; const id = 'mySessionId'; // Should be short and randomly generated, nanoid is good for this const session = new MySession({ bot, id, startInteraction }); await session.start(); // Wait for the session to end await session.getEndPromise(); // Wait 3 seconds await new Promise(resolve => setTimeout(resolve, 3000)); await startInteraction.editReply('Bye from command!'); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; declare const bot: NyxBot; // @ts-expect-error Incomplete example class MySession extends AbstractSession {} // ---cut--- // Can be a command, component or modal interaction declare const startInteraction: ToEventProps; const id = 'mySessionId'; // Should be short and randomly generated, nanoid is good for this const session = new MySession({ bot, id, startInteraction }); await session.start(); // Wait for the session to end await session.getEndPromise(); // Wait 3 seconds await new Promise(resolve => setTimeout(resolve, 3000)); await startInteraction.api.interactions.editReply( startInteraction.data.application_id, startInteraction.data.token, { content: 'Bye from command!' }, ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; declare const bot: NyxBot; // @ts-expect-error Incomplete example class MySession extends AbstractSession {} // ---cut--- // Can be a command, component or modal interaction declare const startInteraction: ToEventProps; const id = 'mySessionId'; // Should be short and randomly generated, nanoid is good for this const session = new MySession({ bot, id, startInteraction }); await session.start(); // Wait for the session to end await session.getEndPromise(); // Wait 3 seconds await new Promise(resolve => setTimeout(resolve, 3000)); await startInteraction.api.interactions.editReply( startInteraction.data.application_id, startInteraction.data.token, { content: 'Bye from command!' }, ); ``` After filling the modal and components with values, this will look like this: Notice how: - The plugin routes interactions belonging to the session to the appropiate handler. - The session finishes automatically after the `ttl` has passed since the last interaction. - The session starter is able to wait for the session to end, and then do what it needs to, like reply further. We'll dive deeper on what each of the methods do later, but this should be enough to give you an idea of how sessions work. ## Installation [#installation] ### Installing [#installing] ```npm npm i @nyx-discord/plugin-sessions ``` ### Registering [#registering] Instantiate and register it to your bot's plugin manager: ```ts twoslash import { type NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { DjsSessionPlugin } from '@nyx-discord/plugin-sessions/djs'; await bot.getPluginManager().register(DjsSessionPlugin.create()); ``` ```ts twoslash import { type NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import { CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; await bot.getPluginManager().register(CoreSessionPlugin.create()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import { CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; await bot.getPluginManager().register(CoreSessionPlugin.create()); ``` And you're done! Check the session types guides to learn how to make your own Session. # Limits (https://nyx-discord.github.io/nyx/guide/session/limits) Session limits cap how many concurrent sessions a user, guild, or channel can have for a given session type. They are enforced **before** a session starts, and they are registered externally via `plugin.getSessionLimits().register(...)`. Limits must be registered and removed **before** starting. Calling `register()` or `remove()` after starting the bot throws an `IllegalStateError`. ## Registration [#registration] Register limits through `plugin.getSessionLimits().register()` before starting the plugin. You can use either a plain object or a builder. ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsSessionLimit } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit: DjsSessionLimit = { session: MySession, rules: [ { max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error, }, ], }; plugin.getSessionLimits().register(limit); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreSessionLimit } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit: CoreSessionLimit = { session: MySession, rules: [ { max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error, }, ], }; plugin.getSessionLimits().register(limit); ``` ```ts twoslash import { DjsSessionPlugin, DjsSessionLimitBuilder, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit = new DjsSessionLimitBuilder() .setSession(MySession) .addRule((rule) => rule .setMax(1) .setScope(SessionLimitScope.User) .setOnExceed(SessionExceedAction.Error), ) .toSessionLimit(); plugin.getSessionLimits().register(limit); ``` ```ts twoslash import { CoreSessionPlugin, CoreSessionLimitBuilder, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit = new CoreSessionLimitBuilder() .setSession(MySession) .addRule((rule) => rule .setMax(1) .setScope(SessionLimitScope.User) .setOnExceed(SessionExceedAction.Error), ) .toSessionLimit(); plugin.getSessionLimits().register(limit); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, CoreSessionLimitBuilder, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit = new CoreSessionLimitBuilder() .setSession(MySession) .addRule((rule) => rule .setMax(1) .setScope(SessionLimitScope.User) .setOnExceed(SessionExceedAction.Error), ) .toSessionLimit(); plugin.getSessionLimits().register(limit); ``` You can pass multiple limits to a single `register()` call and register as many limits as needed before the plugin starts. ## Scopes [#scopes] A scope determines which sessions count toward the limit. Each scope computes a string key from the session's starting interaction. ### User [#user] One session per user. Multiple users can each have their own session. ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, // [!code highlight] onExceed: SessionExceedAction.displace() }], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, // [!code highlight] onExceed: SessionExceedAction.displace() }], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, // [!code highlight] onExceed: SessionExceedAction.displace() }], }); ``` **Example:** An interactive `/counter` command. A user opens a session with increment/decrement buttons. Limit of 1 per user prevents duplicate counter sessions, and opening a second counter silently displaces the first. ### Guild [#guild] One session per guild. DMs are grouped under the key `'dm'`. ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 3, scope: SessionLimitScope.Guild, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 3, scope: SessionLimitScope.Guild, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 3, scope: SessionLimitScope.Guild, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` **Example:** A ticket wizard. The wizard walks the user through category, priority, and description steps. Limit of 3 per guild prevents a noisy server from spawning dozens of incomplete wizards. ### Channel [#channel] One session per channel. Sessions without a `channelId` get the key `'unknown'` (at the time of writing, never the case, but it's still covered for future-proofing). ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.Channel, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.Channel, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.Channel, // [!code highlight] onExceed: SessionExceedAction.Error }], }); ``` **Example:** A live poll session with reaction buttons. Limit of 1 per channel ensures only one active poll runs in a channel at a time. ### Composite [#composite] Combine multiple scopes. For example, one session per user per guild: ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.composite(SessionLimitScope.User, SessionLimitScope.Guild), // [!code highlight] onExceed: SessionExceedAction.displace(), }, ], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.composite(SessionLimitScope.User, SessionLimitScope.Guild), // [!code highlight] onExceed: SessionExceedAction.displace(), }, ], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.composite(SessionLimitScope.User, SessionLimitScope.Guild), // [!code highlight] onExceed: SessionExceedAction.displace(), }, ], }); ``` **Example:** An embedded game like tic-tac-toe. Limit of 1 per user per guild. A user can play one game in each server they're in, but not two games in the same server. ### Custom [#custom] Provide an arbitrary function that returns a string key: ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => AbstractSession; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.custom((s: Session) => s.getStartInteraction().locale), // [!code highlight] onExceed: SessionExceedAction.Error, }, ], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => AbstractSession; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.custom((s: Session) => s.getStartInteraction().data.locale), // [!code highlight] onExceed: SessionExceedAction.Error, }, ], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => AbstractSession; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.custom((s: Session) => s.getStartInteraction().data.locale), // [!code highlight] onExceed: SessionExceedAction.Error, }, ], }); ``` **Example:** A translation-review session. Users with the same Discord locale share one review session across the bot, and only one reviewer per language at a time. ## Actions [#actions] An action defines what happens when the limit is exceeded. ### Error [#error] Throws `SessionLimitExceededError`, which you can catch and reply to the user: ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, SessionLimitExceededError, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; import type { ChatInputCommandInteraction } from 'discord.js'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; declare const session: Session; declare const interaction: ChatInputCommandInteraction; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error // [!code highlight] }], }); // In your command handler: try { await session.start(); } catch (error) { if (error instanceof SessionLimitExceededError) { await interaction.reply({ content: 'You already have an active session.', ephemeral: true }); } } ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, SessionLimitExceededError, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; import type { ChatInputCommandInteraction } from 'discord.js'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; declare const session: Session; declare const interaction: ChatInputCommandInteraction; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error // [!code highlight] }], }); // In your command handler: try { await session.start(); } catch (error) { if (error instanceof SessionLimitExceededError) { await interaction.reply({ content: 'You already have an active session.', ephemeral: true }); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, SessionLimitExceededError, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; import type { ChatInputCommandInteraction } from 'discord.js'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; declare const session: Session; declare const interaction: ChatInputCommandInteraction; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error // [!code highlight] }], }); // In your command handler: try { await session.start(); } catch (error) { if (error instanceof SessionLimitExceededError) { await interaction.reply({ content: 'You already have an active session.', ephemeral: true }); } } ``` **Example:** A profile setup wizard with max 1 per user. The second attempt throws, and the handler catches to reply with a friendly ephemeral message. ### Displace [#displace] Evicts an existing session to make room. The displaced session receives `SessionEndCodes.Displaced`. The existing session is only ended **after** the new one has started. If the new session doesn't start (its start filter rejects it, a middleware stops it, or its `onStart()` throws), the existing session keeps running. Only running sessions are displaced: if every session in the scope is still starting, the new one is rejected with `SessionLimitExceededError`. ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; declare const session: Session; // ---cut--- // Default: replaces the first existing session plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace() // [!code highlight] }], }); // With a custom pick function, e.g. oldest first: plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace((existing: Session[]) => // [!code highlight] existing.reduce((a, b) => ( // [!code highlight] a.getStartInteraction().createdAt < b.getStartInteraction().createdAt ? a : b // [!code highlight] )), // [!code highlight] ), // [!code highlight] }, ], }); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; declare const session: Session; // ---cut--- // Default: replaces the first existing session plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace() // [!code highlight] }], }); // With a custom pick function, e.g. oldest first: plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace((existing: Session[]) => // [!code highlight] existing.reduce((a, b) => ( // [!code highlight] a.getStartInteraction().data.id < b.getStartInteraction().data.id ? a : b // [!code highlight] )), // [!code highlight] ), // [!code highlight] }, ], }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; declare const session: Session; // ---cut--- // Default: replaces the first existing session plugin.getSessionLimits().register({ session: MySession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace() // [!code highlight] }], }); // With a custom pick function, e.g. oldest first: plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.displace((existing: Session[]) => // [!code highlight] existing.reduce((a, b) => ( // [!code highlight] a.getStartInteraction().data.id < b.getStartInteraction().data.id ? a : b // [!code highlight] )), // [!code highlight] ), // [!code highlight] }, ], }); ``` **Example:** An interactive counter. The user runs `/counter`, and if one already exists, it's silently replaced. The old session's `onEnd()` fires, its buttons are disabled, and the promise resolves with `SessionEndCodes.Displaced`. ### Custom [#custom-1] Full control via `ExceedDecision`: ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs'; import type { SessionExceedContext, DjsSessionLimit } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit: DjsSessionLimit = { session: MySession, rules: [ { max: 3, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.custom(async (ctx: SessionExceedContext) => { // [!code highlight] await ctx.attempted.getStartInteraction().reply({ // [!code highlight] content: `Queue full (${ctx.existing.length} dashboards active). Try later.`, // [!code highlight] ephemeral: true, // [!code highlight] }); // [!code highlight] return { proceed: false }; // [!code highlight] }), // [!code highlight] }, ], }; plugin.getSessionLimits().register(limit); ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { SessionExceedContext, CoreSessionLimit } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit: CoreSessionLimit = { session: MySession, rules: [ { max: 3, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.custom(async (ctx: SessionExceedContext) => { // [!code highlight] await ctx.attempted.getStartInteraction().api.interactions.reply( // [!code highlight] ctx.attempted.getStartInteraction().data.id, // [!code highlight] ctx.attempted.getStartInteraction().data.token, // [!code highlight] { content: `Queue full (${ctx.existing.length} dashboards active). Try later.` } // [!code highlight] ); // [!code highlight] return { proceed: false }; // [!code highlight] }), // [!code highlight] }, ], }; plugin.getSessionLimits().register(limit); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { SessionExceedContext, CoreSessionLimit } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- const limit: CoreSessionLimit = { session: MySession, rules: [ { max: 3, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.custom(async (ctx: SessionExceedContext) => { // [!code highlight] await ctx.attempted.getStartInteraction().api.interactions.reply( // [!code highlight] ctx.attempted.getStartInteraction().data.id, // [!code highlight] ctx.attempted.getStartInteraction().data.token, // [!code highlight] { content: `Queue full (${ctx.existing.length} dashboards active). Try later.` } // [!code highlight] ); // [!code highlight] return { proceed: false }; // [!code highlight] }), // [!code highlight] }, ], }; plugin.getSessionLimits().register(limit); ``` - `{ proceed: false }`: throws `SessionLimitExceededError` - `{ proceed: true, displace: null }`: allows the session without eviction (bypassing the limit) - `{ proceed: true, displace: session }`: evicts that specific session and starts **Example:** An admin dashboard with max 3 per guild. On exceed, the custom handler replies with a queue status message and blocks the new session. ## Predicates [#predicates] When you need different limits for the same session type (e.g. premium vs free users), use predicates. ```ts twoslash import { TypedFields, type DjsInteractionTypes } from '@nyx-discord/djs'; import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs'; const Tier = TypedFields.create<'premium' | 'free'>('Tier'); declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register( { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) === 'premium', // [!code highlight] rules: [{ max: 5, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) !== 'premium', // [!code highlight] rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, ); ``` ```ts twoslash import { TypedFields, type CoreInteractionTypes } from '@nyx-discord/djs-core'; import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; const Tier = TypedFields.create<'premium' | 'free'>('Tier'); declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register( { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) === 'premium', // [!code highlight] rules: [{ max: 5, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) !== 'premium', // [!code highlight] rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { TypedFields, type CoreInteractionTypes } from '@nyx-discord/http'; import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; const Tier = TypedFields.create<'premium' | 'free'>('Tier'); declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register( { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) === 'premium', // [!code highlight] rules: [{ max: 5, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, { session: MySession, predicate: (session: Session, meta) => Tier.get(meta) !== 'premium', // [!code highlight] rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }, ); ``` If two or more policies for the same constructor match (or all lack a predicate), an `AmbiguousSessionLimitError` is thrown. Make sure predicates are mutually exclusive. ## Inheritance [#inheritance] Limits are inherited through the prototype chain. When you start a child session, both the parent's and the child's policies are checked (AND semantics). ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const ParentSession: new () => Session; declare const ChildSession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: ParentSession, rules: [{ max: 2, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.Error }], }); plugin.getSessionLimits().register({ session: ChildSession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }); // Starting a ChildSession checks both policies: // 1. At most 2 sessions in the guild (from ParentSession) // 2. At most 1 session per user (from ChildSession) ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const ParentSession: new () => Session; declare const ChildSession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: ParentSession, rules: [{ max: 2, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.Error }], }); plugin.getSessionLimits().register({ session: ChildSession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }); // Starting a ChildSession checks both policies: // 1. At most 2 sessions in the guild (from ParentSession) // 2. At most 1 session per user (from ChildSession) ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, Session } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const ParentSession: new () => Session; declare const ChildSession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: ParentSession, rules: [{ max: 2, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.Error }], }); plugin.getSessionLimits().register({ session: ChildSession, rules: [{ max: 1, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }], }); // Starting a ChildSession checks both policies: // 1. At most 2 sessions in the guild (from ParentSession) // 2. At most 1 session per user (from ChildSession) ``` ## Multiple Rules [#multiple-rules] A single policy can define multiple rules. All rules must pass for the session to start. ```ts twoslash import { DjsSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes } from '@nyx-discord/djs'; declare const plugin: DjsSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 3, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }, { max: 10, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.displace() }, ], }); // Both rules are checked: // - At most 3 per user => Error // - At most 10 per guild => Displace ``` ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 3, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }, { max: 10, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.displace() }, ], }); // Both rules are checked: // - At most 3 per user => Error // - At most 10 per guild => Displace ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CoreSessionPlugin, SessionLimitScope, SessionExceedAction, AbstractSession, Session, } from '@nyx-discord/plugin-sessions/djs-core'; import type { CoreInteractionTypes } from '@nyx-discord/http'; declare const plugin: CoreSessionPlugin; declare const MySession: new () => Session; // ---cut--- plugin.getSessionLimits().register({ session: MySession, rules: [ { max: 3, scope: SessionLimitScope.User, onExceed: SessionExceedAction.Error }, { max: 10, scope: SessionLimitScope.Guild, onExceed: SessionExceedAction.displace() }, ], }); // Both rules are checked: // - At most 3 per user => Error // - At most 10 per guild => Displace ``` # Middlewares (https://nyx-discord.github.io/nyx/guide/session/middlewares) Middlewares are objects or callbacks that run before any session is executed. They can do some pre-processing logic and store it in the metadata, or even prevent the subscriber from being executed. Specifically, sessions have two types of middlewares: one for starting sessions, and one for updating them. For general information about middlewares, you must first read the general [Middlewares](/use/other/middlewares) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `BaseSessionStartMiddleware` or `BaseSessionUpdateMiddleware` and implements the `check()` method. ```ts twoslash import { AbstractSessionStartMiddleware, AbstractSessionUpdateMiddleware } from '@nyx-discord/plugin-sessions/djs'; import type { DjsInteractionTypes, Metadata, MiddlewareResponse, } from '@nyx-discord/djs'; import type { Session, DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; class MyStartMiddleware extends AbstractSessionStartMiddleware { public async check( session: Session, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } class MyUpdateMiddleware extends AbstractSessionUpdateMiddleware { public async check( session: Session, interaction: DjsSessionUpdateInteraction, meta: Metadata ): Promise { return this.true(); } } ``` - Create a function that returns a `MiddlewareResponse`. ```ts twoslash import type { DjsInteractionTypes, Metadata } from '@nyx-discord/djs'; import type { SessionStartMiddlewareResolvable, DjsSessionUpdateMiddlewareResolvable, Session, DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; const myCallbackStartMiddleware: SessionStartMiddlewareResolvable = async ( session: Session, meta: Metadata ) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; const myCallbackUpdateMiddleware: DjsSessionUpdateMiddlewareResolvable = async ( session: Session, interaction: DjsSessionUpdateInteraction, meta: Metadata ) => { return { allowed: true, checkNext: true, }; }; ``` ### Registration [#registration] Register it to the executor's `MiddlewareList`: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; import type { AbstractSessionStartMiddleware, AbstractSessionUpdateMiddleware, SessionStartMiddlewareResolvable, DjsSessionUpdateMiddlewareResolvable, DjsSessionPlugin } from '@nyx-discord/plugin-sessions/djs'; declare const MyStartMiddleware: new () => AbstractSessionStartMiddleware; declare const MyUpdateMiddleware: new () => AbstractSessionUpdateMiddleware; declare const myCallbackUpdateMiddleware: DjsSessionUpdateMiddlewareResolvable; declare const myCallbackStartMiddleware: SessionStartMiddlewareResolvable; declare const sessionPlugin: DjsSessionPlugin; // ---cut--- const executor = sessionPlugin.getExecutor(); executor.getStartMiddleware().add(new MyStartMiddleware(), myCallbackStartMiddleware); executor.getUpdateMiddleware().add(new MyUpdateMiddleware(), myCallbackUpdateMiddleware); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; import type { AbstractSessionStartMiddleware, AbstractSessionUpdateMiddleware, SessionStartMiddlewareResolvable, CoreSessionUpdateMiddlewareResolvable, CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; declare const MyStartMiddleware: new () => AbstractSessionStartMiddleware; declare const MyUpdateMiddleware: new () => AbstractSessionUpdateMiddleware; declare const myCallbackUpdateMiddleware: CoreSessionUpdateMiddlewareResolvable; declare const myCallbackStartMiddleware: SessionStartMiddlewareResolvable; declare const sessionPlugin: CoreSessionPlugin; // ---cut--- const executor = sessionPlugin.getExecutor(); executor.getStartMiddleware().add(new MyStartMiddleware(), myCallbackStartMiddleware); executor.getUpdateMiddleware().add(new MyUpdateMiddleware(), myCallbackUpdateMiddleware); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; import type { AbstractSessionStartMiddleware, AbstractSessionUpdateMiddleware, SessionStartMiddlewareResolvable, CoreSessionUpdateMiddlewareResolvable, CoreSessionPlugin } from '@nyx-discord/plugin-sessions/djs-core'; declare const MyStartMiddleware: new () => AbstractSessionStartMiddleware; declare const MyUpdateMiddleware: new () => AbstractSessionUpdateMiddleware; declare const myCallbackUpdateMiddleware: CoreSessionUpdateMiddlewareResolvable; declare const myCallbackStartMiddleware: SessionStartMiddlewareResolvable; declare const sessionPlugin: CoreSessionPlugin; // ---cut--- const executor = sessionPlugin.getExecutor(); executor.getStartMiddleware().add(new MyStartMiddleware(), myCallbackStartMiddleware); executor.getUpdateMiddleware().add(new MyUpdateMiddleware(), myCallbackUpdateMiddleware); ``` # List Pagination Session (https://nyx-discord.github.io/nyx/guide/session/types/list-pagination-session) It's recommended to read the [Pagination Session](./pagination-session) page first, all of its features apply to this. A `ListPaginationSession` is a special type of pagination session made to paginate a list of items. Initially, the item's values are received at the session's constructor. You can also include a refreshing system in the session to refresh the items with their newest state, if desired. ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractListPaginationSession` class: ```ts twoslash import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyListPaginationSession extends AbstractListPaginationSession {} ``` ```ts twoslash import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyListPaginationSession extends AbstractListPaginationSession {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyListPaginationSession extends AbstractListPaginationSession {} ``` The first type argument is the type of the items, and the second is the session's return type. In `updatePage()` you can now use `getCurrentPageItems()`, which is an utility method that calculates and returns the current page's items. ### Implementation [#implementation] Implement it the same way you'd implement a `PaginationSession`. ### Initialization [#initialization] Instantiate and start your session the same way as a regular one, but passing the list of items: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs'; import { type ChatInputCommandInteraction } from 'discord.js'; declare const startInteraction: ChatInputCommandInteraction; declare const bot: NyxBot; declare const id: string; // @ts-expect-error Incomplete example class MyListPaginationSession extends AbstractListPaginationSession {} // ---cut--- const session = new MyListPaginationSession({ bot, id, startInteraction, items: [1, 2, 3, /** ... */] }); await session.start(); ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; declare const startInteraction: ToEventProps; declare const bot: NyxBot; declare const id: string; // @ts-expect-error Incomplete example class MyListPaginationSession extends AbstractListPaginationSession {} // ---cut--- const session = new MyListPaginationSession({ bot, id, startInteraction, items: [1, 2, 3, /** ... */] }); await session.start(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; import { AbstractListPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; declare const startInteraction: ToEventProps; declare const bot: NyxBot; declare const id: string; // @ts-expect-error Incomplete example class MyListPaginationSession extends AbstractListPaginationSession {} // ---cut--- const session = new MyListPaginationSession({ bot, id, startInteraction, items: [1, 2, 3, /** ... */] }); await session.start(); ``` ## Example [#example] This example will paginate a list of the currently cached guilds: ```ts twoslash import type { NyxBot } from '@nyx-discord/djs'; import { AbstractListPaginationSession, type DjsSessionUpdateInteraction, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; import { ContainerBuilder, SectionBuilder, MessageFlags, type Guild } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { // ^^^^^ constructor(options: { bot: NyxBot; id: string; startInteraction: DjsSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() { const container = this.generateContainer(); const row = this.buildBasicPageRow(); await this.startInteraction.reply({ components: [container, row], flags: MessageFlags.IsComponentsV2, }); } protected async updatePage(interaction: DjsSessionUpdateInteraction): Promise { const container = this.generateContainer(); const row = this.buildBasicPageRow(); if ('update' in interaction) { await interaction.update({ components: [container, row], flags: MessageFlags.IsComponentsV2, }); } return true; } public async onEnd() { const container = this.generateContainer(); await this.startInteraction.editReply({ components: [container], flags: MessageFlags.IsComponentsV2, }); } protected generateContainer(): ContainerBuilder { const guilds = this.getCurrentPageItems(); // [!code highlight] const container = new ContainerBuilder() .addTextDisplayComponents((textDisplay) => textDisplay.setContent('# Guilds')); for (const guild of guilds) { const icon = guild.iconURL(); if (icon) { container.addSectionComponents((section) => section .addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)) .setThumbnailAccessory((thumbnail) => thumbnail.setURL(icon)) ); } else { container.addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)); } } return container; } } ``` ```ts twoslash import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractListPaginationSession, type CoreSessionUpdateInteraction, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import { ContainerBuilder, SectionBuilder, MessageFlags, type Guild } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { // ^^^^^ constructor(options: { bot: NyxBot; id: string; startInteraction: CoreSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() { const container = this.generateContainer(); const row = this.buildBasicPageRow(); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [container.toJSON(), row] } ); } protected async updatePage(interaction: CoreSessionUpdateInteraction): Promise { const container = this.generateContainer(); const row = this.buildBasicPageRow(); await interaction.api.interactions.updateMessage( interaction.data.id, interaction.data.token, { components: [container.toJSON(), row] } ); return true; } public async onEnd() { const container = this.generateContainer(); await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { components: [container.toJSON()] } ); } protected generateContainer(): ContainerBuilder { const guilds = this.getCurrentPageItems(); // [!code highlight] const container = new ContainerBuilder() .addTextDisplayComponents((textDisplay) => textDisplay.setContent('# Guilds')); for (const guild of guilds) { const icon = guild.iconURL(); if (icon) { container.addSectionComponents((section) => section .addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)) .setThumbnailAccessory((thumbnail) => thumbnail.setURL(icon)) ); } else { container.addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)); } } return container; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot } from '@nyx-discord/http'; import { AbstractListPaginationSession, type CoreSessionUpdateInteraction, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import { ContainerBuilder, SectionBuilder, MessageFlags, type Guild } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { // ^^^^^ constructor(options: { bot: NyxBot; id: string; startInteraction: CoreSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() { const container = this.generateContainer(); const row = this.buildBasicPageRow(); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [container.toJSON(), row] } ); } protected async updatePage(interaction: CoreSessionUpdateInteraction): Promise { const container = this.generateContainer(); const row = this.buildBasicPageRow(); await interaction.api.interactions.updateMessage( interaction.data.id, interaction.data.token, { components: [container.toJSON(), row] } ); return true; } public async onEnd() { const container = this.generateContainer(); await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { components: [container.toJSON()] } ); } protected generateContainer(): ContainerBuilder { const guilds = this.getCurrentPageItems(); // [!code highlight] const container = new ContainerBuilder() .addTextDisplayComponents((textDisplay) => textDisplay.setContent('# Guilds')); for (const guild of guilds) { const icon = guild.iconURL(); if (icon) { container.addSectionComponents((section) => section .addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)) .setThumbnailAccessory((thumbnail) => thumbnail.setURL(icon)) ); } else { container.addTextDisplayComponents((textDisplay) => textDisplay.setContent(guild.name)); } } return container; } } ``` You can then use it in your command or anywhere where you have an interaction: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractListPaginationSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; import type { Guild, ContainerBuilder } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { constructor(options: { bot: NyxBot; id: string; startInteraction: DjsSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } protected generateContainer() { return null as unknown as ContainerBuilder; } } declare const startInteraction: DjsSessionStartInteraction; declare const bot: NyxBot; declare const items: Guild[]; const id = 'mySessionId'; // ---cut-end--- const session = new GuildsPaginationSession({ bot, id, startInteraction, items }); await session.start(); ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractListPaginationSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { Guild, ContainerBuilder } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { constructor(options: { bot: NyxBot; id: string; startInteraction: CoreSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } protected generateContainer() { return null as unknown as ContainerBuilder; } } declare const startInteraction: CoreSessionStartInteraction; declare const bot: NyxBot; declare const items: Guild[]; const id = 'mySessionId'; // ---cut-end--- const session = new GuildsPaginationSession({ bot, id, startInteraction, items }); await session.start(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractListPaginationSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { Guild, ContainerBuilder } from 'discord.js'; class GuildsPaginationSession extends AbstractListPaginationSession { constructor(options: { bot: NyxBot; id: string; startInteraction: CoreSessionStartInteraction; items: Guild[]; }) { super(options); } public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } protected generateContainer() { return null as unknown as ContainerBuilder; } } declare const startInteraction: CoreSessionStartInteraction; declare const bot: NyxBot; declare const items: Guild[]; const id = 'mySessionId'; // ---cut-end--- const session = new GuildsPaginationSession({ bot, id, startInteraction, items }); await session.start(); ``` # Pagination Session (https://nyx-discord.github.io/nyx/guide/session/types/pagination-session) It's recommended to read the [Session](./session) page first, all of its features apply to this. A `PaginationSession` is a special type of session made to be paginated (have pages). From a manager's perspective, a pagination session is just a regular session. The pagination logic happens inside the session itself. ## Page switch [#page-switch] A page switch is triggered when the user sends an interaction to the pagination session, and a page can be extracted from it:
  1. It attempts to extract a referred page, depending on the interaction type:
    • Buttons: Extracts from the customId.
    • Select Menu: Extracts from the customId. If no page is present there, and it's a `StringSelectMenu`, and only one value was selected, it extracts from the selected value.
    • Modal: Extracts from the customId. If no page is present there, it iterates through the modal's components, searching for a component whose `customId` is the session's `customId`. If there is one, the page is extracted from said component's value.
  2. If there's no referred page, it behaves like a regular session, passing the interaction to the appropiate handler.
  3. If there's a referred page, it updates its `currentPage` and calls `#updatePage()`.
You can override this behavior by overriding `extractPageFromInteraction()`, or the more concrete methods: - `extractPageFromButton()` for buttons - `extractPageFromSelectMenu()` for select menus - `extractPageFromModal()` for modals ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractPaginationSession` class: ```ts twoslash import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyPaginationSession extends AbstractPaginationSession {} ``` ```ts twoslash import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyPaginationSession extends AbstractPaginationSession {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyPaginationSession extends AbstractPaginationSession {} ``` ### Implementation [#implementation] Apart from the base `Session` implementation, also implement the `updatePage()` method: ```ts twoslash import { AbstractPaginationSession, type DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected async updatePage(interaction: DjsSessionUpdateInteraction): Promise { if ('update' in interaction) { await interaction.update({ content: `Page: ${this.currentPage}` }); } return true; } } ``` ```ts twoslash import { AbstractPaginationSession, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected async updatePage(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.updateMessage(interaction.data.id, interaction.data.token, { content: `Page: ${this.currentPage}`, }); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractPaginationSession, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected async updatePage(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.updateMessage(interaction.data.id, interaction.data.token, { content: `Page: ${this.currentPage}`, }); return true; } } ``` Similarly to `update()`, it must return whether the session's TTL should be renewed or not. ### Initialization [#initialization] Instantiate and start your session the same way as a regular one: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractPaginationSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } } declare const interaction: DjsSessionStartInteraction; declare const bot: NyxBot; const sessionId = 'mySessionId'; // ---cut-end--- const session = new MyPaginationSession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractPaginationSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const sessionId = 'mySessionId'; // ---cut-end--- const session = new MyPaginationSession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractPaginationSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage() { return true; } } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const sessionId = 'mySessionId'; // ---cut-end--- const session = new MyPaginationSession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` ## Pagination customId [#pagination-customid] The page to switch to is usually extracted from the customId. This means you'll need to change the way you build it in case you want to make a component that switches to a specific page. ```ts twoslash import { ButtonBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- // For a specific page const buttonId = this.buildPageCustomId(3); const pageThreeButton = new ButtonBuilder() .setCustomId(buttonId) .setLabel('Go to page 3'); // For the next page const nextPageButtonId = this.buildPageCustomId(this.currentPage + 1); const nextPageButton = new ButtonBuilder() .setCustomId(nextPageButtonId) .setLabel('Next page'); // ---cut-after--- } } ``` ```ts twoslash import { ButtonBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs-core'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- // For a specific page const buttonId = this.buildPageCustomId(3); const pageThreeButton = new ButtonBuilder() .setCustomId(buttonId) .setLabel('Go to page 3'); // For the next page const nextPageButtonId = this.buildPageCustomId(this.currentPage + 1); const nextPageButton = new ButtonBuilder() .setCustomId(nextPageButtonId) .setLabel('Next page'); // ---cut-after--- } } ``` You can add more ways by overriding `extractPageFromButton()`. You can either: * Put the pagination custom id in the select menu itself, making it switch to that page regardless of selection. ```ts twoslash import { SelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- const selectId = this.buildPageCustomId(3); const select = new SelectMenuBuilder() .setCustomId(selectId) .setPlaceholder('Switch to page 3') // ---cut-after--- } } ``` * Put the pagination custom id in the select menu's options, making it switch to that page only when the option is selected. Note that you still need to put the session's custom id in the select menu itself. ```ts twoslash import { StringSelectMenuBuilder, StringSelectMenuOptionBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- const selectId = this.buildCustomId(); const select = new StringSelectMenuBuilder() .setPlaceholder('Go to page...') .setCustomId(selectId) .addOptions([ new StringSelectMenuOptionBuilder() .setLabel('1') .setValue(this.buildPageCustomId(1)), new StringSelectMenuOptionBuilder() .setLabel('2') .setValue(this.buildPageCustomId(2)), ]); // ---cut-after--- } } ``` You can add more ways by overriding `extractPageFromSelectMenu()`. You can either: * Put the pagination custom id in the modal itself, making it switch to that page regardless of values. ```ts twoslash import { ModalBuilder, TextInputBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- const modalId = this.buildPageCustomId(3); const modal = new ModalBuilder() // highlight-next-line .setCustomId(modalId) .setTitle('A modal that switches to page 3'); // ---cut-after--- } } ``` * Put the session's custom id in the modal's components, making it switch to that component's value (if it's a number). Note that you still need to put the session's custom id in the modal. If the component's value is not a number, it will be handled as a regular update (`handleModal()`). ```ts twoslash import { ModalBuilder, TextInputBuilder, ActionRowBuilder } from 'discord.js'; import { AbstractPaginationSession } from '@nyx-discord/plugin-sessions/djs'; // @ts-expect-error Incomplete example class MyPaginationSession extends AbstractPaginationSession { public async start() { // ---cut--- const customId = this.buildCustomId(); const modal = new ModalBuilder() .setCustomId(customId) .setTitle('Type a page number') .addComponents(new ActionRowBuilder().addComponents( new TextInputBuilder().setCustomId(customId) .setLabel('Page') )); // ---cut-after--- } } ``` The `AbstractPaginationSession` has a utility method for building an action row containing two buttons that switch to the previous and next page: ```ts twoslash // ---cut-start--- import { ActionRowBuilder, ButtonBuilder } from 'discord.js'; import { AbstractPaginationSession, type DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage(_interaction: DjsSessionUpdateInteraction) { return true; } public async example() { // ---cut-end--- const row = this.buildBasicPageRow(); await this.startInteraction.reply({ components: [row] }); // ---cut-start--- } } // ---cut-end--- ``` ```ts twoslash // ---cut-start--- import { ActionRowBuilder, ButtonBuilder } from 'discord.js'; import { AbstractPaginationSession, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage(_interaction: CoreSessionUpdateInteraction) { return true; } public async example() { // ---cut-end--- const row = this.buildBasicPageRow(); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row] }, ); // ---cut-start--- } } // ---cut-end--- ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { ActionRowBuilder, ButtonBuilder } from 'discord.js'; import { AbstractPaginationSession, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MyPaginationSession extends AbstractPaginationSession { public async onStart() {} public async onEnd() {} protected async updatePage(_interaction: CoreSessionUpdateInteraction) { return true; } public async example() { // ---cut-end--- const row = this.buildBasicPageRow(); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row] }, ); // ---cut-start--- } } // ---cut-end--- ``` This row uses emoji arrows to avoid issues with localized text. # Session (https://nyx-discord.github.io/nyx/guide/session/types/session) It's recommended to read the [Overview](../) page first. A `Session` is the simplest, most generic object for the sessions API. It replies to interactions it receives and ends after a given TTL. Further session types are based on this one, and are specifically built for other common use cases. ## Usage [#usage] ### Creation [#creation] Extend the `AbstractSession` class: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- ``` There's an optional type argument which is the [return type](#session-result) of your session, which will be explained later. ### Implementation [#implementation] Implement the `onStart` and `onEnd` methods: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { public async onStart() { // Reply to the startInteraction } public async onEnd() { // Do something when the session ends } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() { // Reply to the startInteraction } public async onEnd() { // Do something when the session ends } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() { // Reply to the startInteraction } public async onEnd() { // Do something when the session ends } } ``` Your `onStart` method should perform the initial reply, and `onEnd` any necessary cleanup logic. If the `onStart` method errors, the session will not be registered and the `onEnd` method will not be called. Optionally implement `handleButton`, `handleSelectMenu`, and `handleModal` methods to listen to interactions: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import type { ButtonInteraction, AnySelectMenuInteraction, ModalSubmitInteraction } from 'discord.js'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ButtonInteraction) { // Reply to buttons return true; } protected async handleSelectMenu(interaction: AnySelectMenuInteraction) { // Reply to select menus return true; } protected async handleModal(interaction: ModalSubmitInteraction) { // Reply to modals return true; } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { ToEventProps, APIMessageComponentButtonInteraction, APIMessageComponentSelectMenuInteraction, APIModalSubmitInteraction, } from '@discordjs/core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ToEventProps) { // Reply to buttons return true; } protected async handleSelectMenu(interaction: ToEventProps) { // Reply to select menus return true; } protected async handleModal(interaction: ToEventProps) { // Reply to modals return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { ToEventProps, APIMessageComponentButtonInteraction, APIMessageComponentSelectMenuInteraction, APIModalSubmitInteraction, } from '@discordjs/core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ToEventProps) { // Reply to buttons return true; } protected async handleSelectMenu(interaction: ToEventProps) { // Reply to select menus return true; } protected async handleModal(interaction: ToEventProps) { // Reply to modals return true; } } ``` ### Initialization [#initialization] Somewhere in your code where you want to start a session, create an id for it, instantiate and start the session: In production your ID should be randomly generated using something like [nanoid](https://www.npmjs.com/package/nanoid), and it should be short enough to not collide with extra customId data. You can use [nanoid's collission calculator](https://zelark.github.io/nano-id-cc/) to find out how short your ID needs to be. Consider a collision only happens if two **currently active** sessions have the same ID. ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: DjsSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const sessionId = 'mySessionId'; const session = new MySession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const sessionId = 'mySessionId'; const session = new MySession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const sessionId = 'mySessionId'; const session = new MySession({ bot, id: sessionId, startInteraction: interaction }); await session.start(); ``` ## Component customIds [#component-customids] Given sessions aren't limited to a single `Message`, and the framework needs to know to which session a given component belongs to, you'll need to go through the `buildCustomId` method in order to get your customIds. This will append the necessary information to the customId to allow the framework to know how to route the interaction. You can also append extra data to it by passing it to the method, and it will be saved in the `TypedFields.CustomIdExtra` field. ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import { TypedFields, type Metadata } from '@nyx-discord/djs'; import { ButtonBuilder, ActionRowBuilder, type ButtonInteraction } from 'discord.js'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- public async start() { const customId = this.buildCustomId('my-data'); // [!code highlight] const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.reply({ components: [row] }); } protected async handleButton(interaction: ButtonInteraction, meta: Metadata) { // We can force the get here (`true`) since we know we passed 'my-data' const extra = TypedFields.CustomIdExtra.get(meta, true); // [!code highlight] await interaction.reply(extra); // Replies 'my-data'; return true; } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { TypedFields, type Metadata } from '@nyx-discord/djs-core'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- public async start() { const customId = this.buildCustomId('my-data'); // [!code highlight] const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed 'my-data' const extra = TypedFields.CustomIdExtra.get(meta, true); // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: extra } ); // Replies 'my-data'; return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { TypedFields, type Metadata } from '@nyx-discord/http'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- public async start() { const customId = this.buildCustomId('my-data'); // [!code highlight] const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed 'my-data' const extra = TypedFields.CustomIdExtra.get(meta, true); // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: extra } ); // Replies 'my-data'; return true; } } ``` ### Complex data [#complex-data] If you need to store a complex object as extra data you can consider using the [`@sapphire/string-store`](https://www.npmjs.com/package/@sapphire/string-store) package, which is what the framework and plugin already uses for serialization to short strings: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import { TypedFields, type Metadata } from '@nyx-discord/djs'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder, type ButtonInteraction } from 'discord.js'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async start() { const extra = MySession.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.reply({ components: [row] }); } protected async handleButton(interaction: ButtonInteraction, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MySession.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.reply(`Name: ${deserialized.name}, Age: ${deserialized.age}`); return true; } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { TypedFields, type Metadata } from '@nyx-discord/djs-core'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async start() { const extra = MySession.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MySession.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Name: ${deserialized.name}, Age: ${deserialized.age}` } ); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { TypedFields, type Metadata } from '@nyx-discord/http'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} // ---cut-end--- protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async start() { const extra = MySession.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MySession.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Name: ${deserialized.name}, Age: ${deserialized.age}` } ); return true; } } ``` Check their documentation for more information and examples. ## Session lifecycle [#session-lifecycle] After it's started, a session will have a given TTL before ending. The default is 3 minutes, and it can be overriden per session (in milliseconds): ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- class MySessionTtl extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected readonly ttl = 10_000; // 10 seconds } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- class MySessionTtl extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected readonly ttl = 10_000; // 10 seconds } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; // ---cut-start--- class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } // ---cut-end--- class MySessionTtl extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected readonly ttl = 10_000; // 10 seconds } ``` When the session receives an interaction, it can decide whether or not to renew its TTL by returning `true` on the appropiate handler (or `false` to not renew it): ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import type { ButtonInteraction } from 'discord.js'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ButtonInteraction) { if (interaction.user.id !== this.startInteraction.user.id) { await interaction.reply('You cannot use this button!'); return false; } await interaction.reply('Hello!'); return true; } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ToEventProps) { const userId = interaction.data.member?.user.id ?? interaction.data.user?.id; const startUserId = this.startInteraction.data.member?.user.id ?? this.startInteraction.data.user?.id; if (userId !== startUserId) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You cannot use this button!' } ); return false; } await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' } ); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; class MySession extends AbstractSession { // ---cut-start--- public async onStart() {} public async onEnd() {} // ---cut-end--- protected async handleButton(interaction: ToEventProps) { const userId = interaction.data.member?.user.id ?? interaction.data.user?.id; const startUserId = this.startInteraction.data.member?.user.id ?? this.startInteraction.data.user?.id; if (userId !== startUserId) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You cannot use this button!' } ); return false; } await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' } ); return true; } } ``` This is useful to "filter out" interactions that you don't want to renew the TTL of, like from other users or with invalid input. ### End promise [#end-promise] Sessions are asynchronous by nature, and you may want to wait for a session to finish before continuing. The `getEndPromise()` method returns a promise that resolves when the session ends, either by timeout or manual end. This promise resolves to an object containing the session's final state and result: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: DjsSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const session = new MySession({ bot, id: 'mySessionId', startInteraction: interaction }); await session.start(); // Wait for the session to end const endData = await session.getEndPromise(); console.log('Session ended'); ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const session = new MySession({ bot, id: 'mySessionId', startInteraction: interaction }); await session.start(); // Wait for the session to end const endData = await session.getEndPromise(); console.log('Session ended'); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; // ---cut-end--- const session = new MySession({ bot, id: 'mySessionId', startInteraction: interaction }); await session.start(); // Wait for the session to end const endData = await session.getEndPromise(); console.log('Session ended'); ``` This is particularly useful when you want to perform additional actions after a session completes, such as logging, notifications, or cleanup operations. ### Result [#result] Sessions can specify a `result` that will be passed to awaiters of the session's promise, and the session end event: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs'; import { ButtonBuilder, ActionRowBuilder, type ButtonInteraction } from 'discord.js'; class MySession extends AbstractSession { // ^^^^^^ protected override result = 0; // [!code highlight] public async onStart() {} public async onEnd() {} public async start() { const customId = this.buildCustomId(); const button = new ButtonBuilder() .setLabel('Click to increment!') .setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.reply({ content: this.result.toString(), components: [row], }); } protected async handleButton(interaction: ButtonInteraction) { this.result += 1; // [!code highlight] await interaction.update({ content: this.result.toString() }); return true; } } ``` ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; class MySession extends AbstractSession { // ^^^^^^ protected override result = 0; // [!code highlight] public async onStart() {} public async onEnd() {} public async start() { const customId = this.buildCustomId(); const button = new ButtonBuilder() .setLabel('Click to increment!') .setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { content: this.result.toString(), components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps) { this.result += 1; // [!code highlight] await interaction.api.interactions.updateMessage( interaction.data.id, interaction.data.token, { content: this.result.toString() } ); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSession } from '@nyx-discord/plugin-sessions/djs-core'; import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ToEventProps, APIMessageComponentButtonInteraction } from '@discordjs/core'; class MySession extends AbstractSession { // ^^^^^^ protected override result = 0; // [!code highlight] public async onStart() {} public async onEnd() {} public async start() { const customId = this.buildCustomId(); const button = new ButtonBuilder() .setLabel('Click to increment!') .setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await this.startInteraction.api.interactions.reply( this.startInteraction.data.id, this.startInteraction.data.token, { content: this.result.toString(), components: [row.toJSON()] } ); } protected async handleButton(interaction: ToEventProps) { this.result += 1; // [!code highlight] await interaction.api.interactions.updateMessage( interaction.data.id, interaction.data.token, { content: this.result.toString() } ); return true; } } ``` The default value of the `result` is `null`, which is what consumers will receive if you don't set it. The `onEnd()` method will be called **before** the framework gets the result from the session, so you can use it to make some final changes to it, before it's communicated to the consumer. Then you can await the session's promise to get the result: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: DjsSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); await session.start(); const endData = await session.getEndPromise(); // ^? const result = endData.result; // ^? ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); await session.start(); const endData = await session.getEndPromise(); // ^? const result = endData.result; // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); await session.start(); const endData = await session.getEndPromise(); // ^? const result = endData.result; // ^? ``` A useful use case is to make sessions where a user is "building" something, and you want to get the final result the user inputted. ## Metadata [#metadata] When extending with plugins, you may want to specify extra data for them to read. You can do so with the `Metadata` object, saved on the session. While sessions internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs'; import { AbstractSession, type DjsSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} protected override readonly meta = { someKey: 'someValue', }; } declare const interaction: DjsSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); const meta = session.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/djs-core'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} protected override readonly meta = { someKey: 'someValue', }; } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); const meta = session.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot } from '@nyx-discord/http'; import { AbstractSession, type CoreSessionStartInteraction } from '@nyx-discord/plugin-sessions/djs-core'; class MySession extends AbstractSession { public async onStart() {} public async onEnd() {} protected override readonly meta = { someKey: 'someValue', }; } declare const interaction: CoreSessionStartInteraction; declare const bot: NyxBot; const id = 'mySessionId'; // ---cut-end--- const session = new MySession({ bot, id, startInteraction: interaction }); const meta = session.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/metadata) page for more information. # Stage Pagination Session (https://nyx-discord.github.io/nyx/guide/session/types/stage-pagination-session) It's recommended to read the [Pagination Session](./pagination-session) page first, all of its features apply to this. A `StagePaginationSession` is a special type of pagination session made to paginate a list of stages. ## Stages [#stages] A stage is an object inside a `StagePaginationSession` that represents a single page in the pagination. You can view them as a "nested" session. Switching from one stage to another is the equivalent of switching pages on a pagination component. A stage can: * Be updated, similar to a `Session` update. * Be switched to and reply to the interaction switching to it. * Be left and perform some cleanup logic. * Return a result, similar to a `Session` result. The first stage is a `SessionStartStage`. It behaves exactly the same as any other, except it also has a `SessionStartStage#onStart()` method. ## Pagination [#pagination] The pagination works in a similar way as in the `PaginationSession`. In essence: - A customId not referring to a page is handled by `#update()` of the current stage. - A customId referring to a page makes the session switch to that stage, calling `SessionStage#onSwitch()` on the new one and `SessionStage#onLeave()` on the old one. ## Creation [#creation] There are three things you need to build to create a full `StagePaginationSession`: 1. The start stage 2. The stages (at least one) 3. The session ### Start stage creation [#start-stage-creation] You'll first need to build the first stage of the session, a `SessionStartStage`. #### Class creation [#class-creation] Extend the `AbstractSessionStartStage` class: ```ts twoslash import { AbstractSessionStartStage } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } // ---cut-end--- ``` ```ts twoslash import { AbstractSessionStartStage } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionStartStage } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- ``` #### Implementation [#implementation] Implement: - `onStart()`: Replies to the start interaction. - `onSwitch()`: Replies to the interaction when the user switches to this stage. - `onLeave()`: Performs some cleanup logic when the user leaves the stage. You should not reply to the `onLeave()` interaction, as this will be done by the next stage. ```ts twoslash import { AbstractSessionStartStage, type DjsSessionStartInteraction, type DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; class MySessionStartStage extends AbstractSessionStartStage { // ---cut-start--- protected generateRow() { return null as unknown as ActionRowBuilder; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onStart(interaction: DjsSessionStartInteraction): Promise { await interaction.reply('Welcome to the session!'); } public async onSwitch(interaction: DjsSessionUpdateInteraction): Promise { await interaction.reply('Welcome to this stage!'); this.userOnStage = true; return true; } public async onLeave(interaction: DjsSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` ```ts twoslash import { AbstractSessionStartStage, type CoreSessionStartInteraction, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStartStage extends AbstractSessionStartStage { // ---cut-start--- protected generateRow() { return null as unknown as APIActionRowComponent; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onStart(interaction: CoreSessionStartInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to the session!' } ); } public async onSwitch(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to this stage!' } ); this.userOnStage = true; return true; } public async onLeave(interaction: CoreSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionStartStage, type CoreSessionStartInteraction, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStartStage extends AbstractSessionStartStage { // ---cut-start--- protected generateRow() { return null as unknown as APIActionRowComponent; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onStart(interaction: CoreSessionStartInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to the session!' } ); } public async onSwitch(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to this stage!' } ); this.userOnStage = true; return true; } public async onLeave(interaction: CoreSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` The type argument is the [return type](#stage-result) of your stage, which will be explained later. ### Stages creation [#stages-creation] After the first stage, you can create as many stages as you want. #### Class creation [#class-creation-1] Extend the `AbstractSessionStage` class: ```ts twoslash import { AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; // ---cut-start--- class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } // ---cut-end--- ``` ```ts twoslash import { AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- ``` #### Implementation [#implementation-1] Implement: - `onSwitch()`: Replies to the interaction when the user switches to this stage. - `onLeave()`: Performs some cleanup logic when the user leaves the stage. You should not reply to the `onLeave()` interaction, as this will be done by the next stage. ```ts twoslash import { AbstractSessionStage, type DjsSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; class MySessionStage extends AbstractSessionStage { // ---cut-start--- public async onStart() {} protected generateRow() { return null as unknown as ActionRowBuilder; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onSwitch(interaction: DjsSessionUpdateInteraction): Promise { await interaction.reply('Welcome to this stage!'); this.userOnStage = true; return true; } public async onLeave(interaction: DjsSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` ```ts twoslash import { AbstractSessionStage, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStage extends AbstractSessionStage { // ---cut-start--- public async onStart() {} protected generateRow() { return null as unknown as APIActionRowComponent; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onSwitch(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to this stage!' } ); this.userOnStage = true; return true; } public async onLeave(interaction: CoreSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSessionStage, type CoreSessionUpdateInteraction } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStage extends AbstractSessionStage { // ---cut-start--- public async onStart() {} protected generateRow() { return null as unknown as APIActionRowComponent; } // ---cut-end--- // Example property, not required protected userOnStage = true; public async onSwitch(interaction: CoreSessionUpdateInteraction): Promise { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Welcome to this stage!' } ); this.userOnStage = true; return true; } public async onLeave(interaction: CoreSessionUpdateInteraction): Promise { this.userOnStage = false; } } ``` ### Session creation [#session-creation] After all stages are created, you can create the session. #### Class creation [#class-creation-2] Extend the `AbstractStagePaginationSession` class: ```ts twoslash import type { DjsInteractionTypes } from '@nyx-discord/djs'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } // ---cut-end--- ``` ```ts twoslash import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } // ---cut-end--- ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { CoreInteractionTypes } from '@nyx-discord/http'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } // ---cut-end--- ``` #### Implementation [#implementation-2] Implement `onEnd()` and `stages`: ```ts twoslash import type { DjsInteractionTypes } from '@nyx-discord/djs'; import { AbstractStagePaginationSession, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; // ---cut-start--- import { AbstractSessionStartStage, AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } // ---cut-end--- class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [ new MySessionStartStage(this), new MySessionStage(this) ]; public async onEnd(): Promise { await this.startInteraction.editReply('Session ended!'); } } ``` ```ts twoslash import type { CoreInteractionTypes } from '@nyx-discord/djs-core'; import { AbstractStagePaginationSession, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- import { AbstractSessionStartStage, AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs-core'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [ new MySessionStartStage(this), new MySessionStage(this) ]; public async onEnd(): Promise { await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { content: 'Session ended!' } ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { CoreInteractionTypes } from '@nyx-discord/http'; import { AbstractStagePaginationSession, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; // ---cut-start--- import { AbstractSessionStartStage, AbstractSessionStage } from '@nyx-discord/plugin-sessions/djs-core'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MySessionStage extends AbstractSessionStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } // ---cut-end--- class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [ new MySessionStartStage(this), new MySessionStage(this) ]; public async onEnd(): Promise { await this.startInteraction.api.interactions.editReply( this.startInteraction.data.application_id, this.startInteraction.data.token, { content: 'Session ended!' } ); } } ``` #### Initialization [#initialization] Instantiate and start your session the same way as a regular one: ```ts twoslash // ---cut-start--- import type { DjsInteractionTypes, NyxBot } from '@nyx-discord/djs'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type DjsSessionStartInteraction, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs'; import type { ActionRowBuilder, ButtonBuilder } from 'discord.js'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as ActionRowBuilder; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } declare const startInteraction: DjsSessionStartInteraction; declare const bot: NyxBot; declare const id: string; // ---cut-end--- const session = new MyStagePaginationSession({ bot, startInteraction, id }); await session.start(); ``` ```ts twoslash // ---cut-start--- import type { CoreInteractionTypes, NyxBot } from '@nyx-discord/djs-core'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type CoreSessionStartInteraction, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } declare const startInteraction: CoreSessionStartInteraction; declare const bot: NyxBot; declare const id: string; // ---cut-end--- const session = new MyStagePaginationSession({ bot, startInteraction, id }); await session.start(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { CoreInteractionTypes, NyxBot } from '@nyx-discord/http'; import { AbstractStagePaginationSession, AbstractSessionStartStage, type CoreSessionStartInteraction, type SessionStageArray } from '@nyx-discord/plugin-sessions/djs-core'; import type { APIActionRowComponent, APIButtonComponent } from '@discordjs/core'; class MySessionStartStage extends AbstractSessionStartStage { public async onStart() {} public async onSwitch() { return true; } public async onLeave() {} protected generateRow() { return null as unknown as APIActionRowComponent; } } class MyStagePaginationSession extends AbstractStagePaginationSession { protected readonly stages: SessionStageArray = [new MySessionStartStage(this)]; public async onEnd() {} } declare const startInteraction: CoreSessionStartInteraction; declare const bot: NyxBot; declare const id: string; // ---cut-end--- const session = new MyStagePaginationSession({ bot, startInteraction, id }); await session.start(); ``` # Overview (https://nyx-discord.github.io/nyx/guide/typed-options) The [`@nyx-discord/typed-options`](https://www.npmjs.com/package/@nyx-discord/typed-options) package types the options of your slash commands from the command data itself, so a misspelled name, a wrong option kind or a missing `null` check becomes a compile error. Without it, `interaction.options.getString('reason')` accepts any name, ignores `required` and `choices`, and returns `string | null` even for options Discord always sends. With it, the getters are checked against the data you already write. It doesn't depend on the rest of nyx: it only needs `discord-api-types`. You can use it in any bot that uses discord.js, `@discordjs/core` or raw API payloads, with or without nyx. ## Installation [#installation] ### Installing [#installing] ```npm npm i @nyx-discord/typed-options ``` It has `discord-api-types` as a peer dependency, and `discord.js` as an optional one for the `/djs` entry point. ### Defining the command [#defining-the-command] Create the command data with `chatInput()` and one helper per option kind. The result is plain API JSON, so you register it with any library, or use it as the `data` of a nyx command: ```ts twoslash import { chatInput, string, user } from '@nyx-discord/typed-options'; const data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); ``` ### Reading the options [#reading-the-options] Pass the data and the interaction to `typedOptions()`. The entry point you import it from depends on your library: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { chatInput, string, user } from '@nyx-discord/typed-options'; declare const interaction: ChatInputCommandInteraction; const data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); // ---cut--- import { typedOptions } from '@nyx-discord/typed-options/djs'; const options = typedOptions(data, interaction); const target = options.getUser('target'); // ^? const reason = options.getString('reason'); // ^? ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction } from '@discordjs/core'; import { chatInput, string, user } from '@nyx-discord/typed-options'; declare const interaction: APIChatInputApplicationCommandInteraction; const data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); // ---cut--- import { typedOptions } from '@nyx-discord/typed-options/djs-core'; const options = typedOptions(data, interaction); const target = options.getUser('target'); // ^? const reason = options.getString('reason'); // ^? ``` A mistake in the name, or in the kind of option, doesn't compile: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { chatInput, string, user } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; const data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); // ---cut--- const options = typedOptions(data, interaction); // @errors: 2345 // Error! There is no option named "reasn" options.getString('reasn'); // Error! "target" is a user option, not a string options.getString('target'); ``` ## Entry points [#entry-points] | Entry point | Purpose | |---------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `@nyx-discord/typed-options` | `chatInput()`, `subcommand()`, `group()`, the option helpers, and the types of the getters. Doesn't depend on any Discord library. | | `@nyx-discord/typed-options/djs` | `typedOptions()` for discord.js. It returns `interaction.options` with narrower types, so it costs nothing at runtime. | | `@nyx-discord/typed-options/djs-core` | `typedOptions()` for raw API payloads. It takes the `@discordjs/core` event props or a bare interaction payload, so it also covers the HTTP transport and other libraries. | ## Using it in a nyx command [#using-it-in-a-nyx-command] Read the options from the command's own data: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { AbstractStandaloneCommand } from '@nyx-discord/djs'; import { chatInput, string, user } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; class BanCommand extends AbstractStandaloneCommand { protected readonly data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); public async execute(interaction: ChatInputCommandInteraction) { const options = typedOptions(this.data, interaction); await interaction.reply(`Banning ${options.getUser('target').username}`); } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; import { chatInput, string, user } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs-core'; class BanCommand extends AbstractStandaloneCommand { protected readonly data = chatInput({ name: 'ban', description: 'Ban a member', options: { target: user({ description: 'Who to ban', required: true }), reason: string({ description: 'Why' }), }, }); public async execute(interaction: ToEventProps) { const options = typedOptions(this.data, interaction); await interaction.api.interactions.reply(interaction.data.id, interaction.data.token, { content: `Banning ${options.getUser('target').username}`, }); } } ``` Builders like `SlashCommandBuilder` can't carry literal types, so they keep working but aren't typed. Use `chatInput()` for the commands whose options you want checked. # Options (https://nyx-discord.github.io/nyx/guide/typed-options/options) Each option is defined with a helper, under the name it will have in Discord. The helpers take the same fields as the [API](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure) (`description`, `required`, `choices`, `min_value`...), and `typedOptions()` gives you one getter per option kind. | Helper | Getter | Returns | |-----------------|-------------------------------------------------|----------------------------------------| | `string()` | `getString()` | `string` | | `integer()` | `getInteger()` | `number` | | `number()` | `getNumber()` | `number` | | `boolean()` | `getBoolean()` | `boolean` | | `user()` | `getUser()`, `getMember()` | The user, and the member | | `channel()` | `getChannel()` | The channel | | `role()` | `getRole()` | The role | | `mentionable()` | `getMentionable()` | A user, member or role | | `attachment()` | `getAttachment()` | The attachment | Every getter only accepts the names of options of its own kind. What it returns is the same as in your library, so `getUser()` returns a `User` on discord.js and an `APIUser` with raw payloads. ## Required options [#required-options] A getter returns `null` unless the option is `required: true`, in which case Discord always sends it and the type is not nullable: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { chatInput, string } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; // ---cut--- const data = chatInput({ name: 'report', description: 'Report something', options: { title: string({ description: 'Title', required: true }), details: string({ description: 'Details' }), }, }); const options = typedOptions(data, interaction); const title = options.getString('title'); // ^? const details = options.getString('details'); // ^? ``` ## Choices [#choices] When an option has `choices`, the getter returns the union of their values: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { chatInput, integer, string } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; // ---cut--- const data = chatInput({ name: 'ban', description: 'Ban a member', options: { mode: string({ description: 'How', required: true, choices: [ { name: 'Soft', value: 'soft' }, { name: 'Hard', value: 'hard' }, ], }), days: integer({ description: 'Days of messages to delete', choices: [ { name: 'None', value: 0 }, { name: 'Week', value: 7 }, ], }), }, }); const options = typedOptions(data, interaction); const mode = options.getString('mode'); // ^? const days = options.getInteger('days'); // ^? ``` ## Users and members [#users-and-members] A `user()` option resolves to a user, but the user might not be in the guild (or the command might run in a DM), so `getMember()` is **always** nullable, even for required options: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { chatInput, user } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; // ---cut--- const data = chatInput({ name: 'kick', description: 'Kick a member', options: { target: user({ description: 'Who', required: true }), }, }); const options = typedOptions(data, interaction); const target = options.getUser('target'); // ^? const member = options.getMember('target'); // ^? ``` ## Channels [#channels] `channel_types` narrows the channel the getter returns: ```ts twoslash import { ChannelType, type ChatInputCommandInteraction } from 'discord.js'; import { channel, chatInput } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; // ---cut--- const data = chatInput({ name: 'log', description: 'Set the log channel', options: { target: channel({ description: 'Where', required: true, channel_types: [ChannelType.GuildText], }), }, }); const options = typedOptions(data, interaction); const target = options.getChannel('target'); // ^? ``` ## Mentionables [#mentionables] `getMentionable()` returns the union of what a mentionable can be: a user, a member or a role. Use `getMember()` and `getRole()` for the other kinds' own options. ## Raw payloads [#raw-payloads] With `@nyx-discord/typed-options/djs-core` there is no library to resolve the options for you, so `typedOptions()` reads them from the payload and looks up the users, members, channels, roles and attachments in `resolved` by their ID. Options missing from the payload are `null`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction } from '@discordjs/core'; import { chatInput, user } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs-core'; declare const payload: APIChatInputApplicationCommandInteraction; // ---cut--- const data = chatInput({ name: 'kick', description: 'Kick a member', options: { target: user({ description: 'Who', required: true }), }, }); const options = typedOptions(data, payload); const target = options.getUser('target'); // ^? ``` It takes the interaction payload itself, or the `@discordjs/core` event props that wrap it as `data`, so it works the same for the gateway, for [HTTP bots](/use/http) and for any other library. # Subcommands (https://nyx-discord.github.io/nyx/guide/typed-options/subcommands) A command with subcommands has no options of its own, so `chatInput()` takes a list of `subcommands` instead. Create each one with `subcommand()`, and group them with `group()`: ```ts twoslash import { chatInput, group, string, subcommand } from '@nyx-discord/typed-options'; const add = subcommand({ name: 'add', description: 'Add a tag', options: { name: string({ description: 'The tag name', required: true }), }, }); const purge = subcommand({ name: 'purge', description: 'Delete every tag' }); const data = chatInput({ name: 'tag', description: 'Manage tags', subcommands: [add, group({ name: 'admin', description: 'Admin tools', subcommands: [purge] })], }); ``` ## Reading a subcommand's options [#reading-a-subcommands-options] Subcommand and group names are typed as `string`, so which subcommand ran is not inferred from the interaction. Instead, pass **the subcommand's own data** to `typedOptions()` to type its options: ```ts twoslash import type { ChatInputCommandInteraction } from 'discord.js'; import { string, subcommand } from '@nyx-discord/typed-options'; import { typedOptions } from '@nyx-discord/typed-options/djs'; declare const interaction: ChatInputCommandInteraction; // ---cut--- const add = subcommand({ name: 'add', description: 'Add a tag', options: { name: string({ description: 'The tag name', required: true }), }, }); const options = typedOptions(add, interaction); const name = options.getString('name'); // ^? ``` This fits nyx's [subcommands](/use/commands/types/parent/subcommand), which already live in their own class: define the subcommand's data there and read the options from it. With raw payloads, `typedOptions()` finds the options inside the subcommand (and its group) for you. # Components (https://nyx-discord.github.io/nyx/guide/use/commands/components) You can make your components sent by your commands trigger a callback in the command itself, instead of having to listen to `interactionCreate` separately. This is only recommended for simple non complex components that originate directly from a command. For other cases, create an [`interactionCreate` subscriber](/use/events). Given only these are executable, you can only use this in [Standalone Commands](./types/standalone), [SubCommands](./types/subcommand) and [Context Menu Commands](./types/context-menu). ## Usage [#usage] In this example we'll use a standalone command, but the same applies to the rest. ### Bot extraction [#bot-extraction] You'll first need your bot instance, since it contains the codec used to de/serialize the customIds. You can either instantiate your command with it, or get it from the execution metadata: ```ts twoslash import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs'; import type { ChatInputCommandInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); // ^? } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields } from '@nyx-discord/djs-core'; import type { Metadata } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); // ^? } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields } from '@nyx-discord/http'; import type { Metadata } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); // ^? } } ``` To learn more about TypedFields, check the [Metadata](../other/meta) page. ### Component creation [#component-creation] Create your component the same way you'd normally do, but use the `bot` instance to create the customId: ```ts twoslash import { ButtonBuilder, ActionRowBuilder } from 'discord.js'; import type { ChatInputCommandInteraction } from 'discord.js'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot); // [!code highlight] // Other properties omitted for brevity const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await interaction.reply({ components: [row] }); } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { ComponentType, ButtonStyle } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot); // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { components: [{ type: ComponentType.ActionRow, components: [{ type: ComponentType.Button, style: ButtonStyle.Success, custom_id: customId, label: 'Button' }] }] }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { ComponentType, ButtonStyle } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot); // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { components: [{ type: ComponentType.ActionRow, components: [{ type: ComponentType.Button, style: ButtonStyle.Success, custom_id: customId, label: 'Button' }] }] }, ); } } ``` ### Interaction handling [#interaction-handling] When the component is clicked, the respective callback will be executed: - `handleButton` for buttons - `handleSelectMenu` for select menus - `handleModal` for modals ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; import type { ButtonInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async handleButton(interaction: ButtonInteraction) { await interaction.reply('You clicked the button!'); } } ``` ```ts twoslash import type { APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async handleButton(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You clicked the button!' }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async handleButton(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'You clicked the button!' }, ); } } ``` ## Attaching extra data [#attaching-extra-data] You can also attach an extra string to the customId, which will be sent back when the component is clicked. The `buildCustomId` method accepts an optional `data` parameter, which can be any string. When the component is clicked, the metadata will contain the data you passed in the customId. It's cached there so you don't need to de-serialize it again. ```ts twoslash import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs'; import type { ButtonInteraction, ChatInputCommandInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot, 'my-data'); } public async handleButton(interaction: ButtonInteraction, meta: Metadata) { const extra = TypedFields.CustomIdExtra.get(meta, true); await interaction.reply(extra) // Replies 'my-data' } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot, 'my-data'); } public async handleButton(interaction: ToEventProps, meta: Metadata) { const extra = TypedFields.CustomIdExtra.get(meta, true); await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: extra }, // Replies 'my-data' ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const customId = this.buildCustomId(bot, 'my-data'); } public async handleButton(interaction: ToEventProps, meta: Metadata) { const extra = TypedFields.CustomIdExtra.get(meta, true); await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: extra }, // Replies 'my-data' ); } } ``` ### Complex data [#complex-data] If you need to store a complex object as extra data you can consider using the [`@sapphire/string-store`](https://www.npmjs.com/package/@sapphire/string-store) package, which is what the framework already uses for serialization to short strings: ```ts twoslash import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder, type ButtonInteraction, type ChatInputCommandInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const extra = MyCommand.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(bot, extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await interaction.reply({ components: [row] }); } protected async handleButton(interaction: ButtonInteraction, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MyCommand.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.reply(`Name: ${deserialized.name}, Age: ${deserialized.age}`); } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs-core'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder } from '@discordjs/builders'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const extra = MyCommand.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(bot, extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { components: [row.toJSON()] }, ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MyCommand.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Name: ${deserialized.name}, Age: ${deserialized.age}` }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, APIMessageComponentButtonInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/http'; import { Schema, SchemaStore } from '@sapphire/string-store'; import { ButtonBuilder, ActionRowBuilder } from '@discordjs/builders'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected static readonly Store = new SchemaStore() // Add an schema with a 'name' field stored as a string and an 'age' field stored as a int32: .add(new Schema(0).string('name').int32('age')); public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); const extra = MyCommand.Store.serialize(0, { age: 25, name: 'amgelo563' }); // [!code highlight] const customId = this.buildCustomId(bot, extra); const button = new ButtonBuilder().setCustomId(customId); const row = new ActionRowBuilder().addComponents(button); await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { components: [row.toJSON()] }, ); } protected async handleButton(interaction: ToEventProps, meta: Metadata) { // We can force the get here (`true`) since we know we passed an extra const extra = TypedFields.CustomIdExtra.get(meta, true); const deserialized = MyCommand.Store.deserialize(extra).data; // { age: 25, name: 'amgelo563' } // [!code highlight] await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: `Name: ${deserialized.name}, Age: ${deserialized.age}` }, ); } } ``` Check their documentation for more information and examples. ## Referring to other commands [#referring-to-other-commands] You can also execute other commands callbacks by creating a customId that refers to them. In order to do so, you'll need the command instance first. You can read how to obtain it in the [Command Location](./location) page. ```ts twoslash // ---cut-start--- import { StandaloneCommand } from '@nyx-discord/djs'; declare const commandInstance: StandaloneCommand; // ---cut-end--- import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs'; import type { ChatInputCommandInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ChatInputCommandInteraction, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); /** Somehow get the command instance using one of the provided methods, eg: */ const command = bot.getCommandManager().getRepository().getCommandByName('my-other-command'); if (!command || command.isParent()) return; /** Then build the customId: */ const customId = command.buildCustomId(bot); } } ``` ```ts twoslash // ---cut-start--- import { StandaloneCommand } from '@nyx-discord/djs-core'; declare const commandInstance: StandaloneCommand; // ---cut-end--- import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); /** Somehow get the command instance using one of the provided methods, eg: */ const command = bot.getCommandManager().getRepository().getCommandByName('my-other-command'); if (!command || command.isParent()) return; /** Then build the customId: */ const customId = command.buildCustomId(bot); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { StandaloneCommand } from '@nyx-discord/http'; declare const commandInstance: StandaloneCommand; // ---cut-end--- import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async execute(interaction: ToEventProps, meta: Metadata) { const bot = TypedFields.Bot.get(meta, true); /** Somehow get the command instance using one of the provided methods, eg: */ const command = bot.getCommandManager().getRepository().getCommandByName('my-other-command'); if (!command || command.isParent()) return; /** Then build the customId: */ const customId = command.buildCustomId(bot); } } ``` When the button is clicked, the `MyOtherCommand`'s `handleButton` callback will be executed. # Events (https://nyx-discord.github.io/nyx/guide/use/commands/events) It's recommended to read the [Events Overview](../events/index) and [Event Subscribers](../events/subscribers) pages first. The `CommandManager` has an `EventBus` that allows you to listen to events related to commands. This is useful for monitoring, logging, or any other custom logic you want to execute when a command is executed. ## Events [#events] The following events are available: ```ts twoslash import { CommandEventEnum } from '@nyx-discord/djs'; // @noErrors CommandEventEnum. // ^| ``` ```ts twoslash import { CommandEventEnum } from '@nyx-discord/djs-core'; // @noErrors CommandEventEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { CommandEventEnum } from '@nyx-discord/http'; // @noErrors CommandEventEnum. // ^| ``` ## Usage [#usage] ### Subscriber creation [#subscriber-creation] Create a subscriber that will listen to a given event, use the `CommandEventArgs` type for the arguments map. Check the [Event Subscribers](../events/subscribers) page for more information. ### Subscription [#subscription] Subscribe to the event using the `CommandManager`'s `subscribe()` method. ```ts twoslash // ---cut-start--- import { EventSubscriber, CommandEventArgs } from '@nyx-discord/djs'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- await bot.getCommandManager().subscribe(subscriber); ``` ```ts twoslash // ---cut-start--- import { EventSubscriber, CommandEventArgs } from '@nyx-discord/djs-core'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- await bot.getCommandManager().subscribe(subscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventSubscriber, CommandEventArgs } from '@nyx-discord/http'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- await bot.getCommandManager().subscribe(subscriber); ``` # Filters (https://nyx-discord.github.io/nyx/guide/use/commands/filters) Filters restrict the execution of a given command. You may be familiar with them from other usages, like: - A [cooldown filter](#cooldown-filter) that prevents a command from being executed too frequently - A [permission filter](#permission-filter) that checks if a member has some required permissions. They receive all the information about the command, the interaction that triggered it, and the execution metadata, and return a boolean indicating whether the command should be executed or not. For more general information about filters, you must first read the general [Filters](/use/other/filters) guide. Given only these are executable, you can only use this in [Standalone Commands](./types/standalone), [SubCommands](./types/subcommand) and [Context Menu Commands](./types/context-menu). ## Usage [#usage] In this example we'll use a standalone command, but the same applies to the rest. ### Creation [#creation] The command will simply not be called if the filter returns `false`, so if you want some kind of reply, you'll need to do it yourself in the filter. Either: - Create a class that extends `AbstractCommandFilter` and implements the `check()` method. ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs'; import type { DjsAnyExecutableCommand, DjsCommandResolvableInteraction, Metadata } from '@nyx-discord/djs'; class MyFilter extends AbstractCommandFilter { public async check( command: DjsAnyExecutableCommand, interaction: DjsCommandResolvableInteraction, meta: Metadata ): Promise { // Do some checks return true; // or false if the command should not be executed } } ``` ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs-core'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/djs-core'; class MyFilter extends AbstractCommandFilter { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { // Do some checks return true; // or false if the command should not be executed } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/http'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/http'; class MyFilter extends AbstractCommandFilter { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { // Do some checks return true; // or false if the command should not be executed } } ``` - Create a function that returns a boolean or a Promise that resolves to a boolean. ```ts twoslash import { type DjsCommandFilterResolvable } from '@nyx-discord/djs'; const myFilter: DjsCommandFilterResolvable = async (command, interaction, meta) => { // Do some checks return true; // or false if the command should not be executed }; ``` ```ts twoslash import { type CoreCommandFilterResolvable } from '@nyx-discord/djs-core'; const myFilter: CoreCommandFilterResolvable = async (command, interaction, meta) => { // Do some checks return true; // or false if the command should not be executed }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type CoreCommandFilterResolvable } from '@nyx-discord/http'; const myFilter: CoreCommandFilterResolvable = async (command, interaction, meta) => { // Do some checks return true; // or false if the command should not be executed }; ``` ### Filter usage [#filter-usage] Override the `filter` property in your command: - If you created a class, instantiate it: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- import { AbstractCommandFilter } from '@nyx-discord/djs'; // @ts-expect-error Incomplete example class MyFilter extends AbstractCommandFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = new MyFilter(); } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- import { AbstractCommandFilter } from '@nyx-discord/djs-core'; // @ts-expect-error Incomplete example class MyFilter extends AbstractCommandFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = new MyFilter(); } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- import { AbstractCommandFilter } from '@nyx-discord/http'; // @ts-expect-error Incomplete example class MyFilter extends AbstractCommandFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = new MyFilter(); } ``` - If you created a function, assign it directly: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- import { type DjsCommandFilterResolvable } from '@nyx-discord/djs'; declare const myFilter: DjsCommandFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = myFilter; } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- import { type CoreCommandFilterResolvable } from '@nyx-discord/djs-core'; declare const myFilter: CoreCommandFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = myFilter; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- import { type CoreCommandFilterResolvable } from '@nyx-discord/http'; declare const myFilter: CoreCommandFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = myFilter; } ``` Or use a simple arrow function directly: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = () => { // Do some checks return true; }; } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = () => { // Do some checks return true; }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly filter = () => { // Do some checks return true; }; } ``` ## Examples [#examples] ### Cooldown Filter [#cooldown-filter] A simple cooldown filter that prevents a command from being executed too frequently, while also cleaning up expired cooldowns every minute: ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs'; import type { DjsAnyExecutableCommand, DjsCommandResolvableInteraction, Metadata } from '@nyx-discord/djs'; class CooldownFilter extends AbstractCommandFilter { protected readonly cooldowns = new Map(); protected readonly sweepInterval: NodeJS.Timeout; protected readonly timeout: number; constructor(timeout: number = 5000) { super(); this.timeout = timeout; this.sweepInterval = setInterval(() => { const now = Date.now(); for (const [userId, expiresAt] of this.cooldowns) { if (now >= expiresAt) { this.cooldowns.delete(userId); } } }, 60_000).unref(); } public async check( command: DjsAnyExecutableCommand, interaction: DjsCommandResolvableInteraction, meta: Metadata ): Promise { const userId = interaction.user.id; const now = Date.now(); const cooldownUntil = this.cooldowns.get(userId) ?? 0; if (now < cooldownUntil) { // Ideally reply to the interaction, telling the user they are on cooldown return false; } this.cooldowns.set(userId, now + this.timeout); return true; } } ``` ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs-core'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/djs-core'; class CooldownFilter extends AbstractCommandFilter { protected readonly cooldowns = new Map(); protected readonly sweepInterval: NodeJS.Timeout; protected readonly timeout: number; constructor(timeout: number = 5000) { super(); this.timeout = timeout; this.sweepInterval = setInterval(() => { const now = Date.now(); for (const [userId, expiresAt] of this.cooldowns) { if (now >= expiresAt) { this.cooldowns.delete(userId); } } }, 60_000).unref(); } public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { const user = interaction.data.user ?? interaction.data.member?.user; const userId = user?.id ?? ''; const now = Date.now(); const cooldownUntil = this.cooldowns.get(userId) ?? 0; if (now < cooldownUntil) { // Ideally reply to the interaction, telling the user they are on cooldown return false; } this.cooldowns.set(userId, now + this.timeout); return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/http'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/http'; class CooldownFilter extends AbstractCommandFilter { protected readonly cooldowns = new Map(); protected readonly sweepInterval: NodeJS.Timeout; protected readonly timeout: number; constructor(timeout: number = 5000) { super(); this.timeout = timeout; this.sweepInterval = setInterval(() => { const now = Date.now(); for (const [userId, expiresAt] of this.cooldowns) { if (now >= expiresAt) { this.cooldowns.delete(userId); } } }, 60_000).unref(); } public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { const user = interaction.data.user ?? interaction.data.member?.user; const userId = user?.id ?? ''; const now = Date.now(); const cooldownUntil = this.cooldowns.get(userId) ?? 0; if (now < cooldownUntil) { // Ideally reply to the interaction, telling the user they are on cooldown return false; } this.cooldowns.set(userId, now + this.timeout); return true; } } ``` ### Permission Filter [#permission-filter] A permission filter that checks if a member has the required permissions to execute a command: ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs'; import type { DjsAnyExecutableCommand, DjsCommandResolvableInteraction, Metadata } from '@nyx-discord/djs'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractCommandFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( command: DjsAnyExecutableCommand, interaction: DjsCommandResolvableInteraction, meta: Metadata ): Promise { if (!interaction.member || !interaction.inCachedGuild()) { // This will depend on whether you want to allow outside of cached guilds or not return false; } if (!interaction.member.permissions.has(this.requiredPermissions)) { // Ideally reply to the interaction, telling the user they lack permissions return false; } return true; } } ``` ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/djs-core'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/djs-core'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractCommandFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { const member = interaction.data.member; if (!member) { return false; } const permissions = BigInt(member.permissions); if ((permissions & this.requiredPermissions) !== this.requiredPermissions) { return false; } return true; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCommandFilter } from '@nyx-discord/http'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/http'; import { PermissionFlagsBits } from 'discord.js'; class PermissionFilter extends AbstractCommandFilter { protected readonly requiredPermissions: bigint; constructor(requiredPermissions: bigint) { super(); this.requiredPermissions = requiredPermissions; } public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { const member = interaction.data.member; if (!member) { return false; } const permissions = BigInt(member.permissions); if ((permissions & this.requiredPermissions) !== this.requiredPermissions) { return false; } return true; } } ``` # Commands Overview (https://nyx-discord.github.io/nyx/guide/use/commands) Commands are how your bot responds to user interactions. Nyx **only** supports application commands. It doesn't and won't support message content commands (like `!ping`). If you really need such functionality, you can implement it yourself using the `messageCreate` event, but this isn't advised. Application commands improve DX and UX significantly, and don't require a privileged intent to work. ## Quick example [#quick-example] Let's create a simple ping command: ```ts twoslash import { type NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut--- import { SlashCommandBuilder, type ChatInputCommandInteraction } from 'discord.js'; import { AbstractStandaloneCommand } from '@nyx-discord/djs'; class PingCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with Pong!') .toJSON(); public async execute(interaction: ChatInputCommandInteraction) { await interaction.reply('Pong!'); } } // Register the command await bot.getCommandManager().addCommands(new PingCommand()); ``` ```ts twoslash import { type NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut--- import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; class PingCommand extends AbstractStandaloneCommand { protected readonly data = { name: 'ping', description: 'Replies with Pong!', }; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Pong!' }, ); } } // Register the command await bot.getCommandManager().addCommands(new PingCommand()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut--- import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/http'; class PingCommand extends AbstractStandaloneCommand { protected readonly data = { name: 'ping', description: 'Replies with Pong!', }; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Pong!' }, ); } } // Register the command await bot.getCommandManager().addCommands(new PingCommand()); ``` That's it! Your bot now has a `/ping` command that replies with "Pong!" when used. The framework doesn't store any state in the instance, so you can reuse it across multiple bot instances without any problems. ## Command deployment [#command-deployment] For commands to be deployed at Discord, you must either pass `deployCommands: true` when creating the bot, or deploy them manually. ```ts twoslash import { Client } from 'discord.js'; declare const client: Client; // ---cut--- import { Bot } from '@nyx-discord/djs'; const myBot = Bot.create((bot) => ({ // ---cut-start--- token: 'TOKEN', client: client, logger: console, // ---cut-end--- // ... other options deployCommands: true, })); ``` ```ts twoslash import { Client, GatewayIntentBits } from '@discordjs/core'; import { REST } from '@discordjs/rest'; import { WebSocketManager } from '@discordjs/ws'; const rest = new REST({ version: '10' }).setToken('TOKEN'); const gateway = new WebSocketManager({ token: 'TOKEN', intents: GatewayIntentBits.Guilds, rest }); const client = new Client({ rest, gateway }); // ---cut--- import { Bot, CoreNyxClient } from '@nyx-discord/djs-core'; const myBot = Bot.create((bot) => ({ // ---cut-start--- token: 'TOKEN', client: new CoreNyxClient(client, gateway, 'APPLICATION_ID'), logger: console, // ---cut-end--- // ... other options deployCommands: true, })); ``` ```ts twoslash import { HttpBot } from '@nyx-discord/http'; const myBot = HttpBot.create((bot) => ({ // ---cut-start--- applicationId: 'APPLICATION_ID', publicKey: 'PUBLIC_KEY', token: 'TOKEN', logger: console, // ---cut-end--- // ... other options deployCommands: true, })); ``` Then, when starting the bot, it will automatically deploy them. You can also deploy manually: This will throw if you passed `deployCommands: true` or already called it before. ```ts twoslash import { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut--- await bot.getCommandManager().deploy(); ``` ```ts twoslash import { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut--- await bot.getCommandManager().deploy(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut--- await bot.getCommandManager().deploy(); ``` ### Add or deploy first? [#add-or-deploy-first] If you add a command after commands have already been deployed, the framework will have to make an API call to register it. This is not recommended due to ratelimits, so it's best to add all the commands *before* deploying (you can add commands before starting the bot). ## Command types [#command-types] Commands are categorized into several types, depending on their purposes: Click on each card to learn more about that type. } external={false}> Slash commands with no children, like `/ping` or `/help`. } external={false}> Slash commands that contain subcommands or subcommand groups, like `/user` with `/user info`. } external={false}> Executable commands that live inside parents or subcommand groups, like `info` in a `/user` parent. } external={false}> Non executable groups inside parent commands, like `settings` in a `/user settings view` command. } external={false}> Commands that appear when users right-click on messages or users. # Location (https://nyx-discord.github.io/nyx/guide/use/commands/location) Sometimes you may need a reference to a currently registered command. You can do so using the `CommandRepository` of your command manager. ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- const repository = bot.getCommandManager().getRepository(); // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- repository.locateBy // ^| ``` ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- const repository = bot.getCommandManager().getRepository(); // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- repository.locateBy // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- const repository = bot.getCommandManager().getRepository(); // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- repository.locateBy // ^| ``` ### Location by name [#location-by-name] Use the `locateByNameTree()` method to find a command by its name tree, which is a string representation of the command's hierarchy, e.g. `parent sub-command`. ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/djs'; declare const repository: CommandRepository; // ---cut-end--- const topLevel = repository.locateByNameTree('top-level-command'); // ^? const subCommandOrGroup = repository.locateByNameTree('parent', 'sub-command-or-group'); // ^? const subCommand = repository.locateByNameTree('parent', 'sub-command-group', 'sub-command'); // ^? ``` ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/djs-core'; declare const repository: CommandRepository; // ---cut-end--- const topLevel = repository.locateByNameTree('top-level-command'); // ^? const subCommandOrGroup = repository.locateByNameTree('parent', 'sub-command-or-group'); // ^? const subCommand = repository.locateByNameTree('parent', 'sub-command-group', 'sub-command'); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/http'; declare const repository: CommandRepository; // ---cut-end--- const topLevel = repository.locateByNameTree('top-level-command'); // ^? const subCommandOrGroup = repository.locateByNameTree('parent', 'sub-command-or-group'); // ^? const subCommand = repository.locateByNameTree('parent', 'sub-command-group', 'sub-command'); // ^? ``` This however only returns the generic base types, not a specific class instance. If you need a specific type, use the following method. ### Location by class [#location-by-class] The `locateByClassTree()` method allows you to find a command by its class hierarchy, which is useful if you want to get a specific command type. ```ts twoslash // ---cut-start--- import { AbstractStandaloneCommand, AbstractSubCommand, AbstractParentCommand, AbstractSubCommandGroup, CommandRepository } from '@nyx-discord/djs'; // @ts-expect-error Incomplete example class MyStandaloneCommand extends AbstractStandaloneCommand {} // @ts-expect-error Incomplete example class MySubCommand extends AbstractSubCommand {} // @ts-expect-error Incomplete example class MyParentCommand extends AbstractParentCommand {} // @ts-expect-error Incomplete example class MySubCommandGroup extends AbstractSubCommandGroup {} declare const repository: CommandRepository; // ---cut-end--- const standalone = repository.locateByClassTree(MyStandaloneCommand); // ^? const subCommand = repository.locateByClassTree(MyParentCommand, MySubCommand); // ^? const subCommandGroup = repository.locateByClassTree(MyParentCommand, MySubCommandGroup); // ^? ``` ```ts twoslash // ---cut-start--- import { AbstractStandaloneCommand, AbstractSubCommand, AbstractParentCommand, AbstractSubCommandGroup, CommandRepository } from '@nyx-discord/djs-core'; // @ts-expect-error Incomplete example class MyStandaloneCommand extends AbstractStandaloneCommand {} // @ts-expect-error Incomplete example class MySubCommand extends AbstractSubCommand {} // @ts-expect-error Incomplete example class MyParentCommand extends AbstractParentCommand {} // @ts-expect-error Incomplete example class MySubCommandGroup extends AbstractSubCommandGroup {} declare const repository: CommandRepository; // ---cut-end--- const standalone = repository.locateByClassTree(MyStandaloneCommand); // ^? const subCommand = repository.locateByClassTree(MyParentCommand, MySubCommand); // ^? const subCommandGroup = repository.locateByClassTree(MyParentCommand, MySubCommandGroup); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { AbstractStandaloneCommand, AbstractSubCommand, AbstractParentCommand, AbstractSubCommandGroup, CommandRepository } from '@nyx-discord/http'; // @ts-expect-error Incomplete example class MyStandaloneCommand extends AbstractStandaloneCommand {} // @ts-expect-error Incomplete example class MySubCommand extends AbstractSubCommand {} // @ts-expect-error Incomplete example class MyParentCommand extends AbstractParentCommand {} // @ts-expect-error Incomplete example class MySubCommandGroup extends AbstractSubCommandGroup {} declare const repository: CommandRepository; // ---cut-end--- const standalone = repository.locateByClassTree(MyStandaloneCommand); // ^? const subCommand = repository.locateByClassTree(MyParentCommand, MySubCommand); // ^? const subCommandGroup = repository.locateByClassTree(MyParentCommand, MySubCommandGroup); // ^? ``` Notice how the return type of each call is the respective instance (or `null`), not the generic types. ## Getting commands [#getting-commands] Alternatively, you can get all top level commands with the `getCommands()` method, which returns a `ReadonlyCollection` of them, keyed by name. This returns the local store, not a copy of it. Hence why it's typed as readonly. However, you may type assert and manipulate it, but it's not safe to do so. ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/djs'; declare const repository: CommandRepository; // ---cut-end--- const topLevels = repository.getCommands(); // ^? ``` ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/djs-core'; declare const repository: CommandRepository; // ---cut-end--- const topLevels = repository.getCommands(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { CommandRepository } from '@nyx-discord/http'; declare const repository: CommandRepository; // ---cut-end--- const topLevels = repository.getCommands(); // ^? ``` # Middlewares (https://nyx-discord.github.io/nyx/guide/use/commands/middlewares) Middlewares are objects or callbacks that run before any command is executed. They can do some pre-processing logic and store it in the metadata, or even prevent the command from being executed. For general information about middlewares, you must first read the general [Middlewares](/use/other/middlewares) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `AbstractCommandMiddleware` and implements the `check()` method. ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/djs'; import type { DjsAnyExecutableCommand, DjsCommandResolvableInteraction, Metadata, MiddlewareResponse } from '@nyx-discord/djs'; class MyMiddleware extends AbstractCommandMiddleware { public async check( command: DjsAnyExecutableCommand, interaction: DjsCommandResolvableInteraction, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/djs-core'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata, MiddlewareResponse } from '@nyx-discord/djs-core'; class MyMiddleware extends AbstractCommandMiddleware { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/http'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata, MiddlewareResponse } from '@nyx-discord/http'; class MyMiddleware extends AbstractCommandMiddleware { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` - Create a function that returns a `MiddlewareResponse`. ```ts twoslash import { type DjsCommandMiddlewareResolvable, MiddlewareResponse } from '@nyx-discord/djs'; const myCallbackMiddleware: DjsCommandMiddlewareResolvable = async (command, interaction, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ```ts twoslash import { type CoreCommandMiddlewareResolvable, MiddlewareResponse } from '@nyx-discord/djs-core'; const myCallbackMiddleware: CoreCommandMiddlewareResolvable = async (command, interaction, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type CoreCommandMiddlewareResolvable, MiddlewareResponse } from '@nyx-discord/http'; const myCallbackMiddleware: CoreCommandMiddlewareResolvable = async (command, interaction, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ### Registration [#registration] Register it to the executor's `MiddlewareList`: ```ts twoslash import type { NyxBot, AbstractCommandMiddleware, DjsCommandMiddlewareResolvable } from '@nyx-discord/djs'; declare const MyMiddleware: new () => AbstractCommandMiddleware; declare const myCallbackMiddleware: DjsCommandMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getCommandManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` ```ts twoslash import type { NyxBot, AbstractCommandMiddleware, CoreCommandMiddlewareResolvable } from '@nyx-discord/djs-core'; declare const MyMiddleware: new () => AbstractCommandMiddleware; declare const myCallbackMiddleware: CoreCommandMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getCommandManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot, AbstractCommandMiddleware, CoreCommandMiddlewareResolvable } from '@nyx-discord/http'; declare const MyMiddleware: new () => AbstractCommandMiddleware; declare const myCallbackMiddleware: CoreCommandMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getCommandManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` ## Examples [#examples] ### Logging middleware [#logging-middleware] ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/djs'; import type { DjsAnyExecutableCommand, DjsCommandResolvableInteraction, Metadata } from '@nyx-discord/djs'; class LoggingMiddleware extends AbstractCommandMiddleware { public async check( command: DjsAnyExecutableCommand, interaction: DjsCommandResolvableInteraction, meta: Metadata ) { console.log(`User ${interaction.user.tag} is executing command ${command.getData().name}`); return this.true(); } } ``` ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/djs-core'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/djs-core'; class LoggingMiddleware extends AbstractCommandMiddleware { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ) { const user = interaction.data.user ?? interaction.data.member?.user; console.log(`User ${user?.username} is executing command ${command.getData().name}`); return this.true(); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCommandMiddleware } from '@nyx-discord/http'; import type { CoreAnyExecutableCommand, CoreCommandResolvableInteraction, Metadata } from '@nyx-discord/http'; class LoggingMiddleware extends AbstractCommandMiddleware { public async check( command: CoreAnyExecutableCommand, interaction: CoreCommandResolvableInteraction, meta: Metadata ) { const user = interaction.data.user ?? interaction.data.member?.user; console.log(`User ${user?.username} is executing command ${command.getData().name}`); return this.true(); } } ``` # Context Menu Commands (https://nyx-discord.github.io/nyx/guide/use/commands/types/context-menu) Context menu commands are commands executed on special menus. Currently Discord has two types of context menus: * [Message Context Menus](https://discord.com/developers/docs/interactions/application-commands#message-commands), shown when right clicking on a message. * [User Context Menus](https://discord.com/developers/docs/interactions/application-commands#user-commands), shown when right clicking on a user. ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractContextMenuCommand` class: ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyContextMenuCommand extends AbstractContextMenuCommand {} ``` ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyContextMenuCommand extends AbstractContextMenuCommand {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyContextMenuCommand extends AbstractContextMenuCommand {} ``` ### Implementation [#implementation] Implement `data` that stores the command's data, and the respective `executeX()` method: - `executeMessage()` for message context menus. - `executeUser()` for user context menus. ```ts twoslash import { ApplicationCommandType, ContextMenuCommandBuilder, type MessageContextMenuCommandInteraction } from 'discord.js'; import { AbstractContextMenuCommand } from '@nyx-discord/djs'; class MyContextMenuCommand extends AbstractContextMenuCommand { protected readonly data = new ContextMenuCommandBuilder() .setName('My Context Menu') .setType(ApplicationCommandType.User) // or ApplicationCommandType.Message .toJSON(); public async executeMessage(interaction: MessageContextMenuCommandInteraction) { await interaction.reply('Hello!'); } } ``` ```ts twoslash import { ApplicationCommandType } from '@discordjs/core'; import type { APIMessageApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractContextMenuCommand } from '@nyx-discord/djs-core'; class MyContextMenuCommand extends AbstractContextMenuCommand { protected readonly data = { name: 'My Context Menu', type: ApplicationCommandType.User, // or ApplicationCommandType.Message } as const; public async executeMessage(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { ApplicationCommandType } from '@discordjs/core'; import type { APIMessageApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractContextMenuCommand } from '@nyx-discord/http'; class MyContextMenuCommand extends AbstractContextMenuCommand { protected readonly data = { name: 'My Context Menu', type: ApplicationCommandType.User, // or ApplicationCommandType.Message } as const; public async executeMessage(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` ### Registration [#registration] Instantiate and register it to a bot's `CommandManager`. ```ts twoslash import type { ContextMenuCommand, NyxBot } from '@nyx-discord/djs'; declare const MyContextMenuCommand: new () => ContextMenuCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyContextMenuCommand()); ``` ```ts twoslash import type { ContextMenuCommand, NyxBot } from '@nyx-discord/djs-core'; declare const MyContextMenuCommand: new () => ContextMenuCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyContextMenuCommand()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { ContextMenuCommand, NyxBot } from '@nyx-discord/http'; declare const MyContextMenuCommand: new () => ContextMenuCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyContextMenuCommand()); ``` ## Guild deployment [#guild-deployment] By default, all commands will be deployed in the global scope. If you want to deploy them in a specific guild, you can do so by implementing the `getGuilds()` method. ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` ## Execution Meta [#execution-meta] The second argument of the execute methods is a `Metadata` object, which is a `Record` that stores metadata about the command call. Apart from the keys saved by the caller or the middleware, the dispatch meta contains: * The execution ID, via the `TypedFields.Id` field. * The execution start date, via the `TypedFields.CreationDate` field. * The bot whose `Client` sent the interaction, via the `TypedFields.Bot` field. To learn more about TypedFields, check the [Metadata](/use/other/meta) page. ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the command. While commands internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractContextMenuCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractContextMenuCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. ## Advanced features [#advanced-features] Click on each card to learn more about that feature. } href="../components"> Handle components interactions directly in the subcommand that sent them, without a separate `interactionCreate` listener. } href="../filters"> Add pre-execution checks to your subcommand, like permissions or cooldowns. } href="../middlewares"> Run code before every command's execution, like logging or pre-conditions. # Parent Commands (https://nyx-discord.github.io/nyx/guide/use/commands/types/parent) It's recommended to read the [Commands Overview](../../index) page first. Parent commands are top-level, non executable commands that can have children, which can be either subcommands commands or subcommand groups. ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractParentCommand` class: ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand {} ``` ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand {} ``` ### Implementation [#implementation] Implement `data` that stores the command's data. The `data` field must not contain any option, only the base values (name, description, etc). If they are included, they will be ignored. ```ts twoslash import { SlashCommandBuilder } from 'discord.js'; import { AbstractParentCommand } from '@nyx-discord/djs'; class MyCommand extends AbstractParentCommand { protected readonly data = new SlashCommandBuilder() .setName('my-command') .setDescription('My command') .toJSON(); } ``` ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/djs-core'; class MyCommand extends AbstractParentCommand { protected readonly data = { name: 'my-command', description: 'My command', }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/http'; class MyCommand extends AbstractParentCommand { protected readonly data = { name: 'my-command', description: 'My command', }; } ``` ### Registration [#registration] Instantiate and register it to a bot's `CommandManager`. ```ts twoslash import type { ParentCommand, NyxBot } from '@nyx-discord/djs'; declare const MyCommand: new () => ParentCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` ```ts twoslash import type { ParentCommand, NyxBot } from '@nyx-discord/djs-core'; declare const MyCommand: new () => ParentCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { ParentCommand, NyxBot } from '@nyx-discord/http'; declare const MyCommand: new () => ParentCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` ## Guild deployment [#guild-deployment] By default, all commands will be deployed in the global scope. If you want to deploy them in a specific guild, you can do so by implementing the `getGuilds()` method. ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractParentCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` If you're ever overriding from another base command, you can return `null` to make it global again, this is the default implementation. ## Children management [#children-management] Children aren't static: they can be added and removed in runtime. ```ts twoslash // ---cut-start--- import { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/djs'; declare const parent: ParentCommand; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- parent.addChildren(subCommand, subCommandGroup); parent.removeChildByInstance(subCommand); parent.removeChildByName('sub-command-group-name'); ``` ```ts twoslash // ---cut-start--- import { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/djs-core'; declare const parent: ParentCommand; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- parent.addChildren(subCommand, subCommandGroup); parent.removeChildByInstance(subCommand); parent.removeChildByName('sub-command-group-name'); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/http'; declare const parent: ParentCommand; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- parent.addChildren(subCommand, subCommandGroup); parent.removeChildByInstance(subCommand); parent.removeChildByName('sub-command-group-name'); ``` However, for the changes to be reflected in Discord, you must edit the command afterwards: ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const parent: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parent); ``` ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const parent: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parent); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/http'; declare const bot: NyxBot; declare const parent: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parent); ``` You can also query them by name, class or `Collection`: ```ts twoslash // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs'; declare const parent: ParentCommand; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/djs'; const byName = parent.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = parent.findChildByClass(MySubCommandClass); // ^? const allChildren = parent.getChildren(); // ^? ``` ```ts twoslash // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs-core'; declare const parent: ParentCommand; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/djs-core'; const byName = parent.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = parent.findChildByClass(MySubCommandClass); // ^? const allChildren = parent.getChildren(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { ParentCommand } from '@nyx-discord/http'; declare const parent: ParentCommand; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/http'; const byName = parent.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = parent.findChildByClass(MySubCommandClass); // ^? const allChildren = parent.getChildren(); // ^? ``` # SubCommand Groups (https://nyx-discord.github.io/nyx/guide/use/commands/types/parent/subcommand-group) It's recommended to read the [Commands Overview](../../index), [Parent Commands](./) and [SubCommands](./subcommand) pages first. Subcommand groups are non executable commands that have subcommand children. They are stored inside a [Parent Command](./). While they don't depend on a specific bot, they do depend on their parent (a parent command). ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractSubCommandGroup` class: ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup {} ``` ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup {} ``` ### Implementation [#implementation] Implement `data` that stores the command's data. The group's `children` collection is provided by the base class. The `data` field must not contain any option, only the base values (name, description, etc). If they are included, they will be ignored. ```ts twoslash import { SlashCommandSubcommandGroupBuilder } from 'discord.js'; import { AbstractSubCommandGroup } from '@nyx-discord/djs'; class MySubCommandGroup extends AbstractSubCommandGroup { protected readonly data = new SlashCommandSubcommandGroupBuilder() .setName('my-group') .setDescription('My group') .toJSON(); } ``` ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/djs-core'; import { ApplicationCommandOptionType } from '@discordjs/core'; class MySubCommandGroup extends AbstractSubCommandGroup { protected readonly data = { name: 'my-group', description: 'My group', type: ApplicationCommandOptionType.SubcommandGroup as const, }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/http'; import { ApplicationCommandOptionType } from '@discordjs/core'; class MySubCommandGroup extends AbstractSubCommandGroup { protected readonly data = { name: 'my-group', description: 'My group', type: ApplicationCommandOptionType.SubcommandGroup as const, }; } ``` ### Addition to its parent [#addition-to-its-parent] Instantiate and add it to a parent command. ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/djs'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; declare const parent: ParentCommand; declare const bot: NyxBot; // ---cut-end--- const subCommandGroup = new MySubCommandGroup(parent); parent.addChildren(subCommandGroup); ``` ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/djs-core'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; declare const parent: ParentCommand; declare const bot: NyxBot; // ---cut-end--- const subCommandGroup = new MySubCommandGroup(parent); parent.addChildren(subCommandGroup); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/http'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; declare const parent: ParentCommand; declare const bot: NyxBot; // ---cut-end--- const subCommandGroup = new MySubCommandGroup(parent); parent.addChildren(subCommandGroup); ``` Or do it in the parent's class: ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/djs'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommandGroup } from '@nyx-discord/djs'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommandGroup(this)); } } ``` ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/djs-core'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommandGroup } from '@nyx-discord/djs-core'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommandGroup(this)); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/http'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommandGroup } from '@nyx-discord/http'; declare const MySubCommandGroup: new (parent: ParentCommand) => SubCommandGroup; // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommandGroup(this)); } } ``` Then it'll show up when the top-level parent command is registered. ## Children management [#children-management] Children aren't static: they can be added and removed in runtime. ```ts twoslash // ---cut-start--- import { SubCommand, SubCommandGroup } from '@nyx-discord/djs'; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- subCommandGroup.addChildren(subCommand); subCommandGroup.removeChildByInstance(subCommand); subCommandGroup.removeChildByName('sub-command-name'); ``` ```ts twoslash // ---cut-start--- import { SubCommand, SubCommandGroup } from '@nyx-discord/djs-core'; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- subCommandGroup.addChildren(subCommand); subCommandGroup.removeChildByInstance(subCommand); subCommandGroup.removeChildByName('sub-command-name'); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { SubCommand, SubCommandGroup } from '@nyx-discord/http'; declare const subCommand: SubCommand; declare const subCommandGroup: SubCommandGroup; // ---cut-end--- subCommandGroup.addChildren(subCommand); subCommandGroup.removeChildByInstance(subCommand); subCommandGroup.removeChildByName('sub-command-name'); ``` However, for the changes to be reflected in Discord, you must edit the **parent command** afterwards: ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const parentCommand: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parentCommand); ``` ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const parentCommand: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parentCommand); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot, ParentCommand } from '@nyx-discord/http'; declare const bot: NyxBot; declare const parentCommand: ParentCommand; // ---cut-end--- await bot.getCommandManager().editCommands(parentCommand); ``` You can also query them by name, class or `Collection`: ```ts twoslash // ---cut-start--- import { SubCommandGroup } from '@nyx-discord/djs'; declare const group: SubCommandGroup; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/djs'; const byName = group.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = group.findChildByClass(MySubCommandClass); // ^? const allChildren = group.getChildren(); // ^? ``` ```ts twoslash // ---cut-start--- import { SubCommandGroup } from '@nyx-discord/djs-core'; declare const group: SubCommandGroup; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/djs-core'; const byName = group.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = group.findChildByClass(MySubCommandClass); // ^? const allChildren = group.getChildren(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { SubCommandGroup } from '@nyx-discord/http'; declare const group: SubCommandGroup; // ---cut-end--- import { AbstractSubCommand } from '@nyx-discord/http'; const byName = group.findChildByName('sub-command-name'); // ^? // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandClass extends AbstractSubCommand { /** */ } const byClass = group.findChildByClass(MySubCommandClass); // ^? const allChildren = group.getChildren(); // ^? ``` ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the group. While groups internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/djs'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup { protected override readonly meta = { someKey: 'someValue', }; } const group = new MySubCommandGroup(parent); const meta = group.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/djs-core'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs-core'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup { protected override readonly meta = { someKey: 'someValue', }; } const group = new MySubCommandGroup(parent); const meta = group.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommandGroup } from '@nyx-discord/http'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/http'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommandGroup extends AbstractSubCommandGroup { protected override readonly meta = { someKey: 'someValue', }; } const group = new MySubCommandGroup(parent); const meta = group.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. # SubCommands (https://nyx-discord.github.io/nyx/guide/use/commands/types/parent/subcommand) It's recommended to read the [Commands Overview](../../index) and [Parent Commands](./) pages first. Subcommands are executable commands stored inside a [Parent Command](./) or a [SubCommand Group](./subcommand-group). While they don't depend on a specific bot, they do depend on their parent (a parent command or a group). ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractSubCommand` class: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand {} ``` ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand {} ``` ### Implementation [#implementation] Implement `data` that stores the command's data, and `execute()` that executes the command. ```ts twoslash import { SlashCommandSubcommandBuilder, type ChatInputCommandInteraction } from 'discord.js'; import { AbstractSubCommand } from '@nyx-discord/djs'; class MySubCommand extends AbstractSubCommand { protected readonly data = new SlashCommandSubcommandBuilder() .setName('my-command') .setDescription('My command') .toJSON(); public async execute(interaction: ChatInputCommandInteraction) { await interaction.reply('Hello!'); } } ``` ```ts twoslash import { type APIChatInputApplicationCommandInteraction, ApplicationCommandOptionType, type ToEventProps } from '@discordjs/core'; import { AbstractSubCommand } from '@nyx-discord/djs-core'; class MySubCommand extends AbstractSubCommand { protected readonly data = { name: 'my-command', description: 'My command', type: ApplicationCommandOptionType.Subcommand, } as const; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type APIChatInputApplicationCommandInteraction, ApplicationCommandOptionType, type ToEventProps } from '@discordjs/core'; import { AbstractSubCommand } from '@nyx-discord/http'; class MySubCommand extends AbstractSubCommand { protected readonly data = { name: 'my-command', description: 'My command', type: ApplicationCommandOptionType.Subcommand, } as const; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` ### Addition to its parent [#addition-to-its-parent] Instantiate and add it to a parent command or a subcommand group. ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/djs'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; declare const parent: ParentCommand | SubCommandGroup; declare const bot: NyxBot; // ---cut-end--- const subCommand = new MySubCommand(parent); parent.addChildren(subCommand); ``` ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/djs-core'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; declare const parent: ParentCommand | SubCommandGroup; declare const bot: NyxBot; // ---cut-end--- const subCommand = new MySubCommand(parent); parent.addChildren(subCommand); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { ParentCommand, SubCommandGroup, SubCommand, NyxBot } from '@nyx-discord/http'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; declare const parent: ParentCommand | SubCommandGroup; declare const bot: NyxBot; // ---cut-end--- const subCommand = new MySubCommand(parent); parent.addChildren(subCommand); ``` Or do it in the parent or group's class: ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/djs'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/djs'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; // @ts-expect-error Incomplete example // ---cut-end--- // On a parent command: class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommand(this)); } } // Or on a subcommand group: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyGroup extends AbstractSubCommandGroup { constructor(parent: ParentCommand) { super(parent); this.addChildren(new MySubCommand(this)); } } ``` ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/djs-core'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/djs-core'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; // @ts-expect-error Incomplete example // ---cut-end--- // On a parent command: class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommand(this)); } } // Or on a subcommand group: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyGroup extends AbstractSubCommandGroup { constructor(parent: ParentCommand) { super(parent); this.addChildren(new MySubCommand(this)); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractParentCommand, AbstractSubCommandGroup } from '@nyx-discord/http'; import { SlashCommandBuilder } from 'discord.js'; // ---cut-start--- import type { ParentCommand, SubCommand, SubCommandGroup } from '@nyx-discord/http'; declare const MySubCommand: new (parent: ParentCommand | SubCommandGroup) => SubCommand; // @ts-expect-error Incomplete example // ---cut-end--- // On a parent command: class MyCommand extends AbstractParentCommand { constructor() { super(); this.addChildren(new MySubCommand(this)); } } // Or on a subcommand group: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyGroup extends AbstractSubCommandGroup { constructor(parent: ParentCommand) { super(parent); this.addChildren(new MySubCommand(this)); } } ``` Then it'll show up when the top-level parent command is registered. ## Execution Meta [#execution-meta] The second argument of the execute method is a `Metadata` object, which is a `Record` that stores metadata about the command call. Apart from the keys saved by the caller or the middleware, the dispatch meta contains: * The execution ID, via the `TypedFields.Id` field. * The execution start date, via the `TypedFields.CreationDate` field. * The bot whose `Client` sent the interaction, via the `TypedFields.Bot` field. To learn more about TypedFields, check the [Metadata](/use/other/meta) page. ## Autocompletion [#autocompletion] If your subcommand has autocompletable options, you can implement the `autocomplete()` method. ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs'; import type { AutocompleteInteraction } from 'discord.js'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { public async autocomplete(interaction: AutocompleteInteraction) { await interaction.respond([ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ]); } } ``` ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs-core'; import type { APIApplicationCommandAutocompleteInteraction, ToEventProps } from '@discordjs/core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { public async autocomplete(interaction: ToEventProps) { await interaction.api.interactions.createAutocompleteResponse( interaction.data.id, interaction.data.token, { choices: [ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ], }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/http'; import type { APIApplicationCommandAutocompleteInteraction, ToEventProps } from '@discordjs/core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { public async autocomplete(interaction: ToEventProps) { await interaction.api.interactions.createAutocompleteResponse( interaction.data.id, interaction.data.token, { choices: [ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ], }, ); } } ``` ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the subcommand. While subcommands internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { protected override readonly meta = { someKey: 'someValue', }; } const subcommand = new MySubCommand(parent); const meta = subcommand.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/djs-core'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/djs-core'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { protected override readonly meta = { someKey: 'someValue', }; } const subcommand = new MySubCommand(parent); const meta = subcommand.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSubCommand } from '@nyx-discord/http'; // ---cut-start--- import { ParentCommand } from '@nyx-discord/http'; declare const parent: ParentCommand; // @ts-expect-error Incomplete example // ---cut-end--- class MySubCommand extends AbstractSubCommand { protected override readonly meta = { someKey: 'someValue', }; } const subcommand = new MySubCommand(parent); const meta = subcommand.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. ## Advanced features [#advanced-features] Click on each card to learn more about that feature. } href="../../components"> Handle components interactions directly in the subcommand that sent them, without a separate `interactionCreate` listener. } href="../../filters"> Add pre-execution checks to your subcommand, like permissions or cooldowns. } href="../../middlewares"> Run code before every command's execution, like logging or pre-conditions. # Standalone Commands (https://nyx-discord.github.io/nyx/guide/use/commands/types/standalone) It's recommended to read the [Commands Overview](../index) page first. Standalone commands are fully executable, top level commands that don't store any children. In Discord, they are triggered on Slash Commands. ## Creation [#creation] ### Creation [#creation-1] Extend the `AbstractStandaloneCommand` class: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand {} ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand {} ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand {} ``` ### Implementation [#implementation] Implement `data` that stores the command's data, and `execute()` that executes the command. ```ts twoslash import { SlashCommandBuilder, type ChatInputCommandInteraction } from 'discord.js'; import { AbstractStandaloneCommand } from '@nyx-discord/djs'; class MyCommand extends AbstractStandaloneCommand { protected readonly data = new SlashCommandBuilder() .setName('my-command') .setDescription('My command') .toJSON(); public async execute(interaction: ChatInputCommandInteraction) { await interaction.reply('Hello!'); } } ``` ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; class MyCommand extends AbstractStandaloneCommand { protected readonly data = { name: 'my-command', description: 'My command', }; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/http'; class MyCommand extends AbstractStandaloneCommand { protected readonly data = { name: 'my-command', description: 'My command', }; public async execute(interaction: ToEventProps) { await interaction.api.interactions.reply( interaction.data.id, interaction.data.token, { content: 'Hello!' }, ); } } ``` ### Registration [#registration] Instantiate and register it to a bot's `CommandManager`. ```ts twoslash import type { StandaloneCommand, NyxBot } from '@nyx-discord/djs'; declare const MyCommand: new () => StandaloneCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` ```ts twoslash import type { StandaloneCommand, NyxBot } from '@nyx-discord/djs-core'; declare const MyCommand: new () => StandaloneCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { StandaloneCommand, NyxBot } from '@nyx-discord/http'; declare const MyCommand: new () => StandaloneCommand; declare const bot: NyxBot; // ---cut--- await bot.getCommandManager().addCommands(new MyCommand()); ``` ## Guild deployment [#guild-deployment] By default, all commands will be deployed in the global scope. If you want to deploy them in a specific guild, you can do so by implementing the `getGuilds()` method. ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public getGuilds() { return ['GUILD_ID', 'ANOTHER_GUILD_ID']; } } ``` If you're ever overriding from another base command, you can return `null` to make it global again, this is the default implementation. ## Execution Meta [#execution-meta] The second argument of the execute method is a `Metadata` object, which is a `Record` that stores metadata about the command call. Apart from the keys saved by the caller or the middleware, the dispatch meta contains: * The execution ID, via the `TypedFields.Id` field. * The execution start date, via the `TypedFields.CreationDate` field. * The bot whose `Client` sent the interaction, via the `TypedFields.Bot` field. To learn more about TypedFields, check the [Metadata](/use/other/meta) page. ## Autocompletion [#autocompletion] If your command has autocompletable options, you can implement the `autocomplete()` method. ```ts twoslash import type { AutocompleteInteraction } from 'discord.js'; import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async autocomplete(interaction: AutocompleteInteraction) { await interaction.respond([ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ]); } } ``` ```ts twoslash import type { APIApplicationCommandAutocompleteInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async autocomplete(interaction: ToEventProps) { await interaction.api.interactions.createAutocompleteResponse( interaction.data.id, interaction.data.token, { choices: [ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ] }, ); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { APIApplicationCommandAutocompleteInteraction, ToEventProps } from '@discordjs/core'; import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { public async autocomplete(interaction: ToEventProps) { await interaction.api.interactions.createAutocompleteResponse( interaction.data.id, interaction.data.token, { choices: [ { name: 'First option', value: 'first' }, { name: 'Second option', value: 'second' }, ] }, ); } } ``` ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the command. While commands internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractStandaloneCommand } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { protected override readonly meta = { someKey: 'someValue', }; } const command = new MyCommand(); const meta = command.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. ## Advanced features [#advanced-features] Click on each card to learn more about that feature. } href="../components"> Handle components interactions directly in the command that sent them, without a separate `interactionCreate` listener. } href="../filters"> Add pre-execution checks to your command, like permissions or cooldowns. } href="../middlewares"> Run code before every command's execution, like logging or pre-conditions. # Buses (https://nyx-discord.github.io/nyx/guide/use/events/buses) Event buses are objects that store and notify their `EventSubscribers` when an event is called either internally, typically via an EventEmitter, or externally, via `EventBus#emit()`. ## Main features [#main-features] An event bus can be un/subscribed to: ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber } from '@nyx-discord/djs'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const subscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(subscriber); await bus.unsubscribe(subscriber); ``` ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const subscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(subscriber); await bus.unsubscribe(subscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber } from '@nyx-discord/http'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const subscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(subscriber); await bus.unsubscribe(subscriber); ``` Can be used to emit an event type-safely: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs'; // ---cut-end--- type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; await bus.emit('someEvent', ['hello', 123]); // @errors: 2322 // Error! Argument missmatch await bus.emit('someEvent', [true, 123]); ``` ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs-core'; // ---cut-end--- type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; await bus.emit('someEvent', ['hello', 123]); // @errors: 2322 // Error! Argument missmatch await bus.emit('someEvent', [true, 123]); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/http'; // ---cut-end--- type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; await bus.emit('someEvent', ['hello', 123]); // @errors: 2322 // Error! Argument missmatch await bus.emit('someEvent', [true, 123]); ``` It can be iterated and its subscribers can be obtained: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- const subscribers = bus.getSubscribers(); // ^? for (const [id, subscriber] of bus) { // ^? } ``` ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- const subscribers = bus.getSubscribers(); // ^? for (const [id, subscriber] of bus) { // ^? } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/http'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- const subscribers = bus.getSubscribers(); // ^? for (const [id, subscriber] of bus) { // ^? } ``` And other features you might find useful. Check the for more details. ## Subscriber concurrency [#subscriber-concurrency] An event bus has complete freedom over how to execute its subscribers, however the framework has normalized two patterns for ease of use (though it's not hardcoded): ### Async buses [#async-buses] It calls its subscribers asynchronously, meaning that it doesn't wait for the current subscriber to finish before executing the next. | Advantages | Disadvantages | |---------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Can be faster, especially for events with many subscribers, since it executes them in bulk. | Multiple subscribers running may hog the event loop and decrease performance. | | Less prone to blocking or delaying the system, since it can move on to the next subscriber while the previous one is still executing. | May lead to calling subscribers in an order different than their priority. For example, subscribers with `PriorityEnum.Normal` may execute before subscribers with `PriorityEnum.High` have finished. | | | Since subscribers are executed in bulk, it can be harder to trace when an error occurs. | #### Concurrency Limit [#concurrency-limit] To tackle the mentioned disadvantages, it has a concurrency limit functionality. This allows you to set how many subscribers are being checked or executed at the same time. ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { AsyncEventDispatcher } from '@nyx-discord/djs'; const dispatcher = bus.getDispatcher() as AsyncEventDispatcher; dispatcher.setConcurrencyLimit(5); ``` ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { AsyncEventDispatcher } from '@nyx-discord/djs-core'; const dispatcher = bus.getDispatcher() as AsyncEventDispatcher; dispatcher.setConcurrencyLimit(5); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/http'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { AsyncEventDispatcher } from '@nyx-discord/http'; const dispatcher = bus.getDispatcher() as AsyncEventDispatcher; dispatcher.setConcurrencyLimit(5); ``` * Setting this limit to `1` effectively turns the dispatcher into a sync one. * The default concurrency limit is `3`. ### Sync buses [#sync-buses] It calls its subscribers synchronously, meaning that it waits for the current subscriber to finish before executing the next. | Advantages | Disadvantages | |------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | Ensures that subscribers are only executed in the order of their `Priority`. | May be slower for events with many subscribers, as it has to wait for each subscriber (and its middleware) to finish before moving on to the next one. | | Easier to debug and to trace when and on which state an error occurs. | If one subscriber takes a long time to execute, it can cause a delay for others. | #### Sync Timeout [#sync-timeout] To tackle the mentioned disadvantages, it has a sync timeout functionality. This allows you to set "timeframe" for any subscriber to finish, before the dispatcher stops waiting and calls the next subscriber. ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { SyncEventDispatcher } from '@nyx-discord/djs'; const dispatcher = bus.getDispatcher() as SyncEventDispatcher; dispatcher.setSyncTimeout(50_000); ``` ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { SyncEventDispatcher } from '@nyx-discord/djs-core'; const dispatcher = bus.getDispatcher() as SyncEventDispatcher; dispatcher.setSyncTimeout(50_000); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus } from '@nyx-discord/http'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; // ---cut-end--- import { SyncEventDispatcher } from '@nyx-discord/http'; const dispatcher = bus.getDispatcher() as SyncEventDispatcher; dispatcher.setSyncTimeout(50_000); ``` The default is of 10000 ms (10 seconds). ## Known buses [#known-buses] ### Client bus [#client-bus] The `Client` event bus is a built-in bus that wraps its events: ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` The bot also has a utility method to directly subscribe to it: ```ts twoslash // ---cut-start--- import { Bot, EventSubscriber } from '@nyx-discord/djs'; import { Events, ClientEvents } from 'discord.js'; declare const bot: Bot; declare const eventSubscriber: EventSubscriber; // ---cut-end--- await bot.subscribeToClient(eventSubscriber); ``` ```ts twoslash // ---cut-start--- import { Bot, EventSubscriber } from '@nyx-discord/djs-core'; import { GatewayDispatchEvents, type MappedEvents } from '@discordjs/core'; declare const bot: Bot; declare const eventSubscriber: EventSubscriber; // ---cut-end--- await bot.subscribeToClient(eventSubscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { Bot, EventSubscriber } from '@nyx-discord/http'; import { GatewayDispatchEvents, type MappedEvents } from '@discordjs/core'; declare const bot: Bot; declare const eventSubscriber: EventSubscriber; // ---cut-end--- await bot.subscribeToClient(eventSubscriber); ``` ### Manager buses [#manager-buses] Each manager holds a bus that wraps events related to the feature they manage: ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- const commandBus = bot.getCommandManager().getEventBus(); // ^? const scheduleBus = bot.getScheduleManager().getEventBus(); // ^? const pluginBus = bot.getPluginManager().getEventBus(); // ^? ``` ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- const commandBus = bot.getCommandManager().getEventBus(); // ^? const scheduleBus = bot.getScheduleManager().getEventBus(); // ^? const pluginBus = bot.getPluginManager().getEventBus(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- const commandBus = bot.getCommandManager().getEventBus(); // ^? const scheduleBus = bot.getScheduleManager().getEventBus(); // ^? const pluginBus = bot.getPluginManager().getEventBus(); // ^? ``` See the respective guide of each feature for more information about the events they emit. ## Custom buses [#custom-buses] You can create your own event bus for your building an event-based bot. ### Arguments type [#arguments-type] You'll first need an arguments type for your events, for example: ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; ``` This type's keys are the event names, and their values are the arguments of that event. ### Creation [#creation] #### Manual emits [#manual-emits] If you want a bus whose `emit()` method is manually called, either: - Use `BasicEventBus.createSync()` to create a sync bus. - Use `BasicEventBus.createAsync()` to create an async bus. ```ts twoslash import { BasicEventBus } from '@nyx-discord/djs'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); const asyncBus = BasicEventBus.createAsync(); ``` ```ts twoslash import { BasicEventBus } from '@nyx-discord/djs-core'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); const asyncBus = BasicEventBus.createAsync(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicEventBus } from '@nyx-discord/http'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); const asyncBus = BasicEventBus.createAsync(); ``` #### From an EventEmitter [#from-an-eventemitter] You can also create a bus that will wrap an existent `EventEmitter`, or a class that extends it: - Use `BasicEventBus.createSync()` to create a sync bus. - Use `BasicEventBus.createAsync()` to create an async bus. ```ts twoslash import { EventEmitter } from 'node:events'; import { BasicEventEmitterBus } from '@nyx-discord/djs'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const emitter = new EventEmitter(); const syncBus = BasicEventEmitterBus.createSyncWithEmitter(emitter); const asyncBus = BasicEventEmitterBus.createAsyncWithEmitter(emitter); ``` ```ts twoslash import { EventEmitter } from 'node:events'; import { BasicEventEmitterBus } from '@nyx-discord/djs-core'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const emitter = new EventEmitter(); const syncBus = BasicEventEmitterBus.createSyncWithEmitter(emitter); const asyncBus = BasicEventEmitterBus.createAsyncWithEmitter(emitter); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { EventEmitter } from 'node:events'; import { BasicEventEmitterBus } from '@nyx-discord/http'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const emitter = new EventEmitter(); const syncBus = BasicEventEmitterBus.createSyncWithEmitter(emitter); const asyncBus = BasicEventEmitterBus.createAsyncWithEmitter(emitter); ``` ## Bus events [#bus-events] Apart from the events specified in the type, the bus also emits extra events related to the bus itself: ```ts twoslash import { EventBusEventEnum } from '@nyx-discord/djs'; // @noErrors EventBusEventEnum. // ^| ``` ```ts twoslash import { EventBusEventEnum } from '@nyx-discord/djs-core'; // @noErrors EventBusEventEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { EventBusEventEnum } from '@nyx-discord/http'; // @noErrors EventBusEventEnum. // ^| ``` You can subscribe to these events in any bus, like any other event they'd manage. # Filters (https://nyx-discord.github.io/nyx/guide/use/events/filters) Filters restrict the execution of a given subscriber. For example: - A [bot filter](#bot-filter) that ignores events triggered by bots - A [guild filter](#guild-filter) that restricts the execution to a specific guild. They receive all the information about the subscriber, the event arguments that triggered it, and the execution metadata, and return a boolean indicating whether the subscriber should be executed or not. For more general information about filters, you must first read the general [Filters](/use/other/filters) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `AbstractEventSubscriberFilter` and implements the `check()` method. ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { AbstractEventSubscriberFilter } from '@nyx-discord/djs'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs'; class MyFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs['someEvent'] ): Promise { // Do some checks return true; // or false if the subscriber should not be executed } } ``` ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { AbstractEventSubscriberFilter } from '@nyx-discord/djs-core'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs-core'; class MyFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs['someEvent'] ): Promise { // Do some checks return true; // or false if the subscriber should not be executed } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { AbstractEventSubscriberFilter } from '@nyx-discord/http'; import type { EventSubscriber, Metadata } from '@nyx-discord/http'; class MyFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs['someEvent'] ): Promise { // Do some checks return true; // or false if the subscriber should not be executed } } ``` - Create a function that returns a boolean or a Promise that resolves to a boolean. ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/djs'; const myFilter: EventSubscriberFilterResolvable< MyEventsArgs, 'someEvent' > = async (subscriber, meta, ...args) => { // Do some checks return true; // or false if the subscriber should not be executed }; ``` ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/djs-core'; const myFilter: EventSubscriberFilterResolvable< MyEventsArgs, 'someEvent' > = async (subscriber, meta, ...args) => { // Do some checks return true; // or false if the subscriber should not be executed }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash type MyEventsArgs = { someEvent: [string, number]; }; // ---cut--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/http'; const myFilter: EventSubscriberFilterResolvable< MyEventsArgs, 'someEvent' > = async (subscriber, meta, ...args) => { // Do some checks return true; // or false if the subscriber should not be executed }; ``` You can also write a filter that will work regardless of the event being handled, by omitting the event name in the type arguments: ```ts twoslash import { AbstractEventSubscriberFilter, type EventSubscriberFilterResolvable, type Metadata, type EventSubscriber } from '@nyx-discord/djs'; // ---cut--- type MyEventsArgs = { someEvent: [string, number]; otherEvent: [boolean]; }; // With a class: class MyFilter extends AbstractEventSubscriberFilter { // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs[keyof MyEventsArgs] // ^? ) { /** ... */ } } // Or with a function: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- const myFilter: EventSubscriberFilterResolvable = async ( subscriber, ...args // ^? ) => { /** ... */ }; ``` ```ts twoslash import { AbstractEventSubscriberFilter, type EventSubscriberFilterResolvable, type Metadata, type EventSubscriber } from '@nyx-discord/djs-core'; // ---cut--- type MyEventsArgs = { someEvent: [string, number]; otherEvent: [boolean]; }; // With a class: class MyFilter extends AbstractEventSubscriberFilter { // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs[keyof MyEventsArgs] // ^? ) { /** ... */ } } // Or with a function: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- const myFilter: EventSubscriberFilterResolvable = async ( subscriber, ...args // ^? ) => { /** ... */ }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriberFilter, type EventSubscriberFilterResolvable, type Metadata, type EventSubscriber } from '@nyx-discord/http'; // ---cut--- type MyEventsArgs = { someEvent: [string, number]; otherEvent: [boolean]; }; // With a class: class MyFilter extends AbstractEventSubscriberFilter { // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- public async check( subscriber: EventSubscriber, meta: Metadata, ...args: MyEventsArgs[keyof MyEventsArgs] // ^? ) { /** ... */ } } // Or with a function: // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- const myFilter: EventSubscriberFilterResolvable = async ( subscriber, ...args // ^? ) => { /** ... */ }; ``` Notice how `args` accepts a union of the possible event arguments for any event in the `MyEventsArgs` type. ### Filter usage [#filter-usage] Override the `filter` property in your subscriber: - If you created a class, instantiate it: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; import { AbstractEventSubscriberFilter } from '@nyx-discord/djs'; // @ts-expect-error Incomplete example class MyFilter extends AbstractEventSubscriberFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = new MyFilter(); } ``` ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs-core'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; import { AbstractEventSubscriberFilter } from '@nyx-discord/djs-core'; // @ts-expect-error Incomplete example class MyFilter extends AbstractEventSubscriberFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = new MyFilter(); } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/http'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; import { AbstractEventSubscriberFilter } from '@nyx-discord/http'; // @ts-expect-error Incomplete example class MyFilter extends AbstractEventSubscriberFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = new MyFilter(); } ``` - If you created a function, assign it: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs'; // ---cut-start--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/djs'; type MyEventsArgs = { someEvent: [string, number]; }; declare const myFilter: EventSubscriberFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = myFilter; } ``` ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs-core'; // ---cut-start--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/djs-core'; type MyEventsArgs = { someEvent: [string, number]; }; declare const myFilter: EventSubscriberFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = myFilter; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/http'; // ---cut-start--- import { type EventSubscriberFilterResolvable } from '@nyx-discord/http'; type MyEventsArgs = { someEvent: [string, number]; }; declare const myFilter: EventSubscriberFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = myFilter; } ``` Or use a simple arrow function directly: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = () => { // Do some checks return true; }; } ``` ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs-core'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = () => { // Do some checks return true; }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/http'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MySubscriber extends AbstractEventSubscriber { protected override readonly filter = () => { // Do some checks return true; }; } ``` ## Examples [#examples] ### Bot Filter [#bot-filter] A simple filter that ignores events triggered by bots. This example assumes the event argument is a `Message`. ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/djs'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs'; import type { Message, ClientEvents } from 'discord.js'; class BotFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, message: Message ): Promise { return !message.author.bot; } } ``` ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/djs-core'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs-core'; import type { Message, ClientEvents } from 'discord.js'; class BotFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, message: Message ): Promise { return !message.author.bot; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/http'; import type { EventSubscriber, Metadata } from '@nyx-discord/http'; import type { Message, ClientEvents } from 'discord.js'; class BotFilter extends AbstractEventSubscriberFilter { public async check( subscriber: EventSubscriber, meta: Metadata, message: Message ): Promise { return !message.author.bot; } } ``` ### Guild Filter [#guild-filter] A filter that restricts the execution to a specific guild. This example assumes the event argument has a `guildId` property (like an Interaction or Message). ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/djs'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs'; import type { ClientEvents } from 'discord.js'; class GuildFilter extends AbstractEventSubscriberFilter { protected readonly guildId: string; constructor(guildId: string) { super(); this.guildId = guildId; } public async check( subscriber: EventSubscriber, meta: Metadata, object: { guildId: string | null } ): Promise { return object.guildId === this.guildId; } } ``` ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/djs-core'; import type { EventSubscriber, Metadata } from '@nyx-discord/djs-core'; import type { ClientEvents } from 'discord.js'; class GuildFilter extends AbstractEventSubscriberFilter { protected readonly guildId: string; constructor(guildId: string) { super(); this.guildId = guildId; } public async check( subscriber: EventSubscriber, meta: Metadata, object: { guildId: string | null } ): Promise { return object.guildId === this.guildId; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriberFilter } from '@nyx-discord/http'; import type { EventSubscriber, Metadata } from '@nyx-discord/http'; import type { ClientEvents } from 'discord.js'; class GuildFilter extends AbstractEventSubscriberFilter { protected readonly guildId: string; constructor(guildId: string) { super(); this.guildId = guildId; } public async check( subscriber: EventSubscriber, meta: Metadata, object: { guildId: string | null } ): Promise { return object.guildId === this.guildId; } } ``` # Events Overview (https://nyx-discord.github.io/nyx/guide/use/events) The event system in nyx is powered by [EventBuses](/use/events/buses). These are objects that store and notify their [EventSubscribers](/use/events/subscribers) when an event is called either internally or from another source. You can see them as a more batteries-included way of handling events than using the native Node.js `EventEmitter`. HTTP bots (`@nyx-discord/http`) have no gateway connection, so their client only emits `InteractionCreate`, plus [webhook events](/use/http/webhook-events) if you set them up. Subscribers to other client events never fire. ## Quick example [#quick-example] ```ts twoslash import { AbstractDJSClientSubscriber, type Metadata } from '@nyx-discord/djs'; import { Events, type Interaction } from 'discord.js'; class InteractionCreateLogger extends AbstractDJSClientSubscriber { protected readonly event = Events.InteractionCreate; public async handleEvent(meta: Metadata, interaction: Interaction) { console.log(`Interaction created: ${interaction.id}`); } } // ---cut-start--- import type { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); ``` ```ts twoslash import { AbstractCoreClientSubscriber, type Metadata } from '@nyx-discord/djs-core'; import { GatewayDispatchEvents, type ToEventProps, type APIInteraction } from '@discordjs/core'; class InteractionCreateLogger extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public async handleEvent(meta: Metadata, payload: ToEventProps) { console.log(`Interaction created: ${payload.data.id}`); } } // ---cut-start--- import type { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractCoreClientSubscriber, type Metadata } from '@nyx-discord/http'; import { GatewayDispatchEvents, type ToEventProps, type APIInteraction } from '@discordjs/core'; class InteractionCreateLogger extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public async handleEvent(meta: Metadata, payload: ToEventProps) { console.log(`Interaction created: ${payload.data.id}`); } } // ---cut-start--- import type { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); ``` That's it! Your bot will now log every interaction. ## Client Bus [#client-bus] The client is wrapped under an event bus, which you can get: ```ts twoslash // ---cut-start--- import { Bot } from '@nyx-discord/djs'; declare const bot: Bot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` ```ts twoslash // ---cut-start--- import { Bot } from '@nyx-discord/djs-core'; declare const bot: Bot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { Bot } from '@nyx-discord/http'; declare const bot: Bot; // ---cut-end--- const bus = bot.getClientEventBus(); // ^? ``` And you can directly subscribe to it: ```ts twoslash // ---cut-start--- import { Bot, AbstractDJSClientSubscriber } from '@nyx-discord/djs'; import { Events } from 'discord.js'; declare const bot: Bot; class InteractionCreateLogger extends AbstractDJSClientSubscriber { protected readonly event = Events.InteractionCreate; public async handleEvent() {} } // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); // Equivalent to: await bot.getClientEventBus().subscribe(new InteractionCreateLogger()); ``` ```ts twoslash // ---cut-start--- import { Bot, AbstractCoreClientSubscriber } from '@nyx-discord/djs-core'; import { GatewayDispatchEvents } from '@discordjs/core'; declare const bot: Bot; class InteractionCreateLogger extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public async handleEvent() {} } // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); // Equivalent to: await bot.getClientEventBus().subscribe(new InteractionCreateLogger()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { Bot, AbstractCoreClientSubscriber } from '@nyx-discord/http'; import { GatewayDispatchEvents } from '@discordjs/core'; declare const bot: Bot; class InteractionCreateLogger extends AbstractCoreClientSubscriber { protected readonly event = GatewayDispatchEvents.InteractionCreate; public async handleEvent() {} } // ---cut-end--- await bot.subscribeToClient(new InteractionCreateLogger()); // Equivalent to: await bot.getClientEventBus().subscribe(new InteractionCreateLogger()); ``` ## Custom buses [#custom-buses] You can create and directly use any bus you want: ```ts twoslash // ---cut-start--- import { BasicEventBus } from '@nyx-discord/djs'; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); // Waits for its subscribers to finish, with a timeout const asyncBus = BasicEventBus.createAsync(); // Executes a pool of subscribers at once ``` ```ts twoslash // ---cut-start--- import { BasicEventBus } from '@nyx-discord/djs-core'; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); // Waits for its subscribers to finish, with a timeout const asyncBus = BasicEventBus.createAsync(); // Executes a pool of subscribers at once ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { BasicEventBus } from '@nyx-discord/http'; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; // ---cut-end--- const syncBus = BasicEventBus.createSync(); // Waits for its subscribers to finish, with a timeout const asyncBus = BasicEventBus.createAsync(); // Executes a pool of subscribers at once ``` You can check more information about bus creation in the [Event Buses](/use/events/buses) page. ## What's next? [#whats-next] Click on each card to go to its page. } external={false}> Learn how to create your own event bus, or use built-in ones. } external={false}> Learn how to create event subscribers, and the features they provide. # Middlewares (https://nyx-discord.github.io/nyx/guide/use/events/middlewares) Middlewares are objects or callbacks that run before any subscriber is executed. They can do some pre-processing logic and store it in the metadata, or even prevent the subscriber from being executed. For general information about middlewares, you must first read the general [Middlewares](/use/other/middlewares) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `AbstractEventSubscriberMiddleware` and implements the `check()` method. ```ts twoslash import { AbstractEventSubscriberMiddleware } from '@nyx-discord/djs'; import type { AnyEventSubscriber, Metadata, MiddlewareResponse } from '@nyx-discord/djs'; class MyMiddleware extends AbstractEventSubscriberMiddleware { public async check( subscriber: AnyEventSubscriber, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` ```ts twoslash import { AbstractEventSubscriberMiddleware } from '@nyx-discord/djs-core'; import type { AnyEventSubscriber, Metadata, MiddlewareResponse } from '@nyx-discord/djs-core'; class MyMiddleware extends AbstractEventSubscriberMiddleware { public async check( subscriber: AnyEventSubscriber, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriberMiddleware } from '@nyx-discord/http'; import type { AnyEventSubscriber, Metadata, MiddlewareResponse } from '@nyx-discord/http'; class MyMiddleware extends AbstractEventSubscriberMiddleware { public async check( subscriber: AnyEventSubscriber, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` - Create a function that returns a `MiddlewareResponse`. ```ts twoslash import { type EventSubscriberMiddlewareResolvable } from '@nyx-discord/djs'; const myCallbackMiddleware: EventSubscriberMiddlewareResolvable = async (subscriber, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ```ts twoslash import { type EventSubscriberMiddlewareResolvable } from '@nyx-discord/djs-core'; const myCallbackMiddleware: EventSubscriberMiddlewareResolvable = async (subscriber, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type EventSubscriberMiddlewareResolvable } from '@nyx-discord/http'; const myCallbackMiddleware: EventSubscriberMiddlewareResolvable = async (subscriber, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ### Registration [#registration] Register it to the dispatcher's `MiddlewareList`: ```ts twoslash import type { EventBus, AbstractEventSubscriberMiddleware, EventSubscriberMiddlewareResolvable } from '@nyx-discord/djs'; declare const MyMiddleware: new () => AbstractEventSubscriberMiddleware; declare const myCallbackMiddleware: EventSubscriberMiddlewareResolvable; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; declare const bus: EventBus; // ---cut--- bus.getDispatcher().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` ```ts twoslash import type { EventBus, AbstractEventSubscriberMiddleware, EventSubscriberMiddlewareResolvable } from '@nyx-discord/djs-core'; declare const MyMiddleware: new () => AbstractEventSubscriberMiddleware; declare const myCallbackMiddleware: EventSubscriberMiddlewareResolvable; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; declare const bus: EventBus; // ---cut--- bus.getDispatcher().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { EventBus, AbstractEventSubscriberMiddleware, EventSubscriberMiddlewareResolvable } from '@nyx-discord/http'; declare const MyMiddleware: new () => AbstractEventSubscriberMiddleware; declare const myCallbackMiddleware: EventSubscriberMiddlewareResolvable; type MyEventsArgs = { someEvent: [string, number]; anotherEvent: [boolean]; }; declare const bus: EventBus; // ---cut--- bus.getDispatcher().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` # Subscribers (https://nyx-discord.github.io/nyx/guide/use/events/subscribers) Subscribers are objects that are notified by an `EventBus` when an event they are subscribed to is emitted. ## Creation [#creation] ### Creation [#creation-1] You'll first need a type for your events arguments, here we'll use `MyEventsArgs`. Either: - Extend `AbstractEventSubscriber` class and implement `handleEvent()` and `event`: ```ts twoslash import { AbstractEventSubscriber, type Metadata } from '@nyx-discord/djs'; type MyEventsArgs = { someEvent: [string, number]; }; class MySubscriber extends AbstractEventSubscriber { protected readonly event = 'someEvent'; public async handleEvent(meta: Metadata, ...args: MyEventsArgs['someEvent']) { // Handle event } } ``` ```ts twoslash import { AbstractEventSubscriber, type Metadata } from '@nyx-discord/djs-core'; type MyEventsArgs = { someEvent: [string, number]; }; class MySubscriber extends AbstractEventSubscriber { protected readonly event = 'someEvent'; public async handleEvent(meta: Metadata, ...args: MyEventsArgs['someEvent']) { // Handle event } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriber, type Metadata } from '@nyx-discord/http'; type MyEventsArgs = { someEvent: [string, number]; }; class MySubscriber extends AbstractEventSubscriber { protected readonly event = 'someEvent'; public async handleEvent(meta: Metadata, ...args: MyEventsArgs['someEvent']) { // Handle event } } ``` - Use `SubscriberCallbackWrapper` to create a subscriber from a generic callback: ```ts twoslash import { SubscriberCallbackWrapper, type Metadata } from '@nyx-discord/djs'; type MyEventsArgs = { someEvent: [string, number]; }; export const mySubscriber = new SubscriberCallbackWrapper( 'someEvent', (meta: Metadata, ...args: MyEventsArgs['someEvent']) => { // Handle event } ); ``` ```ts twoslash import { SubscriberCallbackWrapper, type Metadata } from '@nyx-discord/djs-core'; type MyEventsArgs = { someEvent: [string, number]; }; export const mySubscriber = new SubscriberCallbackWrapper( 'someEvent', (meta: Metadata, ...args: MyEventsArgs['someEvent']) => { // Handle event } ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { SubscriberCallbackWrapper, type Metadata } from '@nyx-discord/http'; type MyEventsArgs = { someEvent: [string, number]; }; export const mySubscriber = new SubscriberCallbackWrapper( 'someEvent', (meta: Metadata, ...args: MyEventsArgs['someEvent']) => { // Handle event } ); ``` ### Subscription [#subscription] Register the subscriber to an `EventBus`: ```ts twoslash // ---cut-start--- import type { NyxBot, EventSubscriber, EventBus } from '@nyx-discord/djs'; type MyEventsArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const mySubscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(mySubscriber); ``` ```ts twoslash // ---cut-start--- import type { NyxBot, EventSubscriber, EventBus } from '@nyx-discord/djs-core'; type MyEventsArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const mySubscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(mySubscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import type { NyxBot, EventSubscriber, EventBus } from '@nyx-discord/http'; type MyEventsArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const mySubscriber: EventSubscriber; // ---cut-end--- await bus.subscribe(mySubscriber); ``` If you want to create a listener for the `Client` bus, you can extend the `AbstractDJSClientSubscriber` (or `AbstractCoreClientSubscriber` for `@discordjs/core`) utility class instead, and you won't have to type out the client's event map generic. Check the [Events Overview](./index) page for an example. ## Priorities [#priorities] The priority determines the order in which they are executed: - Higher priorities are executed first. - Monitors are specifically meant for monitoring (e.g. metrics), though that's not enforced. - `HighMonitor` is the first priority to be executed. - `LowMonitor` is the last priority to be executed. ```ts twoslash import { PriorityEnum } from '@nyx-discord/djs'; // @noErrors PriorityEnum. // ^| ``` ```ts twoslash import { PriorityEnum } from '@nyx-discord/djs-core'; // @noErrors PriorityEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { PriorityEnum } from '@nyx-discord/http'; // @noErrors PriorityEnum. // ^| ``` The default priority is `Normal`, it's changed by overriding the `priority` property in classes. It can't be changed for callback-based subscribers. ## Subscription notification [#subscription-notification] The subscriber will be notified when its un/subscribed to an `EventBus`, and when said bus is unregistered: ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber, AbstractEventSubscriber, NyxBot } from '@nyx-discord/djs'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const bot: NyxBot; declare const subscriber: EventSubscriber; // @ts-expect-error Incomplete example // ---cut-end--- class Subscriber extends AbstractEventSubscriber { public override onSubscribe(bus: EventBus) { console.log('I was subscribed!'); } public override onUnsubscribe(bus: EventBus) { console.log('I was unsubscribed!'); } public override onBusUnregister(bus: EventBus) { console.log('My bus was unregistered!'); } } await bus.subscribe(subscriber); // console: I was subscribed! await bus.unsubscribe(subscriber); // console: I was unsubscribed! ``` ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber, AbstractEventSubscriber, NyxBot } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const bot: NyxBot; declare const subscriber: EventSubscriber; // @ts-expect-error Incomplete example // ---cut-end--- class Subscriber extends AbstractEventSubscriber { public override onSubscribe(bus: EventBus) { console.log('I was subscribed!'); } public override onUnsubscribe(bus: EventBus) { console.log('I was unsubscribed!'); } public override onBusUnregister(bus: EventBus) { console.log('My bus was unregistered!'); } } await bus.subscribe(subscriber); // console: I was subscribed! await bus.unsubscribe(subscriber); // console: I was unsubscribed! ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventBus, EventSubscriber, AbstractEventSubscriber, NyxBot } from '@nyx-discord/http'; type EventArgs = { someEvent: [string, number]; }; declare const bus: EventBus; declare const bot: NyxBot; declare const subscriber: EventSubscriber; // @ts-expect-error Incomplete example // ---cut-end--- class Subscriber extends AbstractEventSubscriber { public override onSubscribe(bus: EventBus) { console.log('I was subscribed!'); } public override onUnsubscribe(bus: EventBus) { console.log('I was unsubscribed!'); } public override onBusUnregister(bus: EventBus) { console.log('My bus was unregistered!'); } } await bus.subscribe(subscriber); // console: I was subscribed! await bus.unsubscribe(subscriber); // console: I was unsubscribed! ``` ## Event Meta [#event-meta] The first argument of the `handleEvent()` is an `Metadata` object, which is a `Record` that stores metadata about the event call. Apart from the keys saved by the caller or the middleware, the dispatch meta contains: * The execution ID, via the `TypedFields.Id` field. * The execution start date, via the `TypedFields.CreationDate` field. * The bot that called the event, via the `TypedFields.Bot` field. * The bus where the event was emitted, via the `TypedFields.EventBus` field. * Whether the event has been marked as handled by another subscriber, via the `TypedFields.EventHandled` field, which will be explained later. To learn more about TypedFields, check the [Metadata](/use/other/meta) page. ### Event handling [#event-handling] By default, when a subscriber marks an event as "handled" with `this.setHandled(meta)`, it won't be received by the rest of the subscribers. This is useful for events that only need to be "executed once", for example, replying to an `Interaction`. However, you can make your subscriber to be always called, even when the event is handled, overriding the `ignoreHandled` property: ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, Metadata } from '@nyx-discord/djs'; import { EventBus } from '@nyx-discord/djs'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // ---cut-end--- // A subscriber with priority Highest marks the event as handled // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Highest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Highest; public handleEvent(meta: Metadata) { console.log('Highest'); this.setHandled(meta); } } // A subscriber with priority Lowest doesn't receive the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Lowest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; public handleEvent() { console.log('Lowest'); } } // A subscriber with priority Lowest but `ignoreHandled = false` receives the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class LowestNotIgnored extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; protected readonly ignoreHandled = false; public handleEvent() { console.log('Lowest with ignoreHandled = false'); } } await bus.subscribe(new Lowest(), new Highest(), new LowestNotIgnored()); await bus.emit('someEvent', []); ``` ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, Metadata } from '@nyx-discord/djs-core'; import { EventBus } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // ---cut-end--- // A subscriber with priority Highest marks the event as handled // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Highest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Highest; public handleEvent(meta: Metadata) { console.log('Highest'); this.setHandled(meta); } } // A subscriber with priority Lowest doesn't receive the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Lowest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; public handleEvent() { console.log('Lowest'); } } // A subscriber with priority Lowest but `ignoreHandled = false` receives the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class LowestNotIgnored extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; protected readonly ignoreHandled = false; public handleEvent() { console.log('Lowest with ignoreHandled = false'); } } await bus.subscribe(new Lowest(), new Highest(), new LowestNotIgnored()); await bus.emit('someEvent', []); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, Metadata } from '@nyx-discord/http'; import { EventBus } from '@nyx-discord/http'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // ---cut-end--- // A subscriber with priority Highest marks the event as handled // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Highest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Highest; public handleEvent(meta: Metadata) { console.log('Highest'); this.setHandled(meta); } } // A subscriber with priority Lowest doesn't receive the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class Lowest extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; public handleEvent() { console.log('Lowest'); } } // A subscriber with priority Lowest but `ignoreHandled = false` receives the event // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class LowestNotIgnored extends AbstractEventSubscriber { protected readonly priority = PriorityEnum.Lowest; protected readonly ignoreHandled = false; public handleEvent() { console.log('Lowest with ignoreHandled = false'); } } await bus.subscribe(new Lowest(), new Highest(), new LowestNotIgnored()); await bus.emit('someEvent', []); ``` Would log: ``` Highest Lowest with ignoreHandled = false ``` Notice how the `Lowest` subscriber is not called, because it has a lower priority than the `Highest` one, which marked the event as handled, and it has `ignoreHandled = true` by default. ## Lifetime [#lifetime] Subscribers can specify its "lifetime", which determines how much it lasts registered on the bus. This is similar to using Node's `EventEmitter#on()` vs `EventEmitter#once()`. This can be done overriding the `lifetime` property. Currently available lifetimes are: * `On` to "permanently" subscribe to the bus until manually unsubscribed (default). * `Once` to subscribe for a single call (The `EventSubscriberMiddleware` must allow the execution). ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, EventSubscriberLifetimeEnum, Metadata } from '@nyx-discord/djs'; import { EventBus } from '@nyx-discord/djs'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // @ts-expect-error Incomplete example // ---cut-end--- class Once extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.Once; public handleEvent() { console.log('Once'); } } // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class On extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.On; public handleEvent() { console.log('On'); } } await bus.subscribe(new Once(), new On()); await bus.emit('someEvent', []); await bus.emit('someEvent', []); ``` ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, EventSubscriberLifetimeEnum, Metadata } from '@nyx-discord/djs-core'; import { EventBus } from '@nyx-discord/djs-core'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // @ts-expect-error Incomplete example // ---cut-end--- class Once extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.Once; public handleEvent() { console.log('Once'); } } // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class On extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.On; public handleEvent() { console.log('On'); } } await bus.subscribe(new Once(), new On()); await bus.emit('someEvent', []); await bus.emit('someEvent', []); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { AbstractEventSubscriber, PriorityEnum, EventSubscriberLifetimeEnum, Metadata } from '@nyx-discord/http'; import { EventBus } from '@nyx-discord/http'; type EventArgs = { someEvent: []; }; declare const bus: EventBus; // @ts-expect-error Incomplete example // ---cut-end--- class Once extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.Once; public handleEvent() { console.log('Once'); } } // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class On extends AbstractEventSubscriber { protected readonly lifetime = EventSubscriberLifetimeEnum.On; public handleEvent() { console.log('On'); } } await bus.subscribe(new Once(), new On()); await bus.emit('someEvent', []); await bus.emit('someEvent', []); ``` Would log: ``` Once On On ``` Notice how the `Once` subscriber is called only once, while the `On` subscriber is called twice (as many times as the event is emitted). ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the subscriber. While subscribers internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MyEventSubscriber extends AbstractEventSubscriber { protected override readonly meta = { someKey: 'someValue', }; } const myEventSubscriber = new MyEventSubscriber(); const meta = myEventSubscriber.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/djs-core'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MyEventSubscriber extends AbstractEventSubscriber { protected override readonly meta = { someKey: 'someValue', }; } const myEventSubscriber = new MyEventSubscriber(); const meta = myEventSubscriber.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractEventSubscriber } from '@nyx-discord/http'; // ---cut-start--- type MyEventsArgs = { someEvent: [string, number]; }; // @ts-expect-error Incomplete example // ---cut-end--- class MyEventSubscriber extends AbstractEventSubscriber { protected override readonly meta = { someKey: 'someValue', }; } const myEventSubscriber = new MyEventSubscriber(); const meta = myEventSubscriber.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. # Start (https://nyx-discord.github.io/nyx/guide/use/first-start) ## First Start [#first-start] A minimum version of Node.js 18 is required to run, though we recommend latest LTS. Although they should work, nyx is not tested on other runtimes, such as Deno or Bun. We also recommend using a formatter like [Prettier](https://www.prettier.io/) and a linter like [ESLint](https://eslint.org/) or [TypeScript ESLint](https://typescript-eslint.io/). ### Installing [#installing] ```npm npm i @nyx-discord/djs discord.js ``` ```npm npm i @nyx-discord/djs-core @discordjs/core @discordjs/rest @discordjs/ws ``` ```npm npm i @nyx-discord/http @discordjs/core ``` ### Creating a Client [#creating-a-client] You'll need a client, which will depend on the adapter you're using. It can be any client, as long as it's not logged in or destroyed. ```ts twoslash import { Client, GatewayIntentBits } from 'discord.js'; const client = new Client({ intents: [GatewayIntentBits.Guilds] }); ``` ```ts twoslash import { Client, GatewayIntentBits } from '@discordjs/core'; import { REST } from '@discordjs/rest'; import { WebSocketManager } from '@discordjs/ws'; const rest = new REST({ version: '10' }).setToken('TOKEN'); const gateway = new WebSocketManager({ token: 'TOKEN', intents: GatewayIntentBits.Guilds, rest, }); const client = new Client({ rest, gateway }); ``` No client needed: `HttpBot` creates it for you in the next step, from your application's ID and public key. ### Creating a Bot [#creating-a-bot] Next up, we'll create a new instance of `Bot`. This is the main entry point of the framework, and it will handle the lifecycle of your bot, including loading commands, managing events, and more. There's no global state, so you can create multiple bots and they'll all work independently with no issues! Create one with `Bot.create()`, which takes a function that gets passed the currently constructing bot instance, and should return the options that you want for the bot. ```ts twoslash import { Bot, type NyxBot } from '@nyx-discord/djs'; // ---cut-start--- import { Client, GatewayIntentBits } from 'discord.js'; declare const client: Client; // ---cut-end--- const myBot = Bot.create((bot: NyxBot) => ({ token: 'TOKEN', client, logger: console, // Can be your own logger, see the NyxLogger docs deployCommands: true, // Whether to deploy commands to Discord on start })); ``` ```ts twoslash import { Bot, CoreNyxClient, type NyxBot } from '@nyx-discord/djs-core'; // ---cut-start--- import { Client, GatewayIntentBits } from '@discordjs/core'; import { REST } from '@discordjs/rest'; import { WebSocketManager } from '@discordjs/ws'; const rest = new REST({ version: '10' }).setToken('TOKEN'); const gateway = new WebSocketManager({ token: 'TOKEN', intents: GatewayIntentBits.Guilds, rest }); declare const client: Client; // ---cut-end--- const myBot = Bot.create((bot: NyxBot) => ({ token: 'TOKEN', client: new CoreNyxClient(client, gateway, 'APPLICATION_ID'), logger: console, // Can be your own logger, see the NyxLogger docs deployCommands: true, // Whether to deploy commands to Discord on start })); ``` ```ts twoslash import { HttpBot, type NyxBot } from '@nyx-discord/http'; const myBot = HttpBot.create((bot: NyxBot) => ({ applicationId: 'APPLICATION_ID', publicKey: 'PUBLIC_KEY', // From the Developer Portal, used to verify requests token: 'TOKEN', logger: console, // Can be your own logger, see the NyxLogger docs deployCommands: true, // Whether to deploy commands to Discord on start })); ``` About new Bot()

}> You can also instantiate with the [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) operator, but in order to allow dependency injection, this constructor requires every manager on its options, including default ones. You would need to instantiate and pass every manager to it: ```ts twoslash import { Client, GatewayIntentBits } from 'discord.js'; declare const client: Client; // ---cut--- import { Bot, DefaultScheduleManager, DjsNyxClient, DefaultPluginManager } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Other managers missing for brevity // ---cut-end--- const myBot = new Bot((bot) => ({ token: 'TOKEN', client: new DjsNyxClient(client), logger: console, deployCommands: true, scheduleManager: DefaultScheduleManager.create({ bot }), pluginManager: DefaultPluginManager.create({ bot }), // and so on })); ``` You'll find this pattern in other `@base` objects, where you can use either `new Object(depA, ...)` specifying every dependency, or `Object.create()` which uses default dependencies, and you can optionally inject your own to that method (while still keeping other defaults).
### Starting the Bot [#starting-the-bot] Finally, to start it, simply call `.start()`. This will log in the client, set up event listeners, and get everything ready: ```ts twoslash // ---cut-start--- import { Bot } from '@nyx-discord/djs'; declare const myBot: Bot; // ---cut-end--- await myBot.start(); ``` ```ts twoslash // ---cut-start--- import { Bot } from '@nyx-discord/djs-core'; declare const myBot: Bot; // ---cut-end--- await myBot.start(); ``` This example uses `node:http`, but you can use any backend you want, including serverless! Check out the [HTTP Bots](/use/http) section for more details. ```ts twoslash // ---cut-start--- import { HttpBot } from '@nyx-discord/http'; declare const myBot: HttpBot; // ---cut-end--- import { createServer } from 'node:http'; import { toNodeListener } from '@nyx-discord/http'; await myBot.start(); // then pass Discord's requests to the client, see the HTTP Mounting page for other servers createServer(toNodeListener(myBot.getClient())).listen(3000); ``` If the start errors, it'll reject the promise, and the bot will enter in a `BotStatusEnum.Killed` state, meaning it won't be able to be used anymore. You can create a new bot instance and start it again, but you cannot recover the previous one. To get a bot's status at any time, you can use `Bot#getStatus()`.
## Next Steps [#next-steps] Click on each card to learn more about that feature. } external={false}> Learn how to create and use commands in your bot. } external={false}> Learn how to subscribe to Client or custom events. } external={false}> Learn how to schedule tasks to be executed at specific times. } external={false}> Learn how to create and use plugins to extend your bot's functionality. # Configuration (https://nyx-discord.github.io/nyx/guide/use/http/configuration) Every part of the client can be replaced through `clientInjections` (or `injections`, when calling `HttpNyxClient.create()` yourself): | Injection | Default | Description | |----------------------|------------------------------------------------------------|-----------------------------------------------------------------------------------| | `verifier` | `DefaultSignatureVerifier` | Verifies Discord's Ed25519 signatures. | | `rest` | A `REST` with the bot's token | The REST client used by `api`. | | `api` | An `API` over `rest` | The API passed to commands and subscribers. | | `emitter` | A `BasicAwaitableEventEmitter` | The emitter interactions and webhook events are emitted on. Its `emit()` resolves when the listeners finish, which is what `handled` waits for. | | `acknowledgeTimeout` | `3_000` | How long to wait for an interaction to be acknowledged, in milliseconds. | | `maxTimestampAge` | `300_000` | How old (or how far in the future) a request can be before it's rejected, in ms. | ```ts twoslash declare const env: Record; // ---cut--- import { HttpBot } from '@nyx-discord/http'; const bot = HttpBot.create(() => ({ applicationId: env.APP_ID, publicKey: env.DISCORD_PUBLIC_KEY, token: env.TOKEN, logger: console, deployCommands: true, clientInjections: { acknowledgeTimeout: 2_500, maxTimestampAge: 60_000, }, })); ``` ## Signature verification [#signature-verification] The default verifier checks signatures with the [Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API) (`crypto.subtle`), so it needs no dependencies and works on Node.js, Bun, Deno and Cloudflare Workers. On runtimes without a global `crypto.subtle`, like older Node.js versions, pass one yourself: ```ts twoslash declare const env: Record; // ---cut--- import { webcrypto } from 'node:crypto'; import { DefaultSignatureVerifier, HttpBot } from '@nyx-discord/http'; const bot = HttpBot.create(() => ({ applicationId: env.APP_ID, publicKey: env.DISCORD_PUBLIC_KEY, token: env.TOKEN, logger: console, deployCommands: true, clientInjections: { verifier: DefaultSignatureVerifier.create({ publicKey: env.DISCORD_PUBLIC_KEY, subtle: webcrypto.subtle as SubtleCrypto, }), }, })); ``` Or implement to use any other library. For example, with [tweetnacl](https://www.npmjs.com/package/tweetnacl): ```ts twoslash declare const env: Record; // ---cut--- import nacl from 'tweetnacl'; import { HttpBot, type SignatureVerifier } from '@nyx-discord/http'; class NaclVerifier implements SignatureVerifier { protected readonly publicKey: Uint8Array; protected readonly encoder = new TextEncoder(); constructor(publicKey: string) { this.publicKey = Buffer.from(publicKey, 'hex'); } public async verify(body: string | Uint8Array, signature: string, timestamp: string) { // Discord signs the timestamp followed by the raw body const bodyBytes = typeof body === 'string' ? this.encoder.encode(body) : body; const message = Buffer.concat([this.encoder.encode(timestamp), bodyBytes]); try { return nacl.sign.detached.verify(message, Buffer.from(signature, 'hex'), this.publicKey); } catch { // tweetnacl throws on malformed signatures, which are just invalid requests return false; } } } const bot = HttpBot.create(() => ({ applicationId: env.APP_ID, publicKey: env.DISCORD_PUBLIC_KEY, token: env.TOKEN, logger: console, deployCommands: true, clientInjections: { verifier: new NaclVerifier(env.DISCORD_PUBLIC_KEY), }, })); ``` # HTTP Overview (https://nyx-discord.github.io/nyx/guide/use/http) The [`@nyx-discord/http`](https://www.npmjs.com/package/@nyx-discord/http) package lets an `@discordjs/core` bot receive [interactions](https://discord.com/developers/docs/interactions/overview) and [webhook events](https://discord.com/developers/docs/events/webhook-events) over HTTP, instead of through a gateway connection. Discord sends each interaction as a `POST` request to your app's Interactions Endpoint URL, so a bot that only handles commands and components doesn't need a long-lived connection at all. It can run on a regular server, or on serverless platforms like Cloudflare Workers or Vercel. The framework doesn't ship a server and never opens a port. Our client takes a request and returns a response, and you pass requests to it from the server you already use: `node:http`, Express, Fastify, Hono, Next.js, Bun, Deno, Workers... ## Installation [#installation] ### Installing [#installing] ```npm npm i @nyx-discord/http @discordjs/core ``` The package re-exports `@nyx-discord/djs-core`, so commands, events, schedules and everything else are imported from `@nyx-discord/http`. Everything in this guide that applies to `@discordjs/core` applies here too. ### Creating the bot [#creating-the-bot] `HttpBot.create()` works like `@nyx-discord/djs-core`'s `Bot.create()`, but takes your application's ID and public key (both on the [Developer Portal](https://discord.com/developers/applications)) instead of a client, and creates the client for you. `Bot` from `@nyx-discord/http` is `HttpBot`, so examples using `Bot.create()` or the `Bot` type work as-is: ```ts twoslash declare const env: Record; // ---cut--- import { HttpBot } from '@nyx-discord/http'; const bot = HttpBot.create(() => ({ applicationId: env.APP_ID, publicKey: env.DISCORD_PUBLIC_KEY, token: env.TOKEN, logger: console, deployCommands: true, })); await bot.start(); const client = bot.getClient(); // ^? ``` Requests are answered with `503` until `bot.start()` finishes, so nothing reaches your commands before they're registered. ### Mounting the client [#mounting-the-client] Pass incoming requests to the client from your server. See [Mounting](/use/http/mounting) for each backend: ```ts twoslash import { HttpBot } from '@nyx-discord/http'; declare const bot: HttpBot; // ---cut--- import { createServer } from 'node:http'; import { toNodeListener } from '@nyx-discord/http'; createServer(toNodeListener(bot.getClient())).listen(3000); ``` ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to the public URL of that route. Discord sends a `PING` to check it, which the client answers by itself. ## What's different from the gateway [#whats-different-from-the-gateway] - Only interactions (`InteractionCreate`) and [webhook events](/use/http/webhook-events) are emitted. Subscribers to any other gateway event (messages, members, guilds...) never fire. - Commands work unchanged: they reply through `api.interactions.reply()` and friends, as they do on the gateway. See [Handling requests](/use/http/requests). - Schedules run while the process is alive. On serverless platforms, triggering them (e.g. with Workers cron triggers) is up to you, see [Serverless](/use/http/serverless). - Only the `@discordjs/core` adapter is supported, since discord.js structures need a gateway-backed `Client`. ## Getting the bot [#getting-the-bot] Inside commands, subscribers and schedules, `TypedFields.getBot()` gets the bot from the metadata, typed so its client is the `HttpNyxClient` (a shorthand for `TypedFields.HttpBot.get(meta, true)`): ```ts twoslash import { AbstractSchedule, TypedFields, type Metadata } from '@nyx-discord/http'; class CleanupSchedule extends AbstractSchedule { protected readonly interval = '0 * * * *'; public async tick(meta: Metadata) { const bot = TypedFields.getBot(meta); const client = bot.getClient(); // ^? // Shorthand for bot.getClient().getApi(), the REST API const api = TypedFields.getApi(meta); } } ``` `@nyx-discord/http` exports its own `TypedFields`, without `@nyx-discord/djs-core`'s `GatewayCoreBot` and `getClient()`, since HTTP bots have no gateway client. # Mounting (https://nyx-discord.github.io/nyx/guide/use/http/mounting) Discord sends requests to two URLs, which you set on the Developer Portal: - The **Interactions Endpoint URL**, handled by the client itself. - The **Webhook Events URL**, handled by `client.getWebhookEventHandler()`. It's optional, see [Webhook events](/use/http/webhook-events). Both are handlers with one method, `handle()`, which takes a request and returns the response to send. The package also includes two adapters for the most common signatures: | Adapter | Signature | Use it with | |------------------|----------------------------------------------------------------------------------|---------------------------------------------------| | `toNodeListener` | `(req: IncomingMessage, res: ServerResponse) => Promise` | `node:http`, Express | | `toFetchHandler` | `(request: Request, context?: { waitUntil?(promise): void }) => Promise` | Hono, Cloudflare Workers, Bun, Deno, Next.js | Both answer non-`POST` requests with `405`. Discord's signature is checked against the **raw** request body. Make sure nothing parses the body before the client sees it, like `express.json()` or Fastify's default JSON parser. ## node:http [#nodehttp] ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; // ---cut--- import { createServer } from 'node:http'; import { toNodeListener } from '@nyx-discord/http'; const interactions = toNodeListener(client); const webhookEvents = toNodeListener(client.getWebhookEventHandler()); createServer((req, res) => { const listener = req.url === '/interactions' ? interactions : req.url === '/webhook-events' ? webhookEvents : null; if (!listener) return void res.writeHead(404).end(); listener(req, res).catch(console.error); }).listen(3000); ``` ## Express [#express] ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; import type { RequestListener } from 'node:http'; declare const client: HttpNyxClient; declare const app: { post(path: string, handler: RequestListener): void }; // ---cut--- import { toNodeListener } from '@nyx-discord/http'; // no express.json() on these routes app.post('/interactions', toNodeListener(client)); app.post('/webhook-events', toNodeListener(client.getWebhookEventHandler())); ``` ## Fastify [#fastify] Fastify parses JSON by default, so register a parser that keeps the body as a `Buffer`, and call `handle()` directly. Passing Fastify's request as `raw` makes it available to your handlers through [`TypedFields.HttpRequest`](/use/http/requests#reading-the-request): ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; type Request = { body: unknown; headers: Record }; type Reply = { code(status: number): Reply; headers(headers: Record): Reply; send(body: string): Reply }; declare const app: { addContentTypeParser(type: string, options: { parseAs: 'buffer' }, parser: (req: Request, body: Buffer, done: (error: null, body: Buffer) => void) => void): void; post(path: string, handler: (req: Request, reply: Reply) => Promise): void; }; // ---cut--- app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_req, body, done) => done(null, body)); const endpoints = [ ['/interactions', client], ['/webhook-events', client.getWebhookEventHandler()], ] as const; for (const [path, handler] of endpoints) { app.post(path, async (req, reply) => { const result = await handler.handle({ body: req.body as Buffer, signature: req.headers['x-signature-ed25519'], timestamp: req.headers['x-signature-timestamp'], raw: req, }); return reply.code(result.status).headers(result.headers).send(result.body); }); } ``` ## Hono [#hono] ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; declare const app: { post(path: string, handler: (c: { req: { raw: Request } }) => Promise): void }; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; const interactions = toFetchHandler(client); const webhookEvents = toFetchHandler(client.getWebhookEventHandler()); app.post('/interactions', (c) => interactions(c.req.raw)); app.post('/webhook-events', (c) => webhookEvents(c.req.raw)); ``` When Hono runs on Cloudflare Workers, pass `c.executionCtx` as the second argument too, so the worker stays alive until your handlers finish. ## Cloudflare Workers [#cloudflare-workers] Pass the worker's `ctx` as the handler's second argument, so the worker stays alive until your handlers finish (see [Serverless platforms](/use/http/requests#serverless-platforms)): ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; type ExecutionContext = { waitUntil(promise: Promise): void }; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; const interactions = toFetchHandler(client); const webhookEvents = toFetchHandler(client.getWebhookEventHandler()); export default { fetch(request: Request, env: unknown, ctx: ExecutionContext) { const { pathname } = new URL(request.url); const handler = pathname === '/webhook-events' ? webhookEvents : interactions; return handler(request, ctx); }, }; ``` On Workers, your secrets only arrive with the first request, so the client can't be created when the module loads. See [Cloudflare Workers](/use/http/serverless/cloudflare-workers) for a complete setup. ## Bun and Deno [#bun-and-deno] Both accept a default export with a `fetch` handler: ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; const interactions = toFetchHandler(client); const webhookEvents = toFetchHandler(client.getWebhookEventHandler()); export default { fetch(request: Request) { const { pathname } = new URL(request.url); return pathname === '/webhook-events' ? webhookEvents(request) : interactions(request); }, }; ``` ## Next.js [#nextjs] Use a route handler for each URL, passing [`after()`](https://nextjs.org/docs/app/api-reference/functions/after) as `waitUntil`, so the function stays alive until your handlers finish: ```ts twoslash title="app/interactions/route.ts" import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; // ---cut--- import { after } from 'next/server'; import { toFetchHandler } from '@nyx-discord/http'; const interactions = toFetchHandler(client); export const POST = (request: Request) => interactions(request, { waitUntil: after }); ``` ```ts twoslash title="app/webhook-events/route.ts" import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; // ---cut--- import { after } from 'next/server'; import { toFetchHandler } from '@nyx-discord/http'; const webhookEvents = toFetchHandler(client.getWebhookEventHandler()); export const POST = (request: Request) => webhookEvents(request, { waitUntil: after }); ``` ## Anything else [#anything-else] Call `handle()` with the raw body (a `string` or `Uint8Array`) and the two signature headers, then send back what it returns. The webhook event handler works the same way: ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; declare const client: HttpNyxClient; declare const rawBody: Uint8Array; declare const headers: Record; declare const originalRequest: unknown; // ---cut--- const result = await client.handle({ body: rawBody, signature: headers['x-signature-ed25519'], timestamp: headers['x-signature-timestamp'], raw: originalRequest, // optional, for TypedFields.HttpRequest }); result.status; // the status code result.headers; // the headers to set result.body; // the body, empty when there's none result.handled; // settles once the handlers finish, for waitUntil() ``` # Handling requests (https://nyx-discord.github.io/nyx/guide/use/http/requests) ## Responses [#responses] Every request goes through the same checks before it reaches your bot: | Request | Response | |---------------------------------------------------|------------------------| | Before `bot.start()` finishes | `503` | | Missing or invalid signature | `401` | | Timestamp older (or newer) than `maxTimestampAge` | `401` | | Body that isn't valid JSON | `400` | | Interaction `PING` (Discord checking your URL) | `200` with a `PONG` | | Any other interaction | `202` with no body | | [Webhook event](/use/http/webhook-events) or its `PING` | `204` with no body | Rejecting old timestamps protects against replayed requests: someone who captured a valid request can't send it again later. The window is 5 minutes by default, see [Configuration](/use/http/configuration). ## Replying to interactions [#replying-to-interactions] Over the gateway, commands reply by calling Discord's REST API, like `api.interactions.reply()`. Over HTTP they do exactly the same: Discord accepts interaction responses through the REST callback endpoint, as long as the HTTP request itself is answered with a `202`. This means commands, components and autocompletes written for `@discordjs/core` work unchanged: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, ToEventProps } from '@discordjs/core'; // ---cut--- import { AbstractStandaloneCommand } from '@nyx-discord/http'; class PingCommand extends AbstractStandaloneCommand { // ---cut-start--- protected readonly data = {} as RESTPostAPIChatInputApplicationCommandsJSONBody; // ---cut-end--- public async execute({ data, api }: ToEventProps) { await api.interactions.reply(data.id, data.token, { content: 'Pong!' }); } } ``` The client doesn't answer Discord's request right away. It waits until the interaction is acknowledged (any reply, defer, update, modal or autocomplete response), until the handlers finish without acknowledging it (for example, when no command matches), or until `acknowledgeTimeout` passes (3 seconds by default), and then returns the `202`. Discord requires the first response within 3 seconds, so slow commands should defer first, exactly like on the gateway. ## Reading the request [#reading-the-request] `TypedFields.HttpRequest` gets the HTTP request an interaction or webhook event came from, from the metadata of commands, components and subscribers. Its `raw` property is the original request from your server or runtime, so you can read anything else from it, like headers: ```ts twoslash import type { APIChatInputApplicationCommandInteraction, RESTPostAPIChatInputApplicationCommandsJSONBody, ToEventProps } from '@discordjs/core'; // ---cut--- import { AbstractStandaloneCommand, TypedFields, type Metadata } from '@nyx-discord/http'; class WhereAmICommand extends AbstractStandaloneCommand { // ---cut-start--- protected readonly data = {} as RESTPostAPIChatInputApplicationCommandsJSONBody; // ---cut-end--- public async execute({ data, api }: ToEventProps, meta: Metadata) { const request = TypedFields.HttpRequest.get(meta); // ^? // raw is a fetch Request with toFetchHandler, or a node:http IncomingMessage with toNodeListener const country = request?.raw instanceof Request ? request.raw.headers.get('cf-ipcountry') : null; await api.interactions.reply(data.id, data.token, { content: `You're in ${country ?? 'somewhere'}` }); } } ``` `HttpBot` sets this up for you. If you create the `HttpNyxClient` yourself, add the field to the client event bus once the bot is created: ```ts twoslash import type { CoreNyxBot, HttpNyxClient } from '@nyx-discord/http'; declare const bot: CoreNyxBot; declare const client: HttpNyxClient; // ---cut--- import { TypedFields } from '@nyx-discord/http'; bot.getClientEventBus().getMetadataFactory().addDefaultField(TypedFields.HttpRequest, () => client.getCurrentRequest()); ``` The client only knows which request it's emitting while its listeners are being called, so this relies on the bus creating its metadata as soon as it receives an event, before awaiting anything. nyx's default buses do. A custom bus that doesn't would see `null`. ## Serverless platforms [#serverless-platforms] On serverless platforms, the runtime may stop once the response is sent. Anything your command does after its first reply (follow-ups, edits, other API calls) can then be cut off. Every result from the client has a `handled` promise, which settles once the request's handlers finish: your commands, components and subscribers. Pass it to your platform's tool for keeping work alive, like [`ctx.waitUntil()`](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil) on Cloudflare Workers or [`after()`](https://nextjs.org/docs/app/api-reference/functions/after) on Next.js. `toFetchHandler()` does it for you when you pass a context with `waitUntil` as its second argument, see [Mounting](/use/http/mounting). When calling `handle()` yourself: ```ts twoslash import type { HttpNyxClient, HttpEndpointRequest } from '@nyx-discord/http'; declare const client: HttpNyxClient; declare const request: HttpEndpointRequest; declare const ctx: { waitUntil(promise: Promise): void }; // ---cut--- const result = await client.handle(request); ctx.waitUntil(result.handled); ``` Webhook events need this the most: the client answers them right away, before any subscriber runs. # AWS Lambda (https://nyx-discord.github.io/nyx/guide/use/http/serverless/aws-lambda) This page assumes you've read [Serverless](/use/http/serverless), and have a `createBot()` function like the one there. Lambda has no `waitUntil`: it freezes the function as soon as the handler returns. The handler below waits for your handlers to finish before returning, so Discord gets its HTTP response only after your command is done. Its reply still reaches Discord in time, since commands reply through the API, but keep commands short, and move slow work (anything after a defer that takes more than a few seconds) to a queue processed by another function. ### Installing [#installing] ```npm npm i @nyx-discord/http @discordjs/core ``` ```npm npm i -D @types/aws-lambda esbuild ``` ### Writing the handler [#writing-the-handler] Lambda passes the request as an event instead of a `Request`, so call the client's `handle()` yourself. The body can arrive base64-encoded, and the signature is checked against its exact bytes, so decode it as a buffer: ```ts twoslash title="src/index.ts" // @filename: shims.d.ts declare module 'aws-lambda' { export type LambdaFunctionURLEvent = { rawPath: string; body?: string; isBase64Encoded: boolean; headers: Record; }; export type LambdaFunctionURLResult = { statusCode: number; headers: Record; body: string }; } // @filename: index.ts import type { HttpBot } from '@nyx-discord/http'; type BotEnv = { APP_ID: string; DISCORD_PUBLIC_KEY: string; TOKEN: string }; declare function createBot(env: BotEnv, deployCommands: boolean): Promise; // ---cut--- import type { LambdaFunctionURLEvent, LambdaFunctionURLResult } from 'aws-lambda'; const client = createBot(process.env as BotEnv, false).then((bot) => bot.getClient()); export async function handler(event: LambdaFunctionURLEvent): Promise { const handler = event.rawPath === '/webhook-events' ? (await client).getWebhookEventHandler() : await client; const result = await handler.handle({ body: Buffer.from(event.body ?? '', event.isBase64Encoded ? 'base64' : 'utf8'), signature: event.headers['x-signature-ed25519'], timestamp: event.headers['x-signature-timestamp'], raw: event, }); // Lambda freezes once this returns, so wait for the handlers to finish first await result.handled; return { statusCode: result.status, headers: result.headers, body: result.body }; } ``` ### Deploying [#deploying] Deploy the function the way you prefer. Some ways to do it: - **By hand**: bundle with `npx esbuild src/index.ts --bundle --platform=node --target=node22 --format=esm --outfile=dist/index.mjs`, zip `dist/index.mjs`, and upload it on the AWS console. The handler is then `index.handler`. - **[AWS SAM](https://docs.aws.amazon.com/serverless-application-model/)**: a function with `BuildMethod: esbuild` and a `FunctionUrlConfig`, deployed with `sam build && sam deploy`. - **[AWS CDK](https://docs.aws.amazon.com/cdk/)**: a `NodejsFunction`, which bundles your TypeScript by itself, with `addFunctionUrl()`. - **Continuous deployment**: run either of the above from your CI, like GitHub Actions with [`aws-actions/configure-aws-credentials`](https://github.com/aws-actions/configure-aws-credentials), on every push. It's a good place to [deploy your commands](/use/http/serverless#deploying-commands) too. Remember to [deploy your commands](/use/http/serverless#deploying-commands) whichever way you choose. ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to your function URL, and its Webhook Events URL (if you use them) to the same URL ending in `/webhook-events`. # Cloudflare Workers (https://nyx-discord.github.io/nyx/guide/use/http/serverless/cloudflare-workers) This page assumes you've read [Serverless](/use/http/serverless), and have a `createBot()` function like the one there. ### Creating the project [#creating-the-project] ```npm npm create cloudflare@latest my-bot -- --type hello-world --lang ts ``` ```npm npm i @nyx-discord/http @discordjs/core ``` The bot doesn't need the `nodejs_compat` compatibility flag. ### Writing the worker [#writing-the-worker] Workers only give you your secrets through `env` once a request arrives, and don't allow network calls before that, so create the bot on the first request and keep the promise for the next ones. Pass the worker's `ctx` to the handler, so the worker stays alive until your handlers finish: ```ts twoslash title="src/index.ts" import type { HttpBot } from '@nyx-discord/http'; type BotEnv = { APP_ID: string; DISCORD_PUBLIC_KEY: string; TOKEN: string }; type ExecutionContext = { waitUntil(promise: Promise): void }; declare function createBot(env: BotEnv, deployCommands: boolean): Promise; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; type Handlers = { interactions: ReturnType; webhookEvents: ReturnType; }; let handlers: Promise | null = null; function getHandlers(env: BotEnv) { handlers ??= createBot(env, false).then((bot) => { const client = bot.getClient(); return { interactions: toFetchHandler(client), webhookEvents: toFetchHandler(client.getWebhookEventHandler()), }; }); return handlers; } export default { async fetch(request: Request, env: BotEnv, ctx: ExecutionContext) { const { interactions, webhookEvents } = await getHandlers(env); const { pathname } = new URL(request.url); const handler = pathname === '/webhook-events' ? webhookEvents : interactions; return handler(request, ctx); }, }; ``` ### Running locally [#running-locally] Put your secrets in `.dev.vars`: ```bash APP_ID=... DISCORD_PUBLIC_KEY=... TOKEN=... ``` ```npm npx wrangler dev ``` This runs the worker in `workerd`, the same runtime as production. Test it [without Discord](/use/http/serverless#testing-without-discord), or expose it with a tunnel (like `cloudflared tunnel --url http://localhost:8787`) and set the tunnel's URL as your app's Interactions Endpoint URL. ### Deploying [#deploying] Put your secrets in a file kept out of git (it can be the same as `.dev.vars`), and pass it on the first deploy: ```npm npx wrangler deploy --secrets-file .dev.vars ``` Later deploys keep the secrets, so `npx wrangler deploy` is enough. Remember to [deploy your commands](/use/http/serverless#deploying-commands) too. If it's your account's first worker, the deploy also creates your `workers.dev` subdomain, whose certificate can take a few minutes. Until then, requests to it fail with a TLS handshake error. ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to `https://..workers.dev/interactions`, and its Webhook Events URL (if you use them) to `.../webhook-events`. # Serverless (https://nyx-discord.github.io/nyx/guide/use/http/serverless) On serverless platforms there's no long-lived process: the platform starts an instance when a request arrives, may reuse it for a while, and stops it whenever it wants. The bot works the same way there, but a few things need to change compared to a regular server. ## Creating the bot [#creating-the-bot] Create the bot once per instance and reuse it for every request the instance receives. Put its creation in a function, so your platform's entry and your [command deploy script](#deploying-commands) can share it: ```ts twoslash title="src/bot.ts" import { HttpBot } from '@nyx-discord/http'; export type BotEnv = { APP_ID: string; DISCORD_PUBLIC_KEY: string; TOKEN: string }; export async function createBot(env: BotEnv, deployCommands: boolean) { const bot = HttpBot.create(() => ({ applicationId: env.APP_ID, publicKey: env.DISCORD_PUBLIC_KEY, token: env.TOKEN, logger: console, deployCommands, })); // await bot.getCommandManager().addCommands(...); await bot.start(); return bot; } ``` ## Deploying commands [#deploying-commands] Each new instance runs `bot.start()`, so with `deployCommands: true`, every cold start would deploy your commands to Discord again, wasting rate limits and slowing down the first request. Create the bot with `deployCommands: false` on the platform, and deploy commands from your machine (or CI) with a script that reuses the same function: ```ts twoslash title="scripts/deploy-commands.ts" // @noErrors import 'dotenv/config'; import { createBot } from '../src/bot'; await createBot(process.env as never, true); console.log('Commands deployed.'); ``` Run it again whenever you add or change a command. Commands are matched by name, so the bot doesn't need to know their IDs. ## Keeping work alive [#keeping-work-alive] The platform may stop the instance once the response is sent, cutting off anything your commands do after their first reply. Pass the platform's `waitUntil` to the client, see [Serverless platforms](/use/http/requests#serverless-platforms). Platforms without one, like [AWS Lambda](/use/http/serverless/aws-lambda), need to wait for the handlers before responding. Schedules don't run by themselves either, since there's no process to keep their timers. Trigger the work from your platform's scheduled jobs instead, like [Workers cron triggers](https://developers.cloudflare.com/workers/configuration/cron-triggers/). ## Testing without Discord [#testing-without-discord] You can test your endpoint before setting it on the Developer Portal by signing requests yourself. Generate a keypair, use its public key as `DISCORD_PUBLIC_KEY`, and sign each request like Discord does: ```ts twoslash title="scripts/send.ts" // @noErrors import { createPrivateKey, generateKeyPairSync, sign } from 'node:crypto'; // once: generate a keypair, and set `publicKeyHex` as DISCORD_PUBLIC_KEY const { publicKey, privateKey } = generateKeyPairSync('ed25519'); const publicKeyHex = publicKey.export({ format: 'der', type: 'spki' }).subarray(-32).toString('hex'); const body = JSON.stringify({ id: '1', application_id: '1', type: 1, token: 't', version: 1 }); const timestamp = Math.floor(Date.now() / 1000).toString(); const signature = sign(null, Buffer.from(timestamp + body), privateKey).toString('hex'); const response = await fetch('http://localhost:8787/interactions' /* your local URL */, { method: 'POST', headers: { 'X-Signature-Ed25519': signature, 'X-Signature-Timestamp': timestamp }, body, }); console.log(response.status, await response.text()); // 200 {"type":1} ``` That's a `PING`. Sending an application command interaction runs your command, though its reply fails with `Unknown interaction`, since Discord never created it. ## Platform examples [#platform-examples] } href="/use/http/serverless/cloudflare-workers" external={false} /> } href="/use/http/serverless/vercel" external={false} /> } href="/use/http/serverless/netlify" external={false} /> } href="/use/http/serverless/supabase" external={false} /> } href="/use/http/serverless/aws-lambda" external={false} /> # Netlify (https://nyx-discord.github.io/nyx/guide/use/http/serverless/netlify) This page assumes you've read [Serverless](/use/http/serverless), and have a `createBot()` function like the one there. ### Installing [#installing] In your project, install the bot and Netlify's types: ```npm npm i @nyx-discord/http @discordjs/core ``` ```npm npm i -D @netlify/functions ``` ### Writing the function [#writing-the-function] Functions go in `netlify/functions/`, and `config.path` sets the URLs they're served at. Your secrets are in `process.env` when the module loads, so the bot can be created right away. Netlify's `context` has a `waitUntil`, so pass it as is to keep the function alive until your handlers finish: ```ts twoslash title="netlify/functions/discord.mts" // @filename: shims.d.ts declare module '@netlify/functions' { export type Context = { waitUntil(promise: Promise): void }; export type Config = { path: string[] }; } // @filename: index.ts import type { HttpBot } from '@nyx-discord/http'; type BotEnv = { APP_ID: string; DISCORD_PUBLIC_KEY: string; TOKEN: string }; declare function createBot(env: BotEnv, deployCommands: boolean): Promise; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; import type { Config, Context } from '@netlify/functions'; const handlers = createBot(process.env as BotEnv, false).then((bot) => { const client = bot.getClient(); return { interactions: toFetchHandler(client), webhookEvents: toFetchHandler(client.getWebhookEventHandler()), }; }); export default async (request: Request, context: Context) => { const { interactions, webhookEvents } = await handlers; const { pathname } = new URL(request.url); const handler = pathname === '/webhook-events' ? webhookEvents : interactions; return handler(request, context); }; export const config: Config = { path: ['/interactions', '/webhook-events'], }; ``` ### Running locally [#running-locally] Put your secrets in `.env`: ```bash APP_ID=... DISCORD_PUBLIC_KEY=... TOKEN=... ``` ```npm npx netlify dev ``` Test it [without Discord](/use/http/serverless#testing-without-discord) at `http://localhost:8888/interactions`, or expose it with `npx netlify dev --live` and set that URL as your app's Interactions Endpoint URL. ### Deploying [#deploying] Add your secrets to the site, from your `.env` file: ```npm npx netlify env:import .env ``` ```npm npx netlify deploy --prod ``` Remember to [deploy your commands](/use/http/serverless#deploying-commands) too. ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to `https://.netlify.app/interactions`, and its Webhook Events URL (if you use them) to `https://.netlify.app/webhook-events`. # Supabase Edge Functions (https://nyx-discord.github.io/nyx/guide/use/http/serverless/supabase) This page assumes you've read [Serverless](/use/http/serverless), and have a `createBot()` function like the one there. Edge Functions run on Deno, so packages are imported with `npm:` specifiers. ### Creating the function [#creating-the-function] In a project set up with the [Supabase CLI](https://supabase.com/docs/guides/cli): ```npm npx supabase functions new discord ``` Discord doesn't send Supabase's authorization header, so turn off JWT verification for the function in `supabase/config.toml`: ```toml [functions.discord] verify_jwt = false ``` ### Writing the function [#writing-the-function] Your secrets are in `Deno.env` when the module loads, so the bot can be created right away. Pass `EdgeRuntime.waitUntil`, so the function stays alive until your handlers finish. Keep the `edge-runtime.d.ts` import the CLI generated, which types it: ```ts twoslash title="supabase/functions/discord/index.ts" // @noErrors import 'jsr:@supabase/functions-js/edge-runtime.d.ts'; import { toFetchHandler } from 'npm:@nyx-discord/http'; import { createBot } from './bot.ts'; const handlers = createBot( { APP_ID: Deno.env.get('APP_ID')!, DISCORD_PUBLIC_KEY: Deno.env.get('DISCORD_PUBLIC_KEY')!, TOKEN: Deno.env.get('TOKEN')!, }, false, ).then((bot) => { const client = bot.getClient(); return { interactions: toFetchHandler(client), webhookEvents: toFetchHandler(client.getWebhookEventHandler()), }; }); Deno.serve(async (request) => { const { interactions, webhookEvents } = await handlers; const { pathname } = new URL(request.url); const handler = pathname.endsWith('/webhook-events') ? webhookEvents : interactions; return handler(request, { waitUntil: (promise) => EdgeRuntime.waitUntil(promise) }); }); ``` Import `HttpBot` in your `bot.ts` from `npm:@nyx-discord/http` as well. ### Running locally [#running-locally] Put your secrets in `supabase/functions/.env`: ```bash APP_ID=... DISCORD_PUBLIC_KEY=... TOKEN=... ``` ```npm npx supabase functions serve ``` This needs Docker running. Test it [without Discord](/use/http/serverless#testing-without-discord) at `http://localhost:54321/functions/v1/discord`. ### Deploying [#deploying] ```npm npx supabase secrets set --env-file supabase/functions/.env ``` ```npm npx supabase functions deploy discord ``` Remember to [deploy your commands](/use/http/serverless#deploying-commands) too, from Node or with `deno run`. ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to `https://.supabase.co/functions/v1/discord`, and its Webhook Events URL (if you use them) to `.../functions/v1/discord/webhook-events`. # Vercel (https://nyx-discord.github.io/nyx/guide/use/http/serverless/vercel) This page assumes you've read [Serverless](/use/http/serverless), and have a `createBot()` function like the one there. If your bot lives in a Next.js app, use a [route handler](/use/http/mounting#nextjs) instead. ### Installing [#installing] In your project, install the bot and Vercel's helpers: ```npm npm i @nyx-discord/http @discordjs/core @vercel/functions ``` ### Writing the function [#writing-the-function] Every file in `api/` is a function, served at its path. Your secrets are in `process.env` when the module loads, so the bot can be created right away. Pass `waitUntil` from `@vercel/functions`, so the function stays alive until your handlers finish: ```ts twoslash title="api/interactions.ts" // @filename: shims.d.ts declare module '@vercel/functions' { export function waitUntil(promise: Promise): void; } // @filename: index.ts import type { HttpBot } from '@nyx-discord/http'; type BotEnv = { APP_ID: string; DISCORD_PUBLIC_KEY: string; TOKEN: string }; declare function createBot(env: BotEnv, deployCommands: boolean): Promise; // ---cut--- import { toFetchHandler } from '@nyx-discord/http'; import { waitUntil } from '@vercel/functions'; const handler = createBot(process.env as BotEnv, false).then((bot) => toFetchHandler(bot.getClient()), ); export async function POST(request: Request) { return (await handler)(request, { waitUntil }); } ``` For [webhook events](/use/http/webhook-events), add an `api/webhook-events.ts` that does the same with `toFetchHandler(bot.getClient().getWebhookEventHandler())`. ### Running locally [#running-locally] Put your secrets in `.env.local`: ```bash APP_ID=... DISCORD_PUBLIC_KEY=... TOKEN=... ``` ```npm npx vercel dev ``` Test it [without Discord](/use/http/serverless#testing-without-discord) at `http://localhost:3000/api/interactions`, or expose it with a tunnel and set the tunnel's URL as your app's Interactions Endpoint URL. ### Deploying [#deploying] Add your secrets to the project, for each of `APP_ID`, `DISCORD_PUBLIC_KEY` and `TOKEN`: ```npm npx vercel env add TOKEN production ``` ```npm npx vercel deploy --prod ``` Remember to [deploy your commands](/use/http/serverless#deploying-commands) too. ### Setting the endpoint [#setting-the-endpoint] On the Developer Portal, set your app's **Interactions Endpoint URL** to `https://.vercel.app/api/interactions`, and its Webhook Events URL (if you use them) to `https://.vercel.app/api/webhook-events`. # Webhook events (https://nyx-discord.github.io/nyx/guide/use/http/webhook-events) Besides interactions, Discord can send some events about your app over HTTP: [webhook events](https://discord.com/developers/docs/events/webhook-events). For example, when a user authorizes or deauthorizes your app, or when an entitlement is created. They're sent to a separate URL, the **Webhook Events URL**, which you set on the Developer Portal under **Webhooks**, along with the events you want to receive. ## Mounting [#mounting] `client.getWebhookEventHandler()` returns a handler for that URL, which works with the same [adapters](/use/http/mounting) as the client: ```ts twoslash import type { HttpNyxClient } from '@nyx-discord/http'; import type { RequestListener } from 'node:http'; declare const client: HttpNyxClient; declare const app: { post(path: string, handler: RequestListener): void }; // ---cut--- import { toNodeListener } from '@nyx-discord/http'; app.post('/interactions', toNodeListener(client)); app.post('/webhook-events', toNodeListener(client.getWebhookEventHandler())); ``` The handler verifies requests like the client does, and answers every event (and Discord's `PING`) with a `204`. ## Subscribing [#subscribing] Each event is emitted on the client's emitter under its type, one of the [`ApplicationWebhookEventType`](https://discord-api-types.dev/api/discord-api-types-v10/enum/ApplicationWebhookEventType) values. An `HttpBot`'s client event bus accepts them, so write an `AbstractWebhookEventSubscriber` and subscribe it like any other client subscriber: ```ts twoslash import type { HttpBot } from '@nyx-discord/http'; declare const bot: HttpBot; // ---cut--- import type { APIWebhookEventApplicationAuthorizedData } from '@discordjs/core'; import { ApplicationWebhookEventType } from '@discordjs/core'; import { AbstractWebhookEventSubscriber, type Metadata, type WebhookEventProps } from '@nyx-discord/http'; class AuthorizedSubscriber extends AbstractWebhookEventSubscriber { protected readonly event = ApplicationWebhookEventType.ApplicationAuthorized; public handleEvent( _meta: Metadata, { data, timestamp }: WebhookEventProps, ) { console.log(`${data.user.username} authorized the app at ${timestamp}`); // ^? } } await bot.subscribeToClient(new AuthorizedSubscriber()); ``` Since they're client subscribers, the [event loader](/loaders/events) picks them up too, and their metadata has the same fields as other client events, like [`TypedFields.HttpRequest`](/use/http/requests#reading-the-request). The payload is the usual `{ data, api, shardId }`, where `data` is the event's data (`APIWebhookEvent...Data` from `discord-api-types`), plus the event's `timestamp`. Webhook events aren't realtime and can arrive late or out of order, so use the timestamp when order matters. Discord retries an event for up to 10 minutes if your endpoint doesn't answer, and stops sending events if it fails too often. Since the handler answers as soon as the event is emitted, slow subscribers don't delay the response. # Introduction (https://nyx-discord.github.io/nyx/guide/use) ![nyx](/nyx_guide.png) Hello there 👋! Welcome to official guide for using nyx, a TypeScript bot framework for Discord. Here, you'll discover what nyx is, how to create your own bot and how to customize it. ## What is nyx? [#what-is-nyx] Nyx is a framework to build Discord bots in TypeScript, with adapters for [discord.js](https://discord.js.org), [@discordjs/core](https://discord.js.org/docs/packages/core/main) and HTTP-only bots with [`@nyx-discord/http`](/use/http), built on top of `@discordjs/core`. The main ideas behind the framework are: } title="Fully extendable"> Every single internal component is documented and can be easily swapped by your own. We want you to know how your bot fully works. } title="Bare-bones"> As little runtime dependencies as possible, which you can also replace. } title="Architecture freedom"> Nyx doesn't enforce any specific way to do things. Choose your own folder structure, way to load commands/events, databases, naming conventions, etc. } title="Easy to understand and setup"> Hacky code is avoided, like changing Discord.js typings or internals. Type safety, error handling and extensibility are prioritized over convenience and magic. } title="Native objects"> Use the objects you already know from your Discord library without needing to learn new wrappers. } title="A presentation layer, not the whole system"> Nyx doesn't own your bot's logic, build step or runtime. It's the layer that connects Discord to your design, so your core logic stays independent and testable. - We assume you have some level of understanding of TypeScript. - The framework doesn't come with any commands, events or filters (like cooldowns). To avoid being too opinionated, we only ship the things required for you to be able to build such features. Our optional packages provide some utilities, but you can also build your own. ## Key Features [#key-features] 1. **[Commands](/use/commands)**, for Discord application commands. Includes support for context menu commands, subcommands, and more. 2. **[Events](/use/events)**, for subscribing to events, either from Discord.js or your own. 3. **[Schedules](/use/schedules)**, for timed tasks. 4. **[Plugins](/use/plugins)**, for pieces that extend nyx. All of these features are documented in detail in their respective sections, which we'll cover next. Through optional packages, it also supports: 1. **[Sessions](/session)**, for stateful interaction conversations, similar to collectors. 2. **[Loaders](/loaders)**, for scanning directories to load commands, events, and schedules. 3. **[Type-safe Options](/typed-options)**, for creating commands with type-safe options. The codeblocks in this guide are powered by [Twoslash](https://twoslash.netlify.app/guide/), meaning: - You can hover over variables, functions, etc. to see their documentation. - Every example (only often skipping trivial or already mentioned declarations) will work, otherwise this guide wouldn't compile! ## Community and Contribution [#community-and-contribution] Click on each card to go to its page. } href={discordInvite} title="Discord Community"> Join our Discord server to ask questions, share your creations, and get help from the team or the community. } href="https://github.com/nyx-discord/nyx" title="Contribute" > If you want to contribute, you can do so by opening issues or pull requests on our GitHub repository. # Error Handling (https://nyx-discord.github.io/nyx/guide/use/other/error-handling) Every executor holds an `ErrorHandler`, where errors thrown by middlewares and executed objects are handled. ```ts twoslash import { NyxBot, AnyEventBus } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const bus: AnyEventBus; // ---cut--- const commandErrorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); const eventErrorHandler = bus.getDispatcher().getErrorHandler(); const scheduleErrorHandler = bot.getScheduleManager().getExecutor().getErrorHandler(); ``` ```ts twoslash import { NyxBot, AnyEventBus } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const bus: AnyEventBus; // ---cut--- const commandErrorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); const eventErrorHandler = bus.getDispatcher().getErrorHandler(); const scheduleErrorHandler = bot.getScheduleManager().getExecutor().getErrorHandler(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxBot, AnyEventBus } from '@nyx-discord/http'; declare const bot: NyxBot; declare const bus: AnyEventBus; // ---cut--- const commandErrorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); const eventErrorHandler = bus.getDispatcher().getErrorHandler(); const scheduleErrorHandler = bot.getScheduleManager().getExecutor().getErrorHandler(); ``` It holds a map of consumers, where each handle a specific error class. It also receives the erroring object, and the arguments that were used to call it. ## Manipulating consumers [#manipulating-consumers] This example will use the `CommandManager`'s handler, but it works the same for other executors. To add a consumer, use `ErrorHandler#setConsumer()`: ```ts twoslash import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); // ---cut--- import { TypedFields, CommandError } from '@nyx-discord/djs'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs'; errorHandler.setConsumer( CommandError, ( error: CommandError, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `MyError occurred while executing ${name} with args: ${args}`, error ); } ); ``` ```ts twoslash import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); // ---cut--- import { TypedFields, CommandError } from '@nyx-discord/djs-core'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs-core'; errorHandler.setConsumer( CommandError, ( error: CommandError, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `MyError occurred while executing ${name} with args: ${args}`, error ); } ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); // ---cut--- import { TypedFields, CommandError } from '@nyx-discord/http'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/http'; errorHandler.setConsumer( CommandError, ( error: CommandError, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `MyError occurred while executing ${name} with args: ${args}`, error ); } ); ``` You can also remove consumers: ```ts twoslash import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/djs'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs'; // ---cut--- errorHandler.removeConsumerOf(CommandError); ``` ```ts twoslash import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/djs-core'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs-core'; // ---cut--- errorHandler.removeConsumerOf(CommandError); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/http'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/http'; // ---cut--- errorHandler.removeConsumerOf(CommandError); ``` And set a fallback consumer, for all errors that don't have a consumer: ```ts twoslash import { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/djs'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs'; // ---cut--- import { TypedFields } from '@nyx-discord/djs'; errorHandler.setFallbackConsumer( ( error: object, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `An unhandled error occurred while executing ${name} with args: ${args}`, error ); } ); ``` ```ts twoslash import { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/djs-core'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/djs-core'; // ---cut--- import { TypedFields } from '@nyx-discord/djs-core'; errorHandler.setFallbackConsumer( ( error: object, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `An unhandled error occurred while executing ${name} with args: ${args}`, error ); } ); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; const errorHandler = bot.getCommandManager().getExecutor().getErrorHandler(); import { CommandError } from '@nyx-discord/http'; import type { CommandExecutionArgs, AnyExecutableCommand } from '@nyx-discord/http'; // ---cut--- import { TypedFields } from '@nyx-discord/http'; errorHandler.setFallbackConsumer( ( error: object, command: AnyExecutableCommand, args: CommandExecutionArgs, ) => { const [_interaction, meta] = args; const { name } = command.getData(); TypedFields.getLogger(meta).error( `An unhandled error occurred while executing ${name} with args: ${args}`, error ); } ); ``` ## Consumer resolution [#consumer-resolution] The error handler resolves a consumer based on the error prototype, going from the top to the bottom. For instance: ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/djs'; const errorHandler = BasicErrorHandler.create(); // ---cut--- class MyError extends Error {} class MyError2 extends MyError {} errorHandler.setConsumer(MyError, () => { console.log('MyError'); }); ``` ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/djs-core'; const errorHandler = BasicErrorHandler.create(); // ---cut--- class MyError extends Error {} class MyError2 extends MyError {} errorHandler.setConsumer(MyError, () => { console.log('MyError'); }); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { BasicErrorHandler } from '@nyx-discord/http'; const errorHandler = BasicErrorHandler.create(); // ---cut--- class MyError extends Error {} class MyError2 extends MyError {} errorHandler.setConsumer(MyError, () => { console.log('MyError'); }); ``` This will log `MyError` when an instance of `MyError2` is thrown, because it's a subclass. If no consumer is found, the fallback consumer is used, whose error type is simply `object`. # Filters (https://nyx-discord.github.io/nyx/guide/use/other/filters) Filters are objects or callbacks that can restrict the execution of a given component. They receive all the information about the execution (context, arguments, metadata), and return a boolean indicating whether the execution should proceed (`true`) or strictly stop (`false`). ## Wrapping/Merging Filters [#wrappingmerging-filters] The framework has some utility filters that wrap or merge others, allowing you to create complex filters by combining simpler ones. These wrappers work "synchronously", meaning that it'll wait for each filter, in the order they were passed, before checking whether to proceed to the next. ### AndFilter [#andfilter] Combines multiple filters and only allows the execution if **all** filters return `true`. ```ts new AndFilter(filter1, filter2, filter3) ``` ### OrFilter [#orfilter] Combines multiple filters and allows the execution if **at least one** filter returns `true`. ```ts new OrFilter(filter1, filter2) ``` ### NotFilter [#notfilter] Inverts the result of a single filter, allowing the execution if the filter returns `false`. ```ts new NotFilter(filter) ``` # Metadata (https://nyx-discord.github.io/nyx/guide/use/other/metadata) Many parts of the framework introduce the concept of a `Metadata`, which can store metadata about a given object, or about a given execution. ## Type Safety [#type-safety] Since a metadata object is just a record of unknown values, it's inherently unsafe by itself. For that reason, nyx uses the [`typed-field`](https://www.npmjs.com/package/typed-field) package, which creates a unique key, and only lets you set/get with a given type. The `typed-field` package is re-exported in `TypedFields.create()` method, so you don't need to install it separately. ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/djs'; const meta: Record = Object.create(null); // Fields with the same description won't collide const field = TypedFields.create('someDescription'); field.set(meta, 42); field.set(meta, 'foo'); const stored = field.get(meta); // ^? // Throws if no value was set const forced = field.get(meta, true); // ^? ``` ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/djs-core'; const meta: Record = Object.create(null); // Fields with the same description won't collide const field = TypedFields.create('someDescription'); field.set(meta, 42); field.set(meta, 'foo'); const stored = field.get(meta); // ^? // Throws if no value was set const forced = field.get(meta, true); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/http'; const meta: Record = Object.create(null); // Fields with the same description won't collide const field = TypedFields.create('someDescription'); field.set(meta, 42); field.set(meta, 'foo'); const stored = field.get(meta); // ^? // Throws if no value was set const forced = field.get(meta, true); // ^? ``` ## Object Metadata [#object-metadata] Most nyx objects implement a `getMeta(): ReadonlyMetadata` method. When creating your class, you can fill this with your own metadata, which can then be read by plugins or other entities to extract extra information about your object. As a plugin developer, you may also choose to use the `TypedFields` API to create and expose a field: ```ts twoslash import { TypedFields } from '@nyx-discord/djs'; type MyPluginData = { someKey: string; } export const MyPluginDataField = TypedFields.create('myPluginData'); ``` ```ts twoslash import { TypedFields } from '@nyx-discord/djs-core'; type MyPluginData = { someKey: string; } export const MyPluginDataField = TypedFields.create('myPluginData'); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { TypedFields } from '@nyx-discord/http'; type MyPluginData = { someKey: string; } export const MyPluginDataField = TypedFields.create('myPluginData'); ``` Then, a consumer of your plugin can use it to decorate their objects' metadata: ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/djs'; type MyPluginData = { someKey: string; } const MyPluginDataField = TypedFields.create('myPluginData'); // ---cut--- import { AbstractStandaloneCommand } from '@nyx-discord/djs'; // @noErrors import { MyPluginDataField } from 'my-nyx-plugin'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { constructor() { super(); MyPluginDataField.set(this.meta, { someKey: 'someValue' }); // In case they use it wrongly, it'll error: MyPluginDataField.set(this.meta, 42); } } ``` ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/djs-core'; type MyPluginData = { someKey: string; } const MyPluginDataField = TypedFields.create('myPluginData'); // ---cut--- import { AbstractStandaloneCommand } from '@nyx-discord/djs-core'; // @noErrors import { MyPluginDataField } from 'my-nyx-plugin'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { constructor() { super(); MyPluginDataField.set(this.meta, { someKey: 'someValue' }); // In case they use it wrongly, it'll error: MyPluginDataField.set(this.meta, 42); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // @errors: 2345 import { TypedFields } from '@nyx-discord/http'; type MyPluginData = { someKey: string; } const MyPluginDataField = TypedFields.create('myPluginData'); // ---cut--- import { AbstractStandaloneCommand } from '@nyx-discord/http'; // @noErrors import { MyPluginDataField } from 'my-nyx-plugin'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MyCommand extends AbstractStandaloneCommand { constructor() { super(); MyPluginDataField.set(this.meta, { someKey: 'someValue' }); // In case they use it wrongly, it'll error: MyPluginDataField.set(this.meta, 42); } } ``` Which then you'll be able to read with `MyCommand#getMeta()` and your field, safely. ## Execution Metadata [#execution-metadata] Every "executable" object includes in its arguments an instance of a `Metadata`, which is passed around to middlewares and filters, so they can share data between them, and to your executed object. Additionally, the `TypedFields` class contains constant fields that the framework uses to store framework-specific data. ```ts twoslash import { Collection } from 'discord.js'; const meta: Record = Object.create(null); // ---cut--- import { TypedFields } from '@nyx-discord/djs'; // The bot who triggered the object (command, event, etc). const bot = TypedFields.Bot.get(meta, true); // ^? // Shorthands for the bot typed for this adapter, its discord.js Client and its logger, which throw if the meta has no bot. const typedBot = TypedFields.getBot(meta); // ^? const client = TypedFields.getClient(meta); // ^? const logger = TypedFields.getLogger(meta); // ^? // The identifier of this object execution, which is a Symbol containing some debugable information. const id = TypedFields.Id.get(meta, true); // ^? // The creation date of this meta, can be used as the execution start time. const creationDate = TypedFields.CreationDate.get(meta, true); // ^? // Only for event middlewares and subscribers, whether the event was marked as handled by a subscriber. const handled = TypedFields.EventHandled.get(meta, true); // ^? // Only for event middlewares and subscribers, the EventBus that dispatched the event. const eventBus = TypedFields.EventBus.get(meta, true); // ^? ``` ```ts twoslash import { Collection } from 'discord.js'; const meta: Record = Object.create(null); // ---cut--- import { TypedFields } from '@nyx-discord/djs-core'; // The bot who triggered the object (command, event, etc). const bot = TypedFields.Bot.get(meta, true); // ^? // Shorthands for the bot typed for this adapter, its @discordjs/core gateway Client, its REST API and its logger, which throw if the meta has no bot. const typedBot = TypedFields.getBot(meta); // ^? const client = TypedFields.getClient(meta); // ^? const api = TypedFields.getApi(meta); // ^? const logger = TypedFields.getLogger(meta); // ^? // The identifier of this object execution, which is a Symbol containing some debugable information. const id = TypedFields.Id.get(meta, true); // ^? // The creation date of this meta, can be used as the execution start time. const creationDate = TypedFields.CreationDate.get(meta, true); // ^? // Only for event middlewares and subscribers, whether the event was marked as handled by a subscriber. const handled = TypedFields.EventHandled.get(meta, true); // ^? // Only for event middlewares and subscribers, the EventBus that dispatched the event. const eventBus = TypedFields.EventBus.get(meta, true); // ^? ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { Collection } from 'discord.js'; const meta: Record = Object.create(null); // ---cut--- import { TypedFields } from '@nyx-discord/http'; // The bot who triggered the object (command, event, etc). const bot = TypedFields.Bot.get(meta, true); // ^? // Shorthands for the bot typed for this adapter, its @discordjs/core gateway Client, its REST API and its logger, which throw if the meta has no bot. const typedBot = TypedFields.getBot(meta); // ^? const client = TypedFields.getClient(meta); // ^? const api = TypedFields.getApi(meta); // ^? const logger = TypedFields.getLogger(meta); // ^? // The identifier of this object execution, which is a Symbol containing some debugable information. const id = TypedFields.Id.get(meta, true); // ^? // The creation date of this meta, can be used as the execution start time. const creationDate = TypedFields.CreationDate.get(meta, true); // ^? // Only for event middlewares and subscribers, whether the event was marked as handled by a subscriber. const handled = TypedFields.EventHandled.get(meta, true); // ^? // Only for event middlewares and subscribers, the EventBus that dispatched the event. const eventBus = TypedFields.EventBus.get(meta, true); // ^? ``` Forcing these reads is safe for metadatas created inside the framework, but not for user-created metadatas, including those created by external [`EventBuses`](/use/events/buses) (since they're bot-independent). # Middlewares (https://nyx-discord.github.io/nyx/guide/use/other/middlewares) Middlewares are objects or callbacks that run before an execution. They can do some pre-processing logic and store it in the metadata, or even prevent the execution. We will review some concepts before going into the usage. ## Priorities [#priorities] The determines the order in which they are executed: - Higher priorities are executed first. - Monitors are specifically meant for monitoring (e.g. metrics), though that's not enforced. - `HighMonitor` is the first priority to be executed. - `LowMonitor` is the last priority to be executed. ```ts twoslash import { PriorityEnum } from '@nyx-discord/djs'; // @noErrors PriorityEnum. // ^| ``` ```ts twoslash import { PriorityEnum } from '@nyx-discord/djs-core'; // @noErrors PriorityEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { PriorityEnum } from '@nyx-discord/http'; // @noErrors PriorityEnum. // ^| ``` The default priority is `Normal`, it's changed by overriding the `priority` property in classes. It can't be changed for callback-based middlewares. ## Responses [#responses] A middleware returns a that indicates whether it passes, forces to pass, or fails. If a middleware fails, the execution will stop. Use the utility methods from the abstract middleware class to create the response: - `true()` - The middleware passes, and the execution will continue. - `false()` - The middleware fails, and the execution will stop. - `forceTrue()` - The middleware forces to pass, even if other later middlewares would fail. If you're using a callback-based middleware, you'll need to create your response manually. # Packages (https://nyx-discord.github.io/nyx/guide/use/packages) ## Which package do I need? [#which-package-do-i-need] You only need to install **one**: the adapter that matches how your bot connects to Discord. | If your bot... | Install | |---------------------------------------------------------------------------------------------------|-------------------------| | Uses [discord.js](https://discord.js.org) | `@nyx-discord/djs` | | Uses [@discordjs/core](https://discord.js.org/docs/packages/core/main) | `@nyx-discord/djs-core` | | Only handles HTTP payloads instead of the gateway (e.g. on a serverless platform) | `@nyx-discord/http` | Under the hood, every adapter is built over `@nyx-discord/base`, which has the interfaces every component follows, plus some default implementations of them. The adapters add the missing parts that connect to your Discord library. Every component depends on interfaces rather than on the default implementations, so you can replace any of them with your own. You can later check the [Extend](/extend) section for how. ## Interfaces and implementations [#interfaces-and-implementations] `@nyx-discord/base` contains two kinds of objects, which you can tell apart by their names. **Interfaces** have no prefix, like SubCommand} /> or CommandManager} />. They describe what a component does, and are what the rest of the framework expects. **Implementations** have a prefix that tells you how to use them: | Prefix | Meaning | Example | |------------|-------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------| | `Abstract` | Needs to be extended to be used. You'll extend these to create your own commands, subscribers, schedules, etc. | AbstractSchedule} /> | | `Basic` | A complete, simple implementation. Use it directly, or extend it to customize it. | BasicEventBus} /> | | `Default` | The implementation the bot uses internally. To customize it, extend it and [inject your version](/extend). | DefaultCommandManager} /> | | `Base` | A Discord-library-agnostic foundation that the adapters build on. You won't use these directly. | BaseCommand} /> | For example, your adapter's AbstractStandaloneCommand} /> builds on BaseStandaloneCommand} />, adding the types of your Discord library. Extend the adapter's version, not the `Base` one. When you want to specify a type, prefer the interfaces, e.g. `consume(cmd: SubCommand)` instead of `consume(cmd: AbstractSubCommand)`. That way your code works with any implementation, following [Dependency inversion](https://en.wikipedia.org/wiki/Dependency_inversion_principle). ## Building something for nyx [#building-something-for-nyx] If you're developing something for nyx itself, such as a plugin, you can depend on `@nyx-discord/base` instead of an adapter, so your component works across all of them. `@nyx-discord/base` also lets you import each kind of object separately: | Import | Contains | |------------------------------|------------------------------| | `@nyx-discord/base` | Everything. | | `@nyx-discord/base/types` | Only the interfaces. | | `@nyx-discord/base/defaults` | Only the implementations. | Importing your types from `@nyx-discord/base/types` makes it impossible to accidentally depend on an implementation. # Events (https://nyx-discord.github.io/nyx/guide/use/plugins/events) It's recommended to read the [Events Overview](../events/index) and [Event Subscribers](../events/subscribers) pages first. The `PluginManager` has an `EventBus` that allows you to listen to events related to plugins. This is useful for monitoring, logging, or any other custom logic you want to execute when a plugin is added/removed. ## Events [#events] The following events are available: ```ts twoslash import { PluginEventEnum } from '@nyx-discord/djs'; // @noErrors PluginEventEnum. // ^| ``` ```ts twoslash import { PluginEventEnum } from '@nyx-discord/djs-core'; // @noErrors PluginEventEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { PluginEventEnum } from '@nyx-discord/http'; // @noErrors PluginEventEnum. // ^| ``` ## Usage [#usage] ### Subscriber creation [#subscriber-creation] Create a subscriber that will listen to a given event, use the `PluginEventArgs` type for the arguments map. Check the [Event Subscribers](../events/subscribers) page for more information. ### Subscription [#subscription] Subscribe to the event using the `PluginEventArgs`'s `subscribe()` method. ```ts twoslash // ---cut-start--- import { EventSubscriber, PluginEventArgs } from '@nyx-discord/djs'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- await bot.getPluginManager().subscribe(subscriber); ``` ```ts twoslash // ---cut-start--- import { EventSubscriber, PluginEventArgs } from '@nyx-discord/djs-core'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- await bot.getPluginManager().subscribe(subscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventSubscriber, PluginEventArgs } from '@nyx-discord/http'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- await bot.getPluginManager().subscribe(subscriber); ``` # Plugins Overview (https://nyx-discord.github.io/nyx/guide/use/plugins) Plugins are objects that can be used to pack functionality, such as commands, events and schedules. ## Usage [#usage] ### Plugin creation [#plugin-creation] Create a class that implements NyxPlugin} decorated={false}/>. ```ts twoslash import { NyxPlugin, NyxBot } from '@nyx-discord/djs'; class MyPlugin implements NyxPlugin { public static readonly Id = Symbol('my-plugin'); public async onRegister(bot: NyxBot) { bot.getLogger().log('My plugin has been registered!'); } public async onUnregister(bot: NyxBot) { bot.getLogger().log('My plugin has been unregistered!'); } public getData() { return { name: 'my-plugin', version: '1.0.0', description: 'My plugin', // Optional git: 'https://github.com/...', } } public getId() { return MyPlugin.Id; } } ``` ```ts twoslash import { NyxPlugin, NyxBot } from '@nyx-discord/djs-core'; class MyPlugin implements NyxPlugin { public static readonly Id = Symbol('my-plugin'); public async onRegister(bot: NyxBot) { bot.getLogger().log('My plugin has been registered!'); } public async onUnregister(bot: NyxBot) { bot.getLogger().log('My plugin has been unregistered!'); } public getData() { return { name: 'my-plugin', version: '1.0.0', description: 'My plugin', // Optional git: 'https://github.com/...', } } public getId() { return MyPlugin.Id; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxPlugin, NyxBot } from '@nyx-discord/http'; class MyPlugin implements NyxPlugin { public static readonly Id = Symbol('my-plugin'); public async onRegister(bot: NyxBot) { bot.getLogger().log('My plugin has been registered!'); } public async onUnregister(bot: NyxBot) { bot.getLogger().log('My plugin has been unregistered!'); } public getData() { return { name: 'my-plugin', version: '1.0.0', description: 'My plugin', // Optional git: 'https://github.com/...', } } public getId() { return MyPlugin.Id; } } ``` The `getData()` method is unused by the framework, but it provides information to the plugin's consumer. ### Registration [#registration] Register it to a bot's `PluginManager`: ```ts twoslash import { NyxBot, NyxPlugin } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const MyPlugin: new () => NyxPlugin; // ---cut--- await bot.getPluginManager().register(new MyPlugin()); ``` ```ts twoslash import { NyxBot, NyxPlugin } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const MyPlugin: new () => NyxPlugin; // ---cut--- await bot.getPluginManager().register(new MyPlugin()); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { NyxBot, NyxPlugin } from '@nyx-discord/http'; declare const bot: NyxBot; declare const MyPlugin: new () => NyxPlugin; // ---cut--- await bot.getPluginManager().register(new MyPlugin()); ``` # Events (https://nyx-discord.github.io/nyx/guide/use/schedules/events) It's recommended to read the [Events Overview](../events/index) and [Event Subscribers](../events/subscribers) pages first. The `ScheduleManager` has an `EventBus` that allows you to listen to events related to schedules. This is useful for monitoring, logging, or any other custom logic you want to execute when a schedule is added or removed. ## Events [#events] The following events are available: ```ts twoslash import { ScheduleEventEnum } from '@nyx-discord/djs'; // @noErrors ScheduleEventEnum. // ^| ``` ```ts twoslash import { ScheduleEventEnum } from '@nyx-discord/djs-core'; // @noErrors ScheduleEventEnum. // ^| ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { ScheduleEventEnum } from '@nyx-discord/http'; // @noErrors ScheduleEventEnum. // ^| ``` ## Usage [#usage] ### Subscriber creation [#subscriber-creation] Create a subscriber that will listen to a given event, use the `ScheduleEventArgs` type for the arguments map. Check the [Event Subscribers](../events/subscribers) page for more information. ### Subscription [#subscription] Subscribe to the event using the `ScheduleManager`'s `subscribe()` method. ```ts twoslash // ---cut-start--- import { EventSubscriber, ScheduleEventArgs } from '@nyx-discord/djs'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs'; declare const bot: NyxBot; // ---cut-end--- await bot.getScheduleManager().subscribe(subscriber); ``` ```ts twoslash // ---cut-start--- import { EventSubscriber, ScheduleEventArgs } from '@nyx-discord/djs-core'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/djs-core'; declare const bot: NyxBot; // ---cut-end--- await bot.getScheduleManager().subscribe(subscriber); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut-start--- import { EventSubscriber, ScheduleEventArgs } from '@nyx-discord/http'; declare const subscriber: EventSubscriber; import type { NyxBot } from '@nyx-discord/http'; declare const bot: NyxBot; // ---cut-end--- await bot.getScheduleManager().subscribe(subscriber); ``` # Filters (https://nyx-discord.github.io/nyx/guide/use/schedules/filters) Filters restrict the execution of a given schedule. For example: - A [maintenance filter](#maintenance-filter) that checks if the system is in maintenance mode - A [production filter](#production-filter) that restricts the execution to the production environment. They receive all the information about the schedule and the execution metadata, and return a boolean indicating whether the schedule should be executed or not. For more general information about filters, you must first read the general [Filters](/use/other/filters) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `AbstractScheduleFilter` and implements the `check()` method. ```ts twoslash // ---cut--- import { AbstractScheduleFilter } from '@nyx-discord/djs'; import type { Schedule, Metadata } from '@nyx-discord/djs'; class MyFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Do some checks return true; // or false if the schedule should not be executed } } ``` ```ts twoslash // ---cut--- import { AbstractScheduleFilter } from '@nyx-discord/djs-core'; import type { Schedule, Metadata } from '@nyx-discord/djs-core'; class MyFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Do some checks return true; // or false if the schedule should not be executed } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut--- import { AbstractScheduleFilter } from '@nyx-discord/http'; import type { Schedule, Metadata } from '@nyx-discord/http'; class MyFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Do some checks return true; // or false if the schedule should not be executed } } ``` - Create a function that returns a boolean or a Promise that resolves to a boolean. ```ts twoslash // ---cut--- import { type ScheduleFilterResolvable } from '@nyx-discord/djs'; const myFilter: ScheduleFilterResolvable = async (schedule, meta) => { // Do some checks return true; // or false if the schedule should not be executed }; ``` ```ts twoslash // ---cut--- import { type ScheduleFilterResolvable } from '@nyx-discord/djs-core'; const myFilter: ScheduleFilterResolvable = async (schedule, meta) => { // Do some checks return true; // or false if the schedule should not be executed }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash // ---cut--- import { type ScheduleFilterResolvable } from '@nyx-discord/http'; const myFilter: ScheduleFilterResolvable = async (schedule, meta) => { // Do some checks return true; // or false if the schedule should not be executed }; ``` ### Filter usage [#filter-usage] Override the `filter` property in your schedule: - If you created a class, instantiate it: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; // ---cut-start--- import { AbstractScheduleFilter } from '@nyx-discord/djs'; // @ts-expect-error Incomplete example class MyFilter extends AbstractScheduleFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = new MyFilter(); } ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; // ---cut-start--- import { AbstractScheduleFilter } from '@nyx-discord/djs-core'; // @ts-expect-error Incomplete example class MyFilter extends AbstractScheduleFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = new MyFilter(); } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; // ---cut-start--- import { AbstractScheduleFilter } from '@nyx-discord/http'; // @ts-expect-error Incomplete example class MyFilter extends AbstractScheduleFilter {} // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = new MyFilter(); } ``` - If you created a function, assign it directly: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; // ---cut-start--- import { type ScheduleFilterResolvable } from '@nyx-discord/djs'; declare const myFilter: ScheduleFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = myFilter; } ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; // ---cut-start--- import { type ScheduleFilterResolvable } from '@nyx-discord/djs-core'; declare const myFilter: ScheduleFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = myFilter; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; // ---cut-start--- import { type ScheduleFilterResolvable } from '@nyx-discord/http'; declare const myFilter: ScheduleFilterResolvable; // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = myFilter; } ``` Or use a simple arrow function directly: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = () => { // Do some checks return true; }; } ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = () => { // Do some checks return true; }; } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly filter = () => { // Do some checks return true; }; } ``` ## Examples [#examples] ### Maintenance Filter [#maintenance-filter] A filter that checks if the system is in maintenance mode, and prevents the schedule from running if it is. ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/djs'; import type { Schedule, Metadata } from '@nyx-discord/djs'; class MaintenanceFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Check if the system is in maintenance mode, e.g. from an env variable or database return process.env.MAINTENANCE_MODE !== 'true'; } } ``` ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/djs-core'; import type { Schedule, Metadata } from '@nyx-discord/djs-core'; class MaintenanceFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Check if the system is in maintenance mode, e.g. from an env variable or database return process.env.MAINTENANCE_MODE !== 'true'; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/http'; import type { Schedule, Metadata } from '@nyx-discord/http'; class MaintenanceFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { // Check if the system is in maintenance mode, e.g. from an env variable or database return process.env.MAINTENANCE_MODE !== 'true'; } } ``` ### Production Filter [#production-filter] A filter that restricts the execution to the production environment. ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/djs'; import type { Schedule, Metadata } from '@nyx-discord/djs'; class ProductionFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { return process.env.NODE_ENV === 'production'; } } ``` ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/djs-core'; import type { Schedule, Metadata } from '@nyx-discord/djs-core'; class ProductionFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { return process.env.NODE_ENV === 'production'; } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractScheduleFilter } from '@nyx-discord/http'; import type { Schedule, Metadata } from '@nyx-discord/http'; class ProductionFilter extends AbstractScheduleFilter { public async check(schedule: Schedule, meta: Metadata): Promise { return process.env.NODE_ENV === 'production'; } } ``` # Schedules Overview (https://nyx-discord.github.io/nyx/guide/use/schedules) `Schedules` are objects that are ticked some time in the future, and can be used as a feature complete way of scheduling events in your bot, apart from Node's `setInterval()` API. In essence, a `Schedule` object contains its ticking logic and its interval of when it wishes to be executed, which can be in [cron](https://crontab.guru/) format, in an amount of ms (`number`), or as a `Date`. ## Quick example [#quick-example] Let's create a schedule that updates the activity with the member count every half hour: ```ts twoslash import { type DjsBot } from '@nyx-discord/djs'; declare const bot: DjsBot; // ---cut--- import { AbstractSchedule, TypedFields, type Metadata } from '@nyx-discord/djs'; class MemberCountSchedule extends AbstractSchedule { protected readonly interval = '*/30 * * * *'; public async tick(meta: Metadata) { // the discord.js Client of the bot that ticked this schedule const client = TypedFields.getClient(meta); if (!client.user) return; const memberCount = client.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0); await client.user.setActivity(`Members: ${memberCount}`); } } await bot.getScheduleManager().addSchedule(new MemberCountSchedule()); ``` ```ts twoslash import { type Bot as CoreBot } from '@nyx-discord/djs-core'; declare const bot: CoreBot; // ---cut--- import { AbstractSchedule, TypedFields, type Metadata } from '@nyx-discord/djs-core'; import { ActivityType, PresenceUpdateStatus } from '@discordjs/core'; class MemberCountSchedule extends AbstractSchedule { protected readonly interval = '*/30 * * * *'; public async tick(meta: Metadata) { // the gateway Client of the bot that ticked this schedule, which presences need const client = TypedFields.getClient(meta); const api = client.api; // Ideally you should cache and update these, but it's a simple example const guilds = await api.users.getGuilds({ with_counts: true }); const memberCount = guilds.reduce((acc, guild) => acc + (guild.approximate_member_count ?? 0), 0); await client.updatePresence( 0, // Shard ID { since: null, activities: [{ name: `Members: ${memberCount}`, type: ActivityType.Playing }], status: PresenceUpdateStatus.Online, afk: false, }, ); } } await bot.getScheduleManager().addSchedule(new MemberCountSchedule()); ``` Presences are set through the gateway connection, so HTTP bots can't set them. Schedules themselves work the same as with `@discordjs/core`, as long as the process stays alive. Given it uses the provided metadata, it'll work even if the same instance is used across multiple bots. ## Schedule Job [#schedule-job] When a schedule is added, a job will be created for it, which is responsible for notifying the framework when it is time to run it. It's a wrapper over a more "lower-level" component that will actually do the ticking, like a cron job, a timer, etc. How the job is created is entirely customizable. By default, cron strings and `Date`s use the [croner npm package](https://www.npmjs.com/package/croner), and millisecond intervals use a timer with millisecond precision. There are multiple ways to get it, but given a schedule itself does not depend on a bot, you'll always need the bot: ```ts twoslash import type { NyxBot, Schedule } from '@nyx-discord/djs'; declare const bot: NyxBot; declare const schedule: Schedule; // ---cut--- const fromScheduler = bot.getScheduleManager().getScheduler().getJobForSchedule(schedule); const fromSchedule = schedule.getJob(bot); const whenBeingAdded = await bot.getScheduleManager().addSchedule(schedule); ``` ```ts twoslash import type { NyxBot, Schedule } from '@nyx-discord/djs-core'; declare const bot: NyxBot; declare const schedule: Schedule; // ---cut--- const fromScheduler = bot.getScheduleManager().getScheduler().getJobForSchedule(schedule); const fromSchedule = schedule.getJob(bot); const whenBeingAdded = await bot.getScheduleManager().addSchedule(schedule); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { NyxBot, Schedule } from '@nyx-discord/http'; declare const bot: NyxBot; declare const schedule: Schedule; // ---cut--- const fromScheduler = bot.getScheduleManager().getScheduler().getJobForSchedule(schedule); const fromSchedule = schedule.getJob(bot); const whenBeingAdded = await bot.getScheduleManager().addSchedule(schedule); ``` It's the entry point for interacting with the schedule's ticking logic, and can be used to pause or resume it externally. ```ts twoslash import type { UndestroyableScheduleJobAdapter } from '@nyx-discord/djs'; declare const job: UndestroyableScheduleJobAdapter; // ---cut--- await job.pause(); await job.resume(); // A croner `Cron` for cron strings and Dates, or the current timeout for ms intervals // Depending on this is fragile and not intended, but it doesn't change for the same major version const rawTicker = job.getRaw(); ``` ```ts twoslash import type { UndestroyableScheduleJobAdapter } from '@nyx-discord/djs-core'; declare const job: UndestroyableScheduleJobAdapter; // ---cut--- await job.pause(); await job.resume(); // A croner `Cron` for cron strings and Dates, or the current timeout for ms intervals // Depending on this is fragile and not intended, but it doesn't change for the same major version const rawTicker = job.getRaw(); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { UndestroyableScheduleJobAdapter } from '@nyx-discord/http'; declare const job: UndestroyableScheduleJobAdapter; // ---cut--- await job.pause(); await job.resume(); // A croner `Cron` for cron strings and Dates, or the current timeout for ms intervals // Depending on this is fragile and not intended, but it doesn't change for the same major version const rawTicker = job.getRaw(); ``` ## Metadata [#metadata] When extending nyx with plugins, you may want to specify extra data for them. You can do so with the `Metadata` object, saved on the schedule. While schedules internally save a `Metadata`, the return type of `#getMeta()` is a `ReadonlyMetadata`, meaning that external objects can read the object, but not modify it. ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly meta = { someKey: 'someValue', }; } const schedule = new MySchedule(); const meta = schedule.getMeta(); const value = meta['someKey']; // 'someValue' ``` ```ts twoslash import { AbstractSchedule } from '@nyx-discord/djs-core'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly meta = { someKey: 'someValue', }; } const schedule = new MySchedule(); const meta = schedule.getMeta(); const value = meta['someKey']; // 'someValue' ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractSchedule } from '@nyx-discord/http'; // ---cut-start--- // @ts-expect-error Incomplete example // ---cut-end--- class MySchedule extends AbstractSchedule { protected override readonly meta = { someKey: 'someValue', }; } const schedule = new MySchedule(); const meta = schedule.getMeta(); const value = meta['someKey']; // 'someValue' ``` For a more type-safe approach, you can use `TypedFields`. Check the [Metadata](/use/other/meta) page for more information. # Middlewares (https://nyx-discord.github.io/nyx/guide/use/schedules/middlewares) Middlewares are objects or callbacks that run before any schedule is executed. They can do some pre-processing logic and store it in the metadata, or even prevent the subscriber from being executed. For general information about middlewares, you must first read the general [Middlewares](/use/other/middlewares) guide. ## Usage [#usage] ### Creation [#creation] Either: - Create a class that extends `AbstractScheduleMiddleware` and implements the `check()` method. ```ts twoslash import { AbstractScheduleMiddleware } from '@nyx-discord/djs'; import type { Schedule, Metadata, MiddlewareResponse } from '@nyx-discord/djs'; class MyMiddleware extends AbstractScheduleMiddleware { public async check( schedule: Schedule, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` ```ts twoslash import { AbstractScheduleMiddleware } from '@nyx-discord/djs-core'; import type { Schedule, Metadata, MiddlewareResponse } from '@nyx-discord/djs-core'; class MyMiddleware extends AbstractScheduleMiddleware { public async check( schedule: Schedule, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { AbstractScheduleMiddleware } from '@nyx-discord/http'; import type { Schedule, Metadata, MiddlewareResponse } from '@nyx-discord/http'; class MyMiddleware extends AbstractScheduleMiddleware { public async check( schedule: Schedule, meta: Metadata ): Promise { // Do some pre-processing logic return this.true(); } } ``` - Create a function that returns a `MiddlewareResponse`. ```ts twoslash import { type ScheduleMiddlewareResolvable } from '@nyx-discord/djs'; const myCallbackMiddleware: ScheduleMiddlewareResolvable = async (schedule, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ```ts twoslash import { type ScheduleMiddlewareResolvable } from '@nyx-discord/djs-core'; const myCallbackMiddleware: ScheduleMiddlewareResolvable = async (schedule, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import { type ScheduleMiddlewareResolvable } from '@nyx-discord/http'; const myCallbackMiddleware: ScheduleMiddlewareResolvable = async (schedule, meta) => { // Do some pre-processing logic return { allowed: true, checkNext: true, }; }; ``` ### Registration [#registration] Register it to the executor's `MiddlewareList`: ```ts twoslash import type { AbstractScheduleMiddleware, ScheduleMiddlewareResolvable, NyxBot } from '@nyx-discord/djs'; declare const MyMiddleware: new () => AbstractScheduleMiddleware; declare const myCallbackMiddleware: ScheduleMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getScheduleManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` ```ts twoslash import type { AbstractScheduleMiddleware, ScheduleMiddlewareResolvable, NyxBot } from '@nyx-discord/djs-core'; declare const MyMiddleware: new () => AbstractScheduleMiddleware; declare const myCallbackMiddleware: ScheduleMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getScheduleManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ``` Same as `@discordjs/core`, importing from `@nyx-discord/http`: ```ts twoslash import type { AbstractScheduleMiddleware, ScheduleMiddlewareResolvable, NyxBot } from '@nyx-discord/http'; declare const MyMiddleware: new () => AbstractScheduleMiddleware; declare const myCallbackMiddleware: ScheduleMiddlewareResolvable; declare const bot: NyxBot; // ---cut--- bot.getScheduleManager().getExecutor().getMiddleware().add(new MyMiddleware(), myCallbackMiddleware); ```