### Install CommandKit Development Version Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Use this command to install the latest development build of `create-commandkit`. Be aware that development versions may contain bugs. ```sh npx create-commandkit@dev ``` -------------------------------- ### CommandKit Main Application Entry Point (`src/app.ts`) Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Example content of the `src/app.ts` file, which serves as the main entry point for a CommandKit application. It demonstrates how to initialize a `discord.js` client and export it, noting that CommandKit handles `client.login()` automatically. ```ts import { Client } from 'discord.js'; const client = new Client({ intents: [ /* add stuff */ ], }); // setting up the token manually client.token = process.env.MY_BOT_TOKEN; export default client; ``` -------------------------------- ### Initialize New CommandKit Project (Latest Stable) Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/02-create-commandkit.mdx Run this command to start a new CommandKit application using the latest stable version of the `create-commandkit` utility. This will launch an interactive command-line interface in the current directory to guide you through project configuration. ```bash npm create commandkit@latest ``` -------------------------------- ### Run CommandKit Application in Production Mode Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Start the bot in production mode using `npx commandkit start` to load environment variables from `.env`, or manually execute the compiled JavaScript file. This ensures the bot runs efficiently in a deployed environment. ```sh npx commandkit start ``` ```sh node dist/index.js ``` -------------------------------- ### Generating New CommandKit Commands and Events Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/05-using-commandkit-cli.mdx Use the `commandkit create` command to quickly scaffold new files for your bot. Examples show how to generate a new `ping` command and a `ready` event handler, streamlining project setup. ```sh # Create a new command npx commandkit create command ping # Create a new event npx commandkit create event ready ``` -------------------------------- ### Initialize CommandKit Project with CLI Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Run the `create-commandkit` CLI utility to quickly set up a new CommandKit project. This command initiates an interactive setup process in the current directory. ```sh npx create-commandkit@latest ``` -------------------------------- ### Basic CommandKit Configuration Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/04-commandkit-config.mdx A minimal configuration to get started with CommandKit CLI, defining an empty configuration object using `defineConfig`. ```ts import { defineConfig } from 'commandkit'; export default defineConfig({}); ``` -------------------------------- ### Building and Starting CommandKit for Production Deployment Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/05-using-commandkit-cli.mdx These commands outline the standard workflow for deploying a CommandKit bot to production: first, `build` creates an optimized production bundle, and then `start` runs the bot using that compiled output. ```sh # Build and start in production npx commandkit build npx commandkit start ``` -------------------------------- ### Implement Chat and Message Commands Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Add commands by creating files (e.g., `ping.ts`) in `src/app/commands`. This example demonstrates a simple ping/pong command that registers as both a chat input (slash) and a message (legacy) command, replying 'Pong!' to user input. ```ts import type { ChatInputCommand, CommandData, MessageCommand } from 'commandkit'; export const command: CommandData = { name: 'ping', description: 'Pong!', }; export const chatInput: ChatInputCommand = async ({ interaction }) => { await interaction.reply('Pong!'); }; export const message: MessageCommand = async ({ message }) => { await message.reply('Pong!'); }; ``` -------------------------------- ### Install CommandKit Redis Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/01-redis.mdx Instructions for installing the `@commandkit/redis` package using different Node.js package managers. ```bash npm install @commandkit/redis ``` ```bash yarn add @commandkit/redis ``` ```bash pnpm add @commandkit/redis ``` -------------------------------- ### Initialize Discord Bot Project with create-commandkit CLI Source: https://github.com/underctrl-io/commandkit/blob/main/packages/create-commandkit/README.md This command runs the `create-commandkit` CLI utility to interactively set up a new Discord bot project. It fetches the latest version from npm, providing an easy way to get started with CommandKit-powered Discord bots. ```sh npx create-commandkit@latest ``` -------------------------------- ### Comprehensive CommandKit Configuration Example Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/04-commandkit-config.mdx A complete example demonstrating a comprehensive `commandkit.config.ts` file. It integrates various options including plugins, rolldown plugins, compiler settings, build output directory, environment variables, and typed commands/locales. ```ts import { defineConfig } from 'commandkit'; import { somePlugin } from '@commandkit/some-plugin'; import { someRolldownPlugin } from 'some-rolldown-plugin'; export default defineConfig({ plugins: [somePlugin()], rolldownPlugins: [someRolldownPlugin()], compilerOptions: { macro: { development: true }, cache: { development: true } }, distDir: 'dist', env: { NODE_ENV: 'development' }, typedCommands: true, typedLocales: true }); ``` -------------------------------- ### Create a Message Context Menu Command in CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx This example shows how to implement a context menu command named 'content' that operates on messages. When triggered, it replies with the content of the target message. It also includes options for developer-only access and specific user/bot permissions, and is provided in CommonJS, ESM, and TypeScript. ```js const { ApplicationCommandType } = require("discord.js"); module.exports = { data: { name: 'content', type: ApplicationCommandType.Message, }, run: ({ interaction, client, handler }) => { interaction.reply(`The message is: ${interaction.targetMessage.content}`); }, options: { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, }, }; ``` ```js import { ApplicationCommandType } from "discord.js"; export const data = { name: 'content', type: ApplicationCommandType.Message, } export function run({ interaction, client, handler }) { interaction.reply(`The message is: ${interaction.targetMessage.content}`); } export const options = { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, } ``` ```ts import { type CommandData, type ContextMenuCommandProps, type CommandOptions } from "commandkit"; import { ApplicationCommandType } from "discord.js"; export const data: CommandData = { name: 'content', type: ApplicationCommandType.Message, } export function run({ interaction, client, handler }: ContextMenuCommandProps) { interaction.reply(`The message is: ${interaction.targetMessage.content}`); } export const options: CommandOptions = { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, } ``` -------------------------------- ### CommandKit Constructor Options Reference Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/03-commandkit-setup.mdx Detailed documentation for the configuration options available when instantiating the CommandKit class. Each option specifies its type, purpose, and usage. ```APIDOC CommandKit Options: client: Type: Client (discord.js) Description: Your Discord.js client object. This is required to register and handle application commands and events. commandsPath (optional): Type: string Description: This is the path to your commands directory. It's used to fetch, register, and listen for application commands. eventsPath (optional): Type: string Description: This is the path to your events directory. It's used to fetch and set event listeners based on the folder names inside of it. validationsPath (optional): Type: string Description: This is the path to your validations directory. It's used to fetch and call validation functions before running application commands. devGuildIds (optional): Type: string[] Description: This is a list of development server IDs. It's used to restrict commands marked with `devOnly` to specific servers. If there is at least 1 guild ID provided, CommandKit will register any commands marked as `devOnly` inside the listed servers. devUserIds (optional): Type: string[] Description: This is a list of developer user IDs. It's used to restrict commands marked with `devOnly` to specific users. Trying to execute a command when this is set to at-least 1 user ID will call a built-in validation function everytime to validate that the user running the command belongs to the provided `devUserIds` array. ``` -------------------------------- ### Complete CommandKit Runtime Plugin Example Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/03-creating-a-runtime-plugin.mdx A comprehensive example demonstrating the creation of a CommandKit runtime plugin. This plugin implements `onAfterClientLogin` for bot login logging, `onBeforeInteraction` for command usage logging, `executeCommand` for tracking execution time and command usage, and `prepareCommand` for modifying command names in development. ```typescript import { RuntimePlugin } from 'commandkit'; import type { CommandKitPluginRuntime } from 'commandkit'; import { CommandKitEnvironment } from 'commandkit'; import { Interaction, Message } from 'discord.js'; import { CommandBuilderLike, PreparedAppCommandExecution } from 'commandkit'; export class LoggingPlugin extends RuntimePlugin { private commandUsage = new Map(); async onAfterClientLogin(ctx: CommandKitPluginRuntime): Promise { console.log(`Bot logged in as ${ctx.client.user?.tag}!`); console.log(`Serving ${ctx.client.guilds.cache.size} guilds`); } async onBeforeInteraction( ctx: CommandKitPluginRuntime, interaction: Interaction, ): Promise { if (interaction.isCommand()) { console.log( `Command "${interaction.commandName}" used by ${interaction.user.tag}`, ); } } async executeCommand( ctx: CommandKitPluginRuntime, env: CommandKitEnvironment, source: Interaction | Message, command: PreparedAppCommandExecution, execute: () => Promise, ): Promise { const startTime = Date.now(); // Let CommandKit handle normal execution await execute(); // Log execution time const execTime = Date.now() - startTime; console.log(`Command "${command.name}" executed in ${execTime}ms`); // Track usage this.commandUsage.set( command.name, (this.commandUsage.get(command.name) || 0) + 1, ); return true; // We've handled it } async prepareCommand( ctx: CommandKitPluginRuntime, command: CommandBuilderLike, ): Promise { // Add dev tag to command names in development environment if (process.env.NODE_ENV === 'development') { command.name = `dev_${command.name}`; } return command; } } ``` -------------------------------- ### Handle 'messageCreate' event in CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/05-event-file-setup.mdx This example illustrates how to implement a 'messageCreate' event listener to process incoming messages. It checks if a message's content is 'hey' and then replies with 'Hi!'. The `message` object and `client` instance are provided as parameters to the event function. ```js module.exports = (message, client) => { if (message.content === 'hey') { message.reply('Hi!'); } }; ``` ```js export default function (message, client, handler) { if (message.content === 'hey') { message.reply('Hi!'); } }; ``` ```ts import type { Message, Client } from 'discord.js'; import type { CommandKit } from 'commandkit'; export default function (message: Message, client: Client, handler: CommandKit) { if (message.content === 'hey') { message.reply('Hi!'); } }; ``` -------------------------------- ### Accessing Specific CommandKit Command Help Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/05-using-commandkit-cli.mdx To get detailed information, options, and usage examples for any particular CommandKit CLI command, use this command, replacing `` with the desired command name. ```sh npx commandkit help ``` -------------------------------- ### CommandKit CLI `start` Command Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/08-using-cli.mdx The `commandkit start` command initiates the bot in production mode. It requires `commandkit build` to be run beforehand and also loads environment variables from the `.env` file. ```APIDOC commandkit start Description: Starts your bot in production mode. Prerequisites: Must run 'commandkit build' first. Features: - Loads environment variables from .env file ``` -------------------------------- ### CommandKit Default Project Structure Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Overview of the standard directory and file structure generated by the `create-commandkit` CLI. It highlights the `src/app` directory for commands and events, and the main `src/app.ts` entry point. ```text . ├── src/ │ ├── app/ │ │ ├── commands/ │ │ │ └── ping.ts │ │ └── events/ │ │ └── ready/ │ │ └── log.ts │ └── app.ts ├── .env ├── .gitignore ├── commandkit.config.ts ├── package.json └── tsconfig.json ``` -------------------------------- ### Install @commandkit/redis package Source: https://github.com/underctrl-io/commandkit/blob/main/packages/redis/README.md Instructions to install the `@commandkit/redis` package using npm. ```sh npm install @commandkit/redis ``` -------------------------------- ### Install CommandKit Legacy Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/03-legacy.mdx Instructions to install the CommandKit Legacy plugin using various package managers like npm, yarn, and pnpm. ```bash npm install @commandkit/legacy ``` ```bash yarn add @commandkit/legacy ``` ```bash pnpm add @commandkit/legacy ``` -------------------------------- ### Install CommandKit Analytics Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/05-analytics.mdx Instructions for installing the CommandKit analytics plugin using different package managers. ```bash npm install @commandkit/analytics ``` ```bash yarn add @commandkit/analytics ``` ```bash pnpm add @commandkit/analytics ``` -------------------------------- ### Install CommandKit i18n Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/02-i18n.mdx Instructions for installing the @commandkit/i18n plugin using npm, yarn, or pnpm. ```bash npm install @commandkit/i18n ``` ```bash yarn add @commandkit/i18n ``` ```bash pnpm add @commandkit/i18n ``` -------------------------------- ### Install CommandKit Project Dependencies Source: https://github.com/underctrl-io/commandkit/blob/main/CONTRIBUTING.md Navigate into the cloned CommandKit directory and run this pnpm command from the root to install all project dependencies, leveraging pnpm workspaces for efficient management. ```bash cd commandkit pnpm install # Make sure to run this from the root directory ``` -------------------------------- ### Implement a /ping Slash Command in CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx This example demonstrates how to create a basic `/ping` slash command in CommandKit. It replies with 'Pong!' and the client's WebSocket ping. The command includes options for developer-only access and specific user/bot permissions, and is provided in CommonJS, ESM, and TypeScript. ```js module.exports = { data: { name: 'ping', description: 'Pong!', }, run: ({ interaction, client, handler }) => { interaction.reply(`:ping_pong: Pong! ${client.ws.ping}ms`); }, options: { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, }, }; ``` ```js export const data = { name: 'ping', description: 'Pong!', } export function run({ interaction, client, handler }) { interaction.reply(`:ping_pong: Pong! ${client.ws.ping}ms`); } export const options = { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, } ``` ```ts import type { CommandData, SlashCommandProps, CommandOptions } from 'commandkit'; export const data: CommandData = { name: 'ping', description: 'Pong!', } export function run({ interaction, client, handler }: SlashCommandProps) { interaction.reply(`:ping_pong: Pong! ${client.ws.ping}ms`); } export const options: CommandOptions = { devOnly: true, userPermissions: ['Administrator', 'AddReactions'], botPermissions: ['Administrator', 'AddReactions'], deleted: false, } ``` -------------------------------- ### Create New CommandKit Project Source: https://github.com/underctrl-io/commandkit/blob/main/packages/commandkit/README.md Use this command to scaffold a new CommandKit project. It will prompt you for project details and set up the basic structure. After creation, you can run `commandkit dev` to start the bot application. ```bash npm create commandkit@dev ``` -------------------------------- ### CommandKit CLI Usage and Available Commands Overview Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/05-using-commandkit-cli.mdx This output block details the general syntax for using the CommandKit CLI and lists its core commands (`dev`, `start`, `build`, `create`, `help`), along with their brief descriptions and options. ```sh Usage: commandkit [options] [command] Options: -h, --help display help for command Commands: dev [options] Start your bot in development mode. start [options] Start your bot in production mode after running the build command. build [options] Build your project for production usage. create [options] Create new commands, events, or locale files help [command] display help for command ``` -------------------------------- ### Implement Command Autocomplete with `autocomplete` Function Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx Demonstrates how to export an `autocomplete` function in a CommandKit command file. This function filters options for a `SlashCommandBuilder` string option based on user input, providing dynamic choices without requiring a separate `interactionCreate` event listener. Examples are provided for CommonJS, ESM, and TypeScript. ```js const pets = require('../data/pets.json'); module.exports = { data: new SlashCommandBuilder() .setName('pet') .setDescription('Find a pet from a list of pets.') .addStringOption((option) => option .setName('pet') .setDescription('The pet to check.') .setRequired(true) .setAutocomplete(true) ), run: ({ interaction, client, handler }) => { const targetPetId = interaction.options.getString('pet'); const targetPetObj = pets.find((pet) => pet.id === targetPetId); interaction.reply(`Your pet name is ${targetPetObj.name}.`); }, autocomplete: ({ interaction, client, handler }) => { const focusedPetOption = interaction.options.getFocused(true); const filteredChoices = pets.filter((pet) => pet.name.startsWith(focusedPetOption)); const results = filteredChoices.map((pet) => { return { name: `${pet.name} | ${pet.type}`, value: pet.id, }; }); interaction.respond(results.slice(0, 25)); } } ``` ```js import pets from '../data/pets.json'; export const data = new SlashCommandBuilder() .setName('pet') .setDescription('Find a pet from a list of pets.') .addStringOption((option) => option .setName('pet') .setDescription('The pet to check.') .setRequired(true) .setAutocomplete(true) ); export function run({ interaction, client, handler }) { const targetPetId = interaction.options.getString('pet'); const targetPetObj = pets.find((pet) => pet.id === targetPetId); interaction.reply(`Your pet name is ${targetPetObj.name}.`); } export function autocomplete({ interaction, client, handler }) { const focusedPetOption = interaction.options.getFocused(true); const filteredChoices = pets.filter((pet) => pet.name.startsWith(focusedPetOption)); const results = filteredChoices.map((pet) => { return { name: `${pet.name} | ${pet.type}`, value: pet.id, }; }); interaction.respond(results.slice(0, 25)); } ``` ```ts import type { CommandData, AutocompleteProps, CommandOptions } from 'commandkit'; import pets from '../data/pets.json'; export const data = new SlashCommandBuilder() .setName('pet') .setDescription('Find a pet from a list of pets.') .addStringOption((option) => option .setName('pet') .setDescription('The pet to check.') .setRequired(true) .setAutocomplete(true) ); export function run({ interaction, client, handler }: SlashCommandProps) { const targetPetId = interaction.options.getString('pet'); const targetPetObj = pets.find((pet) => pet.id === targetPetId); interaction.reply(`Your pet name is ${targetPetObj.name}.`); } export function autocomplete({ interaction, client, handler }: AutocompleteProps) { const focusedPetOption = interaction.options.getFocused(true); const filteredChoices = pets.filter((pet) => pet.name.startsWith(focusedPetOption)); const results = filteredChoices.map((pet) => { return { name: `${pet.name} | ${pet.type}`, value: pet.id, }; }); interaction.respond(results.slice(0, 25)); } ``` -------------------------------- ### Install development CommandKit via npm Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/01-installation.mdx This command installs the development version of CommandKit using the npm package manager. Be aware that this version is likely to contain bugs. ```bash npm install commandkit@dev ``` -------------------------------- ### Build CommandKit Application for Production Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Execute `npx commandkit build` to create a production-ready build of your bot. This command compiles your project into a `dist` folder, which contains the optimized files for deployment. The `dist` folder should be excluded from version control. ```sh npx commandkit build ``` -------------------------------- ### APIDOC: onBeforeClientLogin Lifecycle Hook Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/03-creating-a-runtime-plugin.mdx Documentation for the `onBeforeClientLogin` lifecycle hook, which is called right before the Discord client attempts to log in. It provides the runtime context and is useful for performing last-minute setup before connecting to Discord. ```APIDOC onBeforeClientLogin(ctx) Description: Called right before the Discord client attempts to log in. Parameters: ctx: The runtime context. Example use case: Perform last-minute setup before connecting to Discord. ``` ```typescript async onBeforeClientLogin(ctx: CommandKitPluginRuntime): Promise { console.log('Bot is about to connect to Discord...'); // Last minute preparations before login } ``` -------------------------------- ### Install stable CommandKit via npm Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/01-installation.mdx This command installs the latest stable version of CommandKit using the npm package manager. ```bash npm install commandkit ``` -------------------------------- ### Commandkit: options Property Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx The `options` property defines the registration and handling behavior for a command. It allows developers to configure how a command is registered and how it behaves during execution. ```APIDOC options (optional): Type: CommandOptions ``` -------------------------------- ### Set Up Discord.js Client Entrypoint Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Create `src/app.ts` as the application's entrypoint. This file must export your Discord.js client instance, which CommandKit will use to log in. Bot tokens should be stored as environment variables (DISCORD_TOKEN or TOKEN). ```ts import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds', 'GuildMembers'], }); client.token = '...'; // Optional: You can manually set your bot's token // must export the `client` here export default client; ``` -------------------------------- ### Install CommandKit Cache Package Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/04-caching/01-caching-in-commandkit.mdx First, install the `@commandkit/cache` package using npm. ```bash npm install @commandkit/cache ``` -------------------------------- ### Example: Setting up ButtonKit onClick Handler Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/api-reference/classes/ButtonKit.mdx Demonstrates how to create a ButtonKit instance, add it to a message, and set up an inline interaction collector using the `onClick` method to respond to button clicks. Also shows how to remove the handler. ```typescript const button = new ButtonKit() .setLabel('Click me') .setStyle(ButtonStyle.Primary) .setCustomId('click_me'); const row = new ActionRowBuilder().addComponents(button); const message = await channel.send({ content: 'Click the button', components: [row] }); button.onClick(async (interaction) => { await interaction.reply('You clicked me!'); }, { message }); // Remove onClick handler and destroy the interaction collector button.onClick(null); ``` -------------------------------- ### CommandKit Configuration: bulkRegister Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/03-commandkit-setup.mdx Changes how CommandKit loads application commands. When `true`, commands are loaded all at once on restart and when `reloadCommands()` is called, instead of one-by-one. ```APIDOC Parameter: bulkRegister Type: boolean Default: false Description: Used to change the behaviour of how CommandKit loads application commands. By default it's one-by-one while comparing changes. Setting this option to `true` will load application commands all at once on every restart, and when `reloadCommands()` is called. ``` -------------------------------- ### Start CommandKit Application Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKit.mdx Initiates the CommandKit application, connecting to the Discord gateway. It can use a provided token, environment variables (`TOKEN` or `DISCORD_TOKEN`), or skip login if `false` is passed. ```APIDOC CommandKit.start(token?): Promise token: string (Optional: false) Description: The application token to connect to the discord gateway. If not provided, it will use the `TOKEN` or `DISCORD_TOKEN` environment variable. If set to `false`, it will not login. ``` -------------------------------- ### Install CommandKit DevTools Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/04-devtools.mdx Instructions for installing the DevTools plugin using different package managers. This plugin is in early development and recommended for testing. ```bash npm install @commandkit/devtools@dev ``` ```bash yarn add @commandkit/devtools@dev ``` ```bash pnpm add @commandkit/devtools@dev ``` -------------------------------- ### Define CommandKit Configuration File Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Create `commandkit.config.ts` at the project root to configure CommandKit and its plugins. This file serves as the central configuration point for your CommandKit application. ```ts import { defineConfig } from 'commandkit'; export default defineConfig({}); ``` -------------------------------- ### API Reference: Command `run` Function Definition Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx Documents the `run` function, which is executed when a command is invoked. This function contains the primary logic for the command's response and accepts props typed as `SlashCommandProps` or `ContextMenuCommandProps`. ```APIDOC run: Type: void Props Type: SlashCommandProps | ContextMenuCommandProps Description: This function will be called when the command is executed. ``` -------------------------------- ### CommandKit CLI Help Output Structure Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/08-using-cli.mdx This output details the usage syntax, available global options, and a list of primary commands with their brief descriptions, guiding users on how to interact with the CommandKit CLI. ```sh Usage: commandkit [options] [command] Options: -h, --help display help for command Commands: dev [options] Start your bot in development mode. start [options] Start your bot in production mode after running the build command. build [options] Build your project for production usage. help [command] display help for command ``` -------------------------------- ### Configure CommandKit with Legacy Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/03-legacy.mdx Example demonstrating how to integrate and enable the Legacy plugin within your CommandKit application's configuration using `defineConfig`. ```js import { defineConfig } from 'commandkit'; import { legacy } from '@commandkit/legacy'; export default defineConfig({ plugins: [legacy()], }); ``` -------------------------------- ### Install CommandKit Analytics Package Source: https://github.com/underctrl-io/commandkit/blob/main/packages/analytics/README.md Installs the `@commandkit/analytics` package using npm, providing analytics capabilities for CommandKit applications. ```sh npm install @commandkit/analytics ``` -------------------------------- ### Example: Handling Modal Submission with ModalKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/ModalKit.mdx Demonstrates how to create a ModalKit instance, set its properties, add components, and define an onSubmit handler to respond to user submissions. ```ts const modal = new ModalKit() .setTitle('My Modal') .setCustomId('my-modal') .filter((interaction) => interaction.user.id === '1234567890') .onSubmit(async (interaction) => { await interaction.reply('You submitted the modal!'); }) .addComponents(actionRow1, actionRow2); ``` -------------------------------- ### Install CommandKit Analytics Package Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/10-analytics/03-umami.mdx Installs the `@commandkit/analytics` package using npm, which is required for integrating Umami analytics into your CommandKit project. ```sh npm install @commandkit/analytics ``` -------------------------------- ### Configure CommandKit with Analytics Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/05-analytics.mdx Example demonstrating how to integrate the analytics plugin, specifically Umami, into your CommandKit configuration using defineConfig. ```js import { defineConfig } from 'commandkit'; import { umami } from '@commandkit/analytics/umami'; export default defineConfig({ plugins: [umami({...})] }); ``` -------------------------------- ### Example Usage of MentionableSelectMenuKit with onSelect Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/MentionableSelectMenuKit.mdx This TypeScript example demonstrates how to create a `MentionableSelectMenuKit` instance, set its title and custom ID, apply a filter for interactions, and define an `onSelect` handler to respond when the select menu is submitted. It shows a typical setup for handling user interactions with a mentionable select menu. ```TypeScript const modal = new MentionableSelectMenuKit() .setTitle('My Modal') .setCustomId('my-modal') .filter((interaction) => interaction.Mentionable.id === '1234567890') .onSelect(async (interaction) => { await interaction.reply('You submitted the modal!'); }) .addComponents(actionRow1, actionRow2); ``` -------------------------------- ### APIDOC: onAfterClientLogin Lifecycle Hook Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/03-creating-a-runtime-plugin.mdx Documentation for the `onAfterClientLogin` lifecycle hook, which is called after the Discord client has successfully logged in. It provides the runtime context and is useful for starting additional services or initializing post-login resources. ```APIDOC onAfterClientLogin(ctx) Description: Called after the Discord client has successfully logged in. Parameters: ctx: The runtime context. Example use case: Start additional services once the bot is online, log connection details. ``` ```typescript async onAfterClientLogin(ctx: CommandKitPluginRuntime): Promise { console.log(`Bot logged in as ${ctx.client.user?.tag}!`); // Start additional services, initialize post-login resources } ``` -------------------------------- ### Configure CommandKit with Custom Analytics Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/10-analytics/04-custom-providers.mdx Integrate your custom analytics plugin into your CommandKit application by adding it to the `plugins` array in your `defineConfig` setup. This example shows how to pass configuration options to the plugin. ```TypeScript import { AnonymousAnalyticsPlugin } from './anonymous-analytics-plugin'; export default defineConfig({ plugins: [ new AnonymousAnalyticsPlugin({ analyticsOptions: { apiKey: 'YOUR_API_KEY', options: { // Your analytics service options }, }, }), ], }); ``` -------------------------------- ### Basic CommandKit i18n Plugin Setup Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/02-i18n.mdx Demonstrates how to add the i18n plugin to your CommandKit configuration using defineConfig. ```ts import { defineConfig } from 'commandkit'; import { i18n } from '@commandkit/i18n'; export default defineConfig({ plugins: [i18n()], }); ``` -------------------------------- ### Example Translation File for Ping Command in English Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/07-file-system-conventions/06-locales-directory.mdx This JSON snippet provides a more complete example of a translation file for the `ping` command in English. It includes both the `$command` object for command metadata localization and a custom translation key (`success`) that can be accessed and used within the command's logic. ```json { "$command": { "name": "ping", "description": "Ping command", "options": [ { "name": "verbose", "description": "Show verbose output" } ] }, "success": "Pong! {{ping}}ms" } ``` -------------------------------- ### Create Channel Select Menu with CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/03-jsx/v1/03-select-menu.mdx Illustrates how to implement a Channel Select Menu in CommandKit, enabling users to select a channel from the server. The example shows how to capture and respond to the selected channel. ```tsx import { ChannelSelectMenu, OnChannelSelectMenuKitSubmit } from 'commandkit'; const handleSelect: OnChannelSelectMenuKitSubmit = async ( interaction, context, ) => { const channel = interaction.values[0]; await interaction.reply(`Selected channel: ${channel}`); context.dispose(); }; const select = ; ``` -------------------------------- ### Example: Inspecting Event Listeners in Node.js Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKit.mdx Demonstrates how to use `server.listeners()` to retrieve and inspect the array of functions listening for a specific event, such as 'connection', in a Node.js environment. ```JavaScript server.on('connection', (stream) => { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``` -------------------------------- ### Implement Cooldown Validation for CommandKit Commands Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/06-validation-file-setup.mdx This validation function checks if a user is on cooldown for a specific command. If the user is on cooldown, it sends an ephemeral reply to the user and returns `true` to prevent the command from executing. This example demonstrates using a `cooldowns-cache` and Discord.js `MessageFlags`. ```js const cooldowns = require('../cooldowns-cache'); const { MessageFlags } = require('discord.js'); module.exports = ({ interaction, commandObj, handler }) => { if (cooldowns.has(`${interaction.user.id}-${commandObj.data.name}`)) { interaction.reply({ content: "You're on cooldown, please wait some time before running this command again.", flags: MessageFlags.Ephemeral, }); return true; // This is important } }; ``` ```js import cooldowns from '../cooldowns-cache'; import { MessageFlags } from 'discord.js'; export default function ({ interaction, commandObj, handler }) { if (cooldowns.has(`${interaction.user.id}-${commandObj.data.name}`)) { interaction.reply({ content: "You're on cooldown, please wait some time before running this command again.", flags: MessageFlags.Ephemeral, }); return true; // This is important } }; ``` ```ts import type { ValidationProps } from 'commandkit'; import cooldowns from '../cooldowns-cache'; import { MessageFlags } from 'discord.js'; export default function ({ interaction, commandObj, handler }: ValidationProps) { if (cooldowns.has(`${interaction.user.id}-${commandObj.data.name}`)) { interaction.reply({ content: "You're on cooldown, please wait some time before running this command again.", flags: MessageFlags.Ephemeral, }); return true; // This is important } }; ``` -------------------------------- ### Integrate a Custom Runtime Plugin with CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/03-creating-a-runtime-plugin.mdx This example shows how to integrate a custom runtime plugin, such as `MyRuntimePlugin`, into your CommandKit application by adding an instance of the plugin to the `plugins` array during CommandKit initialization. ```typescript import { CommandKit } from 'commandkit'; import { MyRuntimePlugin } from './plugins/MyRuntimePlugin'; const commandkit = new CommandKit({ // ... other options plugins: [new MyRuntimePlugin()], }); ``` -------------------------------- ### Create User Select Menu with CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/03-jsx/v1/03-select-menu.mdx Provides an example of creating a User Select Menu in CommandKit, which enables users to select a user from the server. It includes the event handler for user selection. ```tsx import { UserSelectMenu, OnUserSelectMenuKitSubmit } from 'commandkit'; const handleSelect: OnUserSelectMenuKitSubmit = async ( interaction, context, ) => { const user = interaction.values[0]; await interaction.reply(`Selected user: ${user}`); context.dispose(); }; const select = ; ``` -------------------------------- ### Process 'messageUpdate' event with multiple parameters Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/05-event-file-setup.mdx This snippet demonstrates handling Discord.js events that return multiple parameters, using the 'messageUpdate' event as an example. It logs the original and updated content of an edited message. The `oldMessage`, `newMessage`, and `client` objects are passed as parameters, with the client always being the last one. ```js module.exports = (oldMessage, newMessage, client) => { console.log(`Message edited from ${oldMessage.content} to ${newMessage.content}`); }; ``` ```js export default function (oldMessage, newMessage, client) { console.log(`Message edited from ${oldMessage.content} to ${newMessage.content}`); }; ``` ```ts import type { Message, PartialMessage } from 'discord.js'; import type { CommandKit } from 'commandkit'; export default function (oldMessage: Message | PartialMessage, newMessage: Message | PartialMessage, client: Client, handler: CommandKit) { console.log(`Message edited from ${oldMessage.content} to ${newMessage.content}`); }; ``` -------------------------------- ### Example Usage of onSelect Method Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/UserSelectMenuKit.mdx Demonstrates how to use the `onSelect` method of `UserSelectMenuKit` to handle user interactions with a select menu, including setting a filter and defining an asynchronous handler. ```typescript const modal = new UserSelectMenuKit() .setTitle('My Modal') .setCustomId('my-modal') .filter((interaction) => interaction.user.id === '1234567890') .onSelect(async (interaction) => { await interaction.reply('You submitted the modal!'); }) .addComponents(actionRow1, actionRow2); ``` -------------------------------- ### Initialize CommandKit Instance Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/api-reference/classes/CommandKit.mdx Instantiates a new CommandKit object with the specified configuration options. ```APIDOC CommandKit Constructor: new CommandKit(options: CommandKitOptions) options: CommandKitOptions - The default CommandKit configuration. ``` -------------------------------- ### Set up 'ready' event listener in CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/05-event-file-setup.mdx This snippet demonstrates how to set up a function that is called when the 'ready' event is triggered. It logs the bot's username to the console, indicating that the bot is online and ready to operate. The parameters `c` (client object), `client` (Discord.js client), and `handler` (CommandKit instance) are passed to the event function. ```js module.exports = (c, client, handler) => { console.log(`${c.user.username} is ready!`); }; ``` ```js export default function (c, client, handler) { console.log(`${c.user.username} is ready!`); }; ``` ```ts import type { Client } from 'discord.js'; import type { CommandKit } from 'commandkit'; export default function (c: Client, client: Client, handler: CommandKit) { console.log(`${c.user.username} is ready!`); }; ``` -------------------------------- ### JavaScript EventEmitter Emit Method Example Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKit.mdx Demonstrates how to use the `emit` method of Node.js `EventEmitter` to synchronously call registered listeners. It shows how to define multiple listeners and pass arguments to them. ```JavaScript import { EventEmitter } from 'node:events'; const myEmitter = new EventEmitter(); // First listener myEmitter.on('event', function firstListener() { console.log('Helloooo! first listener'); }); // Second listener myEmitter.on('event', function secondListener(arg1, arg2) { console.log(`event with parameters ${arg1}, ${arg2} in second listener`); }); // Third listener myEmitter.on('event', function thirdListener(...args) { const parameters = args.join(', '); console.log(`event with parameters ${parameters} in third listener`); }); console.log(myEmitter.listeners('event')); myEmitter.emit('event', 1, 2, 3, 4, 5); // Prints: // [ // [Function: firstListener], // [Function: secondListener], // [Function: thirdListener] // ] // Helloooo! first listener // event with parameters 1, 2 in second listener // event with parameters 1, 2, 3, 4, 5 in third listener ``` -------------------------------- ### Sample CommandKit CLI Configuration File Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/09-commandkit-config.mdx This example demonstrates a basic `commandkit.config.mjs` file, showing how to define the source directory (`src`) and the main entry point (`main`) for your CommandKit project. This configuration is essential for the CLI to locate and process your bot's code. ```js import { defineConfig } from 'commandkit'; export default defineConfig({ src: 'src', // The source directory of your project. main: 'index.mjs', // The JavaScript entry point of your project. }); ``` -------------------------------- ### Displaying All CommandKit CLI Commands Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/05-using-commandkit-cli.mdx Run this command to view a comprehensive list of all available CommandKit CLI commands and global options, providing a quick reference for its functionalities. ```sh npx commandkit --help ``` -------------------------------- ### Install @commandkit/i18n Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/packages/i18n/README.md This snippet shows how to install the `@commandkit/i18n` plugin using npm, which is required to integrate i18next with CommandKit. ```Shell $ npm i @commandkit/i18n ``` -------------------------------- ### Run Local Development Server for Documentation Source: https://github.com/underctrl-io/commandkit/blob/main/CONTRIBUTING.md If you've made changes to the project documentation, navigate to 'apps/website' and run `pnpm dev` to spin up a local development server to preview your updates. ```bash pnpm dev ``` -------------------------------- ### Commandkit: autocomplete Function Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/04-command-file-setup.mdx The `autocomplete` function is invoked when an autocomplete interaction event occurs for any option configured as autocomplete within a command's `data` object. It is designed to handle dynamic suggestions for command inputs. ```APIDOC autocomplete: Type: void Props Type: AutocompleteProps ``` -------------------------------- ### ButtonKit Instance Methods API Reference Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/api-reference/classes/ButtonKit.mdx Detailed API documentation for all instance methods of the ButtonKit class, covering interaction handling, customization, and serialization. ```APIDOC ButtonKit Methods: public dispose(): ButtonKit public onClick(handler, data?): this handler: CommandKitButtonBuilderInteractionCollectorDispatch (Optional: ❌) data: CommandKitButtonBuilderInteractionCollectorDispatchContextData (Optional: ✅) Description: Sets up an inline interaction collector for this button. This collector by default allows as many interactions as possible if it is actively used. If unused, this expires after 24 hours or custom time if specified. public onEnd(handler): this handler: CommandKitButtonBuilderOnEnd (Optional: ❌) public setCustomId(customId): this customId: string (Optional: ❌) Description: The custom id to use public setDisabled(disabled?): this disabled: boolean (Optional: ✅) Description: Whether to disable this button public setEmoji(emoji): this emoji: ComponentEmojiResolvable (Optional: ❌) Description: The emoji to use public setLabel(label): this label: string (Optional: ❌) Description: The label to use public setSKUId(skuId): this skuId: string (Optional: ❌) Description: The SKU id to use public setStyle(style): this style: ButtonStyle (Optional: ❌) Description: The style to use public setURL(url): this url: string (Optional: ❌) Description: The URL to use public toJSON(): APIButtonComponent Description: ComponentBuilder.toJSON ``` -------------------------------- ### Example Discord.js Event Directory Structure Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/07-file-system-conventions/05-events-directory.mdx Illustrates the recommended directory structure for defining Discord.js events within the `src/app/events` directory, showing how built-in events like `messageCreate` and `ready` are organized with their respective handler files. ```plaintext . └── src/ └── app/ └── events/ ├── messageCreate/ │ ├── give-xp.ts │ └── log.ts └── ready/ ├── log.ts └── initialize.ts ``` -------------------------------- ### Run CommandKit Application in Development Mode Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/03-setup-commandkit-manually.mdx Use `npx commandkit dev` to run your application in development mode. This command automatically reloads the bot upon code changes. A `.commandkit` folder is generated for compiled files and should be added to `.gitignore`. ```sh npx commandkit dev ``` -------------------------------- ### Install CommandKit Analytics Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/10-analytics/01-analytics-in-commandkit.mdx Installs the CommandKit analytics plugin using npm, adding it to your project's dependencies. ```sh npm install @commandkit/analytics ``` -------------------------------- ### Initialize CommandKit with Discord.js Client Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/03-commandkit-setup.mdx This code demonstrates how to initialize CommandKit in your Discord.js bot's entry file (e.g., `src/index.js` or `src/index.ts`). It sets up the Discord.js client with necessary intents and then configures CommandKit with paths for commands, events, and validations, along with optional development-specific IDs for guilds, users, and roles. The `skipBuiltInValidations` and `bulkRegister` options are also shown. ```javascript const { Client, GatewayIntentBits } = require('discord.js'); const { CommandKit } = require('commandkit'); const path = require('path'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, ], }); new CommandKit({ client, commandsPath: path.join(__dirname, 'commands'), eventsPath: path.join(__dirname, 'events'), validationsPath: path.join(__dirname, 'validations'), devGuildIds: ['DEV_SERVER_ID_1', 'DEV_SERVER_ID_2'], devUserIds: ['DEV_USER_ID_1', 'DEV_USER_ID_2'], devRoleIds: ['DEV_ROLE_ID_1', 'DEV_ROLE_ID_2'], skipBuiltInValidations: true, bulkRegister: true, }); client.login('YOUR_TOKEN_HERE'); ``` ```javascript import { Client, GatewayIntentBits } from 'discord.js'; import { CommandKit } from 'commandkit'; import { fileURLToPath } from 'url'; import path from 'path'; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ], }); const __dirname = path.dirname(fileURLToPath(import.meta.url)); new CommandKit({ client, commandsPath: path.join(__dirname, 'commands'), eventsPath: path.join(__dirname, 'events'), validationsPath: path.join(__dirname, 'validations'), devGuildIds: ['DEV_SERVER_ID_1', 'DEV_SERVER_ID_2'], devUserIds: ['DEV_USER_ID_1', 'DEV_USER_ID_2'], devRoleIds: ['DEV_ROLE_ID_1', 'DEV_ROLE_ID_2'], skipBuiltInValidations: true, bulkRegister: true, }); client.login('YOUR_TOKEN_HERE'); ``` ```typescript import { Client, GatewayIntentBits } from 'discord.js'; import { CommandKit } from 'commandkit'; import path from 'path'; const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ], }); new CommandKit({ client, commandsPath: path.join(__dirname, 'commands'), eventsPath: path.join(__dirname, 'events'), validationsPath: path.join(__dirname, 'validations'), devGuildIds: ['DEV_SERVER_ID_1', 'DEV_SERVER_ID_2'], devUserIds: ['DEV_USER_ID_1', 'DEV_USER_ID_2'], devRoleIds: ['DEV_ROLE_ID_1', 'DEV_ROLE_ID_2'], skipBuiltInValidations: true, bulkRegister: true, }); client.login('YOUR_TOKEN_HERE'); ``` -------------------------------- ### Install CommandKit Cache Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/official-plugins/00-cache.mdx Install the CommandKit cache plugin using npm, yarn, or pnpm package managers. ```bash npm install @commandkit/cache ``` ```bash yarn add @commandkit/cache ``` ```bash pnpm add @commandkit/cache ``` -------------------------------- ### Install CommandKit Devtools Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/packages/devtools/README.md This command installs the `@commandkit/devtools` package using npm, making it available for use in your CommandKit project. ```bash npm install @commandkit/devtools ``` -------------------------------- ### Install pnpm Globally Source: https://github.com/underctrl-io/commandkit/blob/main/CONTRIBUTING.md This command installs pnpm globally using npm, which is essential for managing dependencies within the CommandKit monorepo structure. ```bash npm install -g pnpm ``` -------------------------------- ### CompilerPluginRuntime Class API Reference Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CompilerPluginRuntime.mdx Comprehensive API documentation for the `CompilerPluginRuntime` class, including its constructor, public properties, and methods for plugin and template management. This class is central to handling compiler-related plugins. ```APIDOC CompilerPluginRuntime Class: Constructor: new CompilerPluginRuntime(plugins: Array) Properties: public name: any Methods: public destroy(): Promise public getPlugins(): Array public getTemplate(name: string): undefined | TemplateHandler public getTemplates(): Map public init(): Promise public isEmpty(): boolean public registerTemplate(name: string, handler: TemplateHandler): void public toJSON(): { name: string; transform: ( code: string, id: string ) => Promise<{ code: string; map: null | string; }>; } ``` -------------------------------- ### Install CommandKit Analytics Package Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/10-analytics/02-posthog.mdx This command installs the `@commandkit/analytics` package, which provides integration capabilities for analytics platforms like PostHog into your CommandKit Discord bot. ```sh npm install @commandkit/analytics ``` -------------------------------- ### Install @commandkit/cache Plugin Source: https://github.com/underctrl-io/commandkit/blob/main/packages/cache/README.md This snippet shows how to install the `@commandkit/cache` plugin using npm, a package manager for JavaScript. It's the first step to integrate caching capabilities into your CommandKit application. ```bash npm install @commandkit/cache ``` -------------------------------- ### Get Event Listeners for Node.js Emitters/Targets Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKit.mdx Returns a copy of the array of listeners for a specified event name from an `EventEmitter` or `EventTarget`. Useful for debugging and diagnostics, as it's the only way to get listeners for `EventTarget`s. ```APIDOC getEventListeners(emitter, name): Function[] emitter: EventEmitter | EventTarget (Optional: false) name: string | symbol (Optional: false) ``` -------------------------------- ### Install @commandkit/tasks Plugin via npm Source: https://github.com/underctrl-io/commandkit/blob/main/packages/tasks/README.md This command installs the `@commandkit/tasks` plugin using npm, making it available for use within your CommandKit project. It's the essential first step to integrate task management capabilities into your application. ```bash npm install @commandkit/tasks ``` -------------------------------- ### API Method: onBeforeCommandsLoad Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/RuntimePlugin.mdx Documents the `onBeforeCommandsLoad` method, which is invoked before commands begin loading. It provides the CommandKit plugin runtime context. ```APIDOC onBeforeCommandsLoad(ctx: CommandKitPluginRuntime): Promise Description: Called before commands are loaded. Parameters: ctx: CommandKitPluginRuntime (Required) ``` -------------------------------- ### CommandKitPluginRuntime API Documentation Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKitPluginRuntime.mdx Detailed API reference for the CommandKitPluginRuntime class, including its constructor, properties, and methods for plugin management within CommandKit. ```APIDOC class CommandKitPluginRuntime Constructor: new CommandKitPluginRuntime(commandkit) Parameters: commandkit: CommandKit (Required) Properties: public commandkit: any Methods: public capture(): void public execute(f): Promise Parameters: f: AsyncFunction<[ | CommandKitPluginRuntime | RuntimePlugin | ] | undefined | R> (Required) public getPlugin(pluginName): null | RuntimePlugin Parameters: pluginName: string (Required) public getPlugins(): Collection public registerPlugin(plugin): Promise Parameters: plugin: RuntimePlugin (Required) public softRegisterPlugin(plugin): Promise Parameters: plugin: RuntimePlugin (Required) public unregisterAllPlugins(): Promise public unregisterPlugin(plugin): Promise Parameters: plugin: RuntimePlugin (Required) ``` -------------------------------- ### Example Translation File with Command Localization Source: https://github.com/underctrl-io/commandkit/blob/main/packages/i18n/README.md This JSON snippet provides an example of a translation file (`ping.json`) that includes the special `$command` key. This key is used to localize command names, descriptions, and options, which are then merged with the actual command object for Discord compatibility. Other keys in the file are used for localizing command responses. ```JSON { "$command": { "name": "Ping", "description": "Ping the server", "options": [ { "name": "database", "description": "Ping the database" } ] }, "response": "Pong! The latency is {{latency}}ms" } ``` -------------------------------- ### Registering onApplicationBootstrap Hook in CommandKit Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/01-getting-started/06-onApplicationBootstrap-function.mdx This snippet demonstrates how to use the `onApplicationBootstrap` lifecycle hook in CommandKit. The provided callback function will execute once the application is fully initialized and ready, making it suitable for setting up initial configurations or logging application readiness. ```typescript import { onApplicationBootstrap } from 'commandkit'; onApplicationBootstrap((commandkit) => { // This code will run when the application is ready console.log('CommandKit is ready!'); }); ``` -------------------------------- ### Example of getEventListeners Usage Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/classes/CommandKit.mdx Illustrates how to use `getEventListeners` to retrieve listeners from both `EventEmitter` and `EventTarget` instances for a given event name. ```JavaScript import { getEventListeners, EventEmitter } from 'node:events'; { const ee = new EventEmitter(); const listener = () => console.log('Events are fun'); ee.on('foo', listener); console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] } { const et = new EventTarget(); const listener = () => console.log('Events are fun'); et.addEventListener('foo', listener); console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] } ``` -------------------------------- ### CommandKit Configuration: skipBuiltInValidations Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/03-commandkit-setup.mdx Disables CommandKit's default validation functions, specifically ignoring the `devOnly` command validation behavior. ```APIDOC Parameter: skipBuiltInValidations Type: boolean Default: false Description: Used to disable CommandKit's built-in validation functions. Setting this to `true` will ignore the default behaviour of validating who is running commands marked with `devOnly`. ``` -------------------------------- ### Initialize CommandKit Project (Development Version) Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/02-create-commandkit.mdx Use this command to create a new CommandKit application with the development version of the `create-commandkit` utility. Note that the development version is likely to have bugs and is intended for testing new features. ```bash npm create commandkit@dev ``` -------------------------------- ### Setting up CommandKit handler Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/versioned_docs/version-0.1.10/guide/10-migrating-from-djs-commander.mdx This snippet demonstrates how to instantiate the CommandKit handler. Unlike DJS-Commander's 'CommandHandler', CommandKit uses the 'CommandKit' class name for initialization, requiring the client, commands path, and events path. ```JavaScript const { CommandKit } = require('commandkit'); new CommandKit({ client, commandsPath, eventsPath, }); ``` -------------------------------- ### APIDOC: onBeforeCommandsLoad Lifecycle Hook Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/guide/06-plugins/03-creating-a-runtime-plugin.mdx Documentation for the `onBeforeCommandsLoad` lifecycle hook, which is invoked before commands are loaded into CommandKit. It provides the runtime context and is useful for initializing resources or modifying command loading behavior. ```APIDOC onBeforeCommandsLoad(ctx) Description: Called before commands are loaded into CommandKit. Parameters: ctx: The runtime context, providing access to CommandKit internals like the client, command context, etc. Example use case: Initialize resources needed by commands, or modify command loading behavior. ``` ```typescript async onBeforeCommandsLoad(ctx: CommandKitPluginRuntime): Promise { console.log('Loading commands soon...'); // Initialize resources needed for commands } ``` -------------------------------- ### Example Usage of ParagraphInput Component in TypeScript Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/functions/ParagraphInput.mdx Demonstrates how to instantiate the ParagraphInput component in TypeScript, specifying a custom ID and a label for the input field. ```ts ``` -------------------------------- ### Example Usage of ActionRow Component in TypeScript Source: https://github.com/underctrl-io/commandkit/blob/main/apps/website/docs/api-reference/functions/ActionRow.mdx Demonstrates how to use the ActionRow component to contain a Button, specifying its label, style, and custom ID. ```TypeScript