### Scaffolding with Curated Example Source: https://github.com/neplextech/commandkit/blob/main/skills/create-commandkit/references/02-example-templates.md Use this command to initialize a new project with a curated example template. Ensure you have `create-commandkit` installed or use `npx`. ```sh npx create-commandkit@latest --example basic-ts ``` -------------------------------- ### Basic create-commandkit Installation Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Run this command to start an interactive setup for a new Discord bot using CommandKit. ```sh npx create-commandkit@latest ``` -------------------------------- ### CommandKit v0 Manual Entry Point Setup Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/04-migrating-from-v0.mdx Example of a CommandKit v0 entry point, showing manual setup for the client, CommandKit instance, and paths. ```typescript import { Client, GatewayIntentBits } from 'discord.js'; import { CommandKit } from 'commandkit'; import path from 'path'; const client = new Client({ intents: [ 'Guilds', 'GuildMessages', 'MessageContent', ], }); new CommandKit({ client, commandsPath: path.join(__dirname, 'commands'), eventsPath: path.join(__dirname, 'events'), validationsPath: path.join(__dirname, 'validations'), skipBuiltInValidations: true, bulkRegister: true, }); client.login('YOUR_TOKEN_HERE'); ``` -------------------------------- ### Install CommandKit Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/01-setup-commandkit-manually.mdx Install CommandKit using npm or yarn. This is the first step in manual setup. ```sh npm install commandkit ``` -------------------------------- ### Get Help with CommandKit CLI Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Display all available options and usage examples for the `create-commandkit` CLI by using the help flag. ```bash npm create commandkit@latest --help ``` -------------------------------- ### Create CommandKit Project from Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Create a new CommandKit project using a specific example by providing the `--example` flag. ```bash # Create a basic TypeScript bot npm create commandkit@latest --example basic-ts ``` ```bash # Create a basic JavaScript bot npm create commandkit@latest --example basic-js ``` ```bash # Create a Deno TypeScript bot npm create commandkit@latest --example deno-ts ``` ```bash # Create a bot without CLI integration npm create commandkit@latest --example without-cli ``` -------------------------------- ### Install @commandkit/ai Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/01-commandkit-ai.mdx Install the core AI plugin and your preferred AI SDK. For example, install the Google Gemini SDK. ```bash npm install @commandkit/ai ``` ```bash npm install @ai-sdk/google ``` -------------------------------- ### CommandKit v0 Manual Configuration Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/04-migrating-from-v0.mdx Example of a CommandKit v0 configuration file, demonstrating the manual setup required for paths and entry points. ```typescript import { defineConfig } from 'commandkit'; export default defineConfig({ src: 'src', main: 'index.mjs', // Manual configuration was required }); ``` -------------------------------- ### List Available Examples Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Display a list of all available curated examples that can be used with create-commandkit. ```sh # List all available examples npx create-commandkit@latest --list-examples ``` -------------------------------- ### Basic Message Command Setup (JavaScript) Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/02-commands/04-message-commands.mdx Export the `message` function to define a message command. This example shows a simple 'ping' command that replies with 'Pong!'. ```javascript /** * @typedef {import('commandkit').CommandData} CommandData * @typedef {import('commandkit').MessageCommand} MessageCommand */ /** @type {CommandData} */ export const command = { name: 'ping', }; /** @type {MessageCommand} */ export const message = async (ctx) => { await ctx.message.reply('Pong!'); }; ``` -------------------------------- ### List Available CommandKit Examples Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Use this command to see all the pre-built examples available for CommandKit projects. ```bash npm create commandkit@latest --list-examples ``` -------------------------------- ### Install @commandkit/ratelimit Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/07-commandkit-ratelimit.mdx Install the ratelimit plugin using npm or yarn to begin. ```bash npm install @commandkit/ratelimit ``` ```bash yarn add @commandkit/ratelimit ``` -------------------------------- ### Use Curated Example with create-commandkit Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Bootstrap your Discord bot using a curated example from the CommandKit repository. ```sh # Use a curated example npx create-commandkit@latest --example with-database ``` -------------------------------- ### Install Dependencies Source: https://github.com/neplextech/commandkit/blob/main/examples/with-leveling-system/README.md Clone the repository and install project dependencies using npm. ```bash git clone https://github.com/neplextech/leveling-bot cd leveling-bot npm install ``` -------------------------------- ### Create CommandKit Project with npm Source: https://context7.com/neplextech/commandkit/llms.txt Use npm create to scaffold a new CommandKit project. Supports interactive setup, defaults, and specific examples. ```bash npm create commandkit@latest npm create commandkit@latest my-bot --yes --use-pnpm npm create commandkit@latest --example basic-ts npm create commandkit@latest --example basic-js npm create commandkit@latest --example deno-ts npm create commandkit@latest --example without-cli npm create commandkit@latest --list-examples ``` -------------------------------- ### Specify Example Path in Repository with create-commandkit Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md When using a custom GitHub repository, specify a subdirectory containing the example. ```sh # Use a specific path within a repository npx create-commandkit@latest --example "https://github.com/user/repo" --example-path "examples/bot" ``` -------------------------------- ### Example CommandKit Project Filesystem Source: https://github.com/neplextech/commandkit/blob/main/skills/create-commandkit/references/00-filesystem-structure.md An example illustrating the expected filesystem structure for a CommandKit bot. This structure is essential for CommandKit's runtime bootstrapping and feature discovery. ```txt my-bot/ package.json commandkit.config.ts src/ app/ commands/ events/ ``` -------------------------------- ### User Onboarding Workflow Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/10-commandkit-workflow.mdx An example of a multi-step user onboarding workflow, including delays. ```typescript import { sleep } from 'workflow'; import { sendWelcomeMessage } from './steps/send-welcome-message'; import { assignRole } from './steps/assign-role'; import { sendFollowUpMessage } from './steps/send-follow-up-message'; export async function userOnboardingWorkflow(userId: string, guildId: string) { 'use workflow'; await sendWelcomeMessage(userId, guildId); await assignRole(userId, guildId); await sleep('7 days'); await sendFollowUpMessage(userId, guildId); return { userId, status: 'completed' }; } ``` -------------------------------- ### Install @commandkit/redis Source: https://github.com/neplextech/commandkit/blob/main/packages/redis/README.md Install the package using npm. ```sh npm install @commandkit/redis ``` -------------------------------- ### CommandKit Project Filesystem Structure with Example Command Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit-i18n/references/00-filesystem-structure.md An example illustrating the filesystem structure with a specific command file ('ping.json') placed within the locales directory. This demonstrates how command-specific locale files should be organized. ```txt project/ commandkit.config.ts src/ app/ locales/ en-US/ ping.json commands/ events/ ``` -------------------------------- ### Install @commandkit/tasks Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/08-commandkit-tasks.mdx Install the tasks plugin using npm. ```bash npm install @commandkit/tasks ``` -------------------------------- ### Install @commandkit/workflow Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/10-commandkit-workflow.mdx Install the necessary packages for the workflow plugin. ```bash npm install @commandkit/workflow workflow ``` -------------------------------- ### Start Workflow from Command Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit-workflow/references/03-start-workflow.md Use this snippet to start a workflow from a command handler. Ensure the `start` API and the workflow are correctly imported. ```typescript import { start } from 'workflow/api'; import { greetUserWorkflow } from '@/workflows/greet'; export const chatInput = async (ctx) => { await ctx.interaction.reply("I'm gonna greet you"); await start(greetUserWorkflow, [ctx.interaction.user.id]); }; ``` -------------------------------- ### Install Dependencies Source: https://github.com/neplextech/commandkit/blob/main/examples/with-ai/README.md Install the necessary Node.js dependencies for the Agent bot. Ensure you have Node.js v22 or higher installed. ```bash npm install ``` -------------------------------- ### CommandKit.start Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/command-kit.mdx Starts the CommandKit application, optionally with a provided token. ```APIDOC ## start ### Description Starts the commandkit application. ### Method `start(token?: string | false)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **token** (string | false) - Optional - The authentication token to use for starting the application. ``` -------------------------------- ### Install @commandkit/i18n Source: https://github.com/neplextech/commandkit/blob/main/packages/i18n/README.md Install the i18n plugin using npm. ```sh $ npm i @commandkit/i18n ``` -------------------------------- ### Run Deno Dev Server Source: https://github.com/neplextech/commandkit/blob/main/examples/deno-ts/README.md Starts the development server for live reloading and testing. ```sh deno task dev ``` -------------------------------- ### Install Deno Dependencies Source: https://github.com/neplextech/commandkit/blob/main/examples/deno-ts/README.md Run this command to install necessary Deno dependencies for the project. ```sh deno install ``` -------------------------------- ### Basic Message Command Setup (TypeScript) Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/02-commands/04-message-commands.mdx Export the `message` function to define a message command. This example shows a simple 'ping' command that replies with 'Pong!'. ```typescript import type { CommandData, MessageCommand } from 'commandkit'; export const command: CommandData = { name: 'ping', }; export const message: MessageCommand = async (ctx) => { await ctx.message.reply('Pong!'); }; ``` -------------------------------- ### Create CommandKit Project with Package Manager Flags Source: https://github.com/neplextech/commandkit/blob/main/skills/create-commandkit/references/03-package-manager-flags.md Use this command to create a new CommandKit project with specific package manager and setup flags. It demonstrates using pnpm, skipping installation, and disabling Git initialization. ```bash npx create-commandkit@latest --use-pnpm --skip-install --no-git ``` -------------------------------- ### Install @commandkit/devtools Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/04-commandkit-devtools.mdx Install the devtools plugin using npm or yarn. ```sh npm install @commandkit/devtools ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/neplextech/commandkit/blob/main/CONTRIBUTING.md Install project dependencies using pnpm from the root directory. Ensure you have pnpm installed globally. ```bash cd commandkit pnpm install ``` -------------------------------- ### Install @commandkit/i18n Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/05-commandkit-i18n.mdx Install the i18n plugin using npm or yarn. ```sh npm install @commandkit/i18n ``` -------------------------------- ### Create Basic TypeScript Bot and Skip Install Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Bootsrap a basic TypeScript bot and skip the package installation step. ```sh # Create a basic TypeScript bot, skip installation npx create-commandkit@latest --example basic-ts --skip-install ``` -------------------------------- ### Install @commandkit/ai Source: https://github.com/neplextech/commandkit/blob/main/packages/ai/README.md Install the @commandkit/ai package using npm. ```bash npm install @commandkit/ai ``` -------------------------------- ### Example Locale File Organization Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit-i18n/references/02-locales-structure.md Shows a specific example of how locale files for a 'ping' command might be organized across different languages. ```txt src/ app/ locales/ en-US/ ping.json fr/ ping.json commands/ ping.ts ``` -------------------------------- ### Discord.js Sharding Manager Setup Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit/references/07-sharding-your-bot.md Use this setup for your bot's sharding manager entrypoint. Ensure environment variables like DISCORD_TOKEN are loaded before manager creation. The `index.js` path should point to your bot's main runtime entrypoint. ```typescript // src/sharding-manager.ts import { ShardingManager } from 'discord.js'; import { join } from 'node:path'; process.loadEnvFile('./.env'); const manager = new ShardingManager(join(import.meta.dirname, 'index.js'), { token: process.env.DISCORD_TOKEN, totalShards: 2, mode: 'worker', }); manager.on('shardCreate', (shard) => { console.log(`Launched shard ${shard.id}`); }); await manager.spawn(); ``` -------------------------------- ### Install @commandkit/analytics Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/02-commandkit-analytics.mdx Install the analytics package using npm or yarn. ```bash npm install @commandkit/analytics ``` -------------------------------- ### Install @discordjs/brokers and ioredis Source: https://github.com/neplextech/commandkit/blob/main/packages/queue/README.md Install the necessary dependencies for using the Redis driver with @discordjs/brokers. ```bash npm install @discordjs/brokers ioredis ``` -------------------------------- ### String Select Menu Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/04-jsx-components/02-interactive-components/03-select-menu.mdx Implement a string select menu for users to choose from predefined string options. This example shows how to define options, handle selections, and reply to the user. ```tsx import { type ChatInputCommand, type OnStringSelectMenuKitSubmit, ActionRow, StringSelectMenu, StringSelectMenuOption, } from 'commandkit'; import { MessageFlags } from 'discord.js'; const handleSelect: OnStringSelectMenuKitSubmit = async ( interaction, context, ) => { const selection = interaction.values[0]; await interaction.reply({ content: `You selected: ${selection}`, flags: MessageFlags.Ephemeral, }); // Clean up the select menu context context.dispose(); }; export const chatInput: ChatInputCommand = async ({ interaction }) => { const selectMenu = ( ); await interaction.reply({ content: 'Please make a selection:', components: [selectMenu], }); }; ``` -------------------------------- ### Start Workflow from Command Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/10-commandkit-workflow.mdx Initiate a workflow from a CommandKit command using the 'start' function. ```typescript import type { CommandData, ChatInputCommand } from 'commandkit'; import { start } from 'workflow/api'; import { greetUserWorkflow } from '@/workflows/greet/greet.workflow'; export const command: CommandData = { name: 'greet', description: 'Greet a user with a workflow', }; export const chatInput: ChatInputCommand = async (ctx) => { await ctx.interaction.reply("I'm going to greet you! :wink:"); await start(greetUserWorkflow, [ctx.interaction.user.id]); }; ``` -------------------------------- ### Start CommandKit in Production Mode Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/01-setup-commandkit-manually.mdx Use this command to start your bot in production mode. It automatically loads environment variables from a `.env` file. ```bash npx commandkit start ``` -------------------------------- ### Manually Start Bot in Production Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/01-setup-commandkit-manually.mdx Alternatively, you can manually start your bot in production by executing the compiled JavaScript file using Node.js. ```bash node dist/index.js ``` -------------------------------- ### Install CommandKit Queue Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/09-commandkit-queue.mdx Install the core CommandKit Queue package using npm. ```bash npm install @commandkit/queue ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/neplextech/commandkit/blob/main/examples/without-cli/README.md Install project dependencies using pnpm. This is a prerequisite for running the project. ```sh pnpm install ``` -------------------------------- ### MediaGalleryItem Usage Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/media-gallery-item.mdx Import and use the MediaGalleryItem component by providing a URL and a description. This example demonstrates a basic implementation in a React context. ```tsx import { MediaGalleryItem } from 'commandkit'; const item = ; ``` -------------------------------- ### Basic Translation File Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/05-commandkit-i18n.mdx Example of a basic translation file for a command, including response and error messages. ```json { "response": "🏓 Pong! Latency: **{{latency}}ms**", "error": "❌ Failed to ping the server", "database_response": "📊 Database latency: **{{dbLatency}}ms**" } ``` -------------------------------- ### Additional Application Directories Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit/references/00-filesystem-structure.md Example of additional directories that can be placed within the `src/app/` directory for organizing components and utilities. ```txt src/ app/ components/ utils/ ``` -------------------------------- ### Basic Setup for @commandkit/devtools Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/04-commandkit-devtools.mdx Add the devtools plugin to your CommandKit configuration to enable its features. ```typescript import { defineConfig } from 'commandkit'; import { devtools } from '@commandkit/devtools'; export default defineConfig({ plugins: [devtools()], }); ``` -------------------------------- ### KV Get Method Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/kv.mdx Illustrates how to retrieve data using the get method, including accessing nested properties via dot notation. ```typescript // Store an object v.set('user:123', { name: 'John', age: 30, settings: { theme: 'dark' } }); // Get the entire object const user = kv.get('user:123'); // { name: 'John', age: 30, settings: { theme: 'dark' } } // Get nested properties using dot notation const name = kv.get('user:123.name'); // 'John' const theme = kv.get('user:123.settings.theme'); // 'dark' ``` -------------------------------- ### Scaffolding with Custom Repository Example Source: https://github.com/neplextech/commandkit/blob/main/skills/create-commandkit/references/02-example-templates.md Initialize a new project using a template from a custom GitHub repository. Provide the full repository URL. ```sh npx create-commandkit@latest --example "https://github.com/user/repo" ``` -------------------------------- ### Run Development Server Source: https://github.com/neplextech/commandkit/blob/main/examples/with-leveling-system/README.md Start the bot in development mode using the npm run dev script. ```bash npm run dev ``` -------------------------------- ### Create Production Build and Start Server Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/05-using-cli-api.mdx Utilize the production module to create an optimized production build and then bootstrap the production server. Both actions require the path to the configuration file. ```ts import { production } from 'commandkit/cli'; // Create a production build await production.createProductionBuild('./commandkit.config.ts'); // Start production server const server = await production.bootstrapProductionServer( './commandkit.config.ts', ); ``` -------------------------------- ### Run in Production Source: https://github.com/neplextech/commandkit/blob/main/examples/with-leveling-system/README.md Execute the built bot in a production environment using the npm run start script. ```bash npm run start ``` -------------------------------- ### Filesystem Structure Example Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit/references/08-file-naming-conventions.md Illustrates the expected directory and file structure for CommandKit applications, including command and event handler organization. ```txt src/ app.ts app/ commands/ +global-middleware.ts +middleware.ts +.middleware.ts events/ / .ts ``` -------------------------------- ### Handle Translation Errors in Event Handlers Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/05-commandkit-i18n.mdx This example demonstrates how to gracefully handle translation errors in an event handler by providing a fallback message in English. It uses the `locale` function to get a translation function `t` based on the guild's preferred locale. ```typescript import { locale } from '@commandkit/i18n'; import type { Message } from 'discord.js'; const FORBIDDEN_WORDS = ['spam', 'scam', 'hack']; export default async function autoModerator(message: Message) { if (message.author.bot) return; try { const { t } = locale(message.guild?.preferredLocale); const hasViolation = FORBIDDEN_WORDS.some((word) => message.content.toLowerCase().includes(word), ); if (hasViolation) { // Delete the message await message.delete(); // Send warning await message.channel.send({ content: t('moderation.auto_warning', { user: message.author.displayName, }), }); // Log the action console.log( t('moderation.log_message', { user: message.author.tag, guild: message.guild?.name, channel: message.channel.name, }), ); } } catch (error) { // Fallback to English if translation fails console.error('Translation error:', error); await message.channel.send( `⚠️ ${message.author.displayName}, please follow our community guidelines.`, ); } } ``` -------------------------------- ### StringSelectMenu Component Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/string-select-menu.mdx Demonstrates how to import and use the StringSelectMenu component with options. Ensure StringSelectMenuOption is also imported. ```tsx import { StringSelectMenu } from 'commandkit'; const stringSelectMenu = ``` -------------------------------- ### Start CommandKit with Devtools Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/04-commandkit-devtools.mdx Run your application in development mode using the 'commandkit dev' command to activate the devtools. ```bash npx commandkit dev ``` -------------------------------- ### Create Entrypoint File (TypeScript) Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/01-setup-commandkit-manually.mdx Set up the main application file using TypeScript. This file must export your discord.js client instance. ```typescript import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds'], }); client.token = '...'; // Optional: Manually set a bot token export default client; ``` -------------------------------- ### Implement LaunchDarklyProvider Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/09-useful-utilities/01-feature-flags.mdx Implement the FlagProvider interface for LaunchDarkly. This example shows how to initialize the client, fetch flag configurations, and handle potential errors. ```typescript import { FlagProvider, FlagConfiguration } from 'commandkit'; export class LaunchDarklyProvider implements FlagProvider { private client: any; // LaunchDarkly SDK client constructor(private apiKey: string) {} async initialize(): Promise { // Initialize LaunchDarkly client // this.client = LaunchDarkly.initialize(this.apiKey); // await this.client.waitUntilReady(); console.log('LaunchDarkly provider initialized'); } async getFlag(key: string, context?: any): Promise { try { // Fetch flag from LaunchDarkly // const variation = await this.client.variation(key, context, false); // const flagDetail = await this.client.variationDetail(key, context, false); // Return provider configuration return { enabled: true, // Whether the flag is enabled percentage: 75, // Optional: percentage rollout config: { // Custom configuration from LaunchDarkly colors: ['#ff0000', '#00ff00'], feature: 'enhanced-ui', }, }; } catch (error) { console.error(`LaunchDarkly flag evaluation failed for ${key}:`, error); return null; } } async hasFlag(key: string): Promise { // Check if flag exists in LaunchDarkly return true; } async destroy(): Promise { // Clean up LaunchDarkly client // await this.client.close(); } } ``` -------------------------------- ### Initialize Discord Client Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit/references/09-manual-setup.md Set up the Discord.js client instance. Ensure necessary intents are provided. CommandKit will handle the client's login and lifecycle management. ```typescript // src/app.ts import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds'] }); export default client; ``` -------------------------------- ### Compare Project Structure: v1 vs v0 Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/04-migrating-from-v0.mdx Illustrates the difference in project structure between CommandKit v1's framework-based 'app' directory and v0's legacy structure. ```tree . ├── src/ │ ├── app/ │ │ ├── commands/ │ │ │ └── ping.ts │ │ └── events/ │ │ └── clientReady/ │ │ └── log.ts │ └── app.ts ├── .env ├── commandkit.config.ts ├── package.json └── tsconfig.json ``` ```tree . ├── src/ │ ├── commands/ │ │ └── ping.ts │ ├── events/ │ │ └── clientReady/ │ │ └── log.ts │ └── index.ts ├── .env ├── commandkit.config.mjs ├── package.json └── tsconfig.json ``` -------------------------------- ### Production Module Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/05-using-cli-api.mdx Handles production builds and server startup. ```APIDOC ## Production Module ### Description Handles production builds and server startup. ### Functions - `createProductionBuild(configPath?: string)`: Creates an optimized production build. - `bootstrapProductionServer(configPath?: string)`: Starts the production server. ### Example ```ts import { production } from 'commandkit/cli'; // Create a production build await production.createProductionBuild('./commandkit.config.ts'); // Start production server const server = await production.bootstrapProductionServer( './commandkit.config.ts', ); ``` ``` -------------------------------- ### Create a New CommandKit Project Source: https://github.com/neplextech/commandkit/blob/main/packages/commandkit/README.md Use this command to initialize a new CommandKit project. Follow the prompts to configure your bot. ```bash npm create commandkit ``` -------------------------------- ### Build CommandKit for Production Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/01-setup-commandkit-manually.mdx Execute this command to create a production-ready build of your application. The compiled files will be placed in the `dist` folder. ```bash npx commandkit build ``` -------------------------------- ### Complete LoggingPlugin Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/07-creating-plugins/01-creating-runtime-plugin.mdx A comprehensive runtime plugin demonstrating multiple hooks: onAfterClientLogin, onBeforeInteraction, executeCommand, and prepareCommand. It includes logging, command usage tracking, and development environment command name modification. ```typescript import { type PreparedAppCommandExecution, type CommandKitEnvironment, type CommandKitPluginRuntime, type CommandBuilderLike, RuntimePlugin, } from 'commandkit'; import type { Interaction, Message } from 'discord.js'; 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; } } ``` -------------------------------- ### CommandKit v1 Streamlined Entry Point Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/04-migrating-from-v0.mdx How to set up the entry point in CommandKit v1. Simply export a configured Discord.js client; CommandKit handles the rest. ```typescript import { Client } from 'discord.js'; const client = new Client({ intents: [ 'Guilds', 'GuildMessages', 'MessageContent', ], }); // Optional: Override the default DISCORD_TOKEN env variable client.token = 'CUSTOM_BOT_TOKEN'; export default client; // CommandKit handles the rest automatically ``` -------------------------------- ### Creating and Configuring a Channel Select Menu Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/channel-select-menu-kit.mdx Example of how to instantiate and configure a ChannelSelectMenuKit, including setting a filter and an onSelect handler. ```typescript const modal = new ChannelSelectMenuKit() .setTitle('My Modal') .setCustomId('my-modal') .filter((interaction) => interaction.Channel.id === '1234567890') .onSelect(async (interaction) => { await interaction.reply('You submitted the modal!'); }) .addComponents(actionRow1, actionRow2); ``` -------------------------------- ### Command Middleware Example Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit/references/08-file-naming-conventions.md Defines a middleware function to execute before a command. This example logs the command name. ```typescript // src/app/commands/+middleware.ts import type { MiddlewareContext } from 'commandkit'; export function beforeExecute(ctx: MiddlewareContext) { console.log(`before ${ctx.command.name}`); } ``` -------------------------------- ### CommandKit Configuration with Plugins Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit-plugin-development/references/00-filesystem-structure.md Example of how to configure CommandKit with both runtime and compiler plugins in the commandkit.config.ts file. Ensure plugin instances or wrappers are listed in the 'plugins' array. ```typescript // commandkit.config.ts import { defineConfig } from 'commandkit'; export default defineConfig({ plugins: [ // runtime plugin instances or plugin wrappers ], rolldownPlugins: [ // optional compiler-time rolldown plugins ], }); ``` -------------------------------- ### Install @commandkit/cache Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/03-commandkit-cache.mdx Install the cache package using npm or yarn to enable caching functionality in your CommandKit project. ```bash npm install @commandkit/cache ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/neplextech/commandkit/blob/main/examples/with-ai/README.md Set up your environment variables by creating a .env file. This file should contain your Discord bot token, Google API key, and Clipdrop API key. ```env DISCORD_TOKEN="your_discord_token" GOOGLE_API_KEY="your_google_api_key" CLIPDROP_API_KEY="your_clipdrop_api_key" ``` -------------------------------- ### Install @commandkit/legacy Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/06-commandkit-legacy.mdx Install the legacy plugin using npm or yarn. This package is deprecated and only supported up to CommandKit v1.2.0-rc.10. ```sh npm install @commandkit/legacy ``` -------------------------------- ### CommandKit v1 Simplified Configuration Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/08-advanced/04-migrating-from-v0.mdx Example of a CommandKit v1 configuration file. Configuration is optional as the framework auto-detects project structure. ```typescript import { defineConfig } from 'commandkit'; export default defineConfig({ // Configuration is now optional for most use cases // CommandKit automatically detects your app structure }); ``` -------------------------------- ### KV Store Configuration Options Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/09-useful-utilities/05-commandkit-kv.mdx Shows how to create KV store instances with different configurations, including specifying a custom database file, using an in-memory store for testing, and setting a specific namespace. ```typescript import { openKV } from 'commandkit/kv'; // Create with custom database file const kv = openKV('my-bot-data.db'); // In-memory store for testing const testKv = openKV(':memory:'); // Create with specific namespace const userKv = openKV('data.db', { namespace: 'users', }); ``` -------------------------------- ### Scaffolding with Custom Path in Repository Source: https://github.com/neplextech/commandkit/blob/main/skills/create-commandkit/references/02-example-templates.md Initialize a new project using a template located at a specific path within a custom GitHub repository. Use the `--example-path` flag to specify the directory. ```sh npx create-commandkit@latest --example "https://github.com/user/repo" --example-path "examples/bot" ``` -------------------------------- ### Install Discord.js Integration with Redis Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/05-official-plugins/09-commandkit-queue.mdx Install CommandKit Queue along with necessary packages for Discord.js integration and Redis support. ```bash npm install @commandkit/queue @discordjs/brokers ioredis ``` -------------------------------- ### Displaying a Media Gallery Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/04-jsx-components/03-display-components/03-media-gallery.mdx This example demonstrates how to use the MediaGallery and MediaGalleryItem components to create a responsive grid of images. It maps an array of image URLs to MediaGalleryItem components and includes a TextDisplay for a title. Ensure you have the necessary CommandKit imports. ```tsx import { type ChatInputCommand, MediaGallery, MediaGalleryItem, TextDisplay, } from 'commandkit'; import { MessageFlags } from 'discord.js'; export const chatInput: ChatInputCommand = async ({ interaction }) => { const images = [ 'https://cdn.discordapp.com/embed/avatars/0.png', 'https://cdn.discordapp.com/embed/avatars/1.png', 'https://cdn.discordapp.com/embed/avatars/2.png', ]; const components = [ , {images.map((url, index) => ( ))} , ]; await interaction.reply({ components: components, flags: MessageFlags.IsComponentsV2, }); }; ``` -------------------------------- ### Create Bot from Custom Repository Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Initialize a bot project using a custom GitHub repository URL. ```sh # Create a bot from custom repository npx create-commandkit@latest --example "https://github.com/username/my-commandkit-template" ``` -------------------------------- ### Get Available Permits Signature Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/get-available-permits.mdx Gets the number of available permits using the default semaphore. Requires a string key to identify the semaphore. ```typescript function getAvailablePermits(key: string): Promise ``` -------------------------------- ### Get Localization Context Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/i18n/functions/locale.mdx Use the locale function to get the localization context for a specific locale. The returned 't' function is bound to the provided locale for translations. ```typescript const { t, locale, i18n } = locale('en-US'); const translated = t('hello'); // Translates 'hello' in the 'en-US' locale ``` -------------------------------- ### Debounce Function Example Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/debounce.mdx This example demonstrates how to use the debounce function. The debounced function will only execute after 300ms of inactivity. Subsequent calls within this period will reset the timer. ```typescript const debouncedFn = debounce(() => { console.log('Debounced function called'); }, 300); debouncedFn(); // Will only execute after 300ms of inactivity debouncedFn(); // Will reset the timer debouncedFn(); // Will reset the timer again ``` -------------------------------- ### Create Bot with All Defaults Source: https://github.com/neplextech/commandkit/blob/main/packages/create-commandkit/README.md Use the --yes flag to create a bot with all default options, bypassing interactive prompts. ```sh # Create a bot with all defaults (no prompts) npx create-commandkit@latest --yes ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/neplextech/commandkit/blob/main/examples/with-leveling-system/README.md Set up the .env file with necessary Discord bot token, Redis URL, and database connection string. ```env # The discord bot token DISCORD_TOKEN="xxx" # Redis url REDIS_URL="redis://localhost:6379" # Database url DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public" ``` -------------------------------- ### Build Deno Project Source: https://github.com/neplextech/commandkit/blob/main/examples/deno-ts/README.md Compiles the project for production deployment. ```sh deno task build ``` -------------------------------- ### Basic KV Store Usage Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/09-useful-utilities/05-commandkit-kv.mdx Demonstrates the fundamental operations of creating a KV store instance, storing data, and retrieving it. Ensure the 'commandkit/kv' module is imported. ```typescript import { KV } from 'commandkit/kv'; // Create a new KV store const kv = new KV('data.db'); // Store data directly kv.set('user:123', { name: 'John', age: 30 }); kv.set('counter', 42); kv.set('active', true); // Retrieve data const user = kv.get('user:123'); // { name: 'John', age: 30 } const counter = kv.get('counter'); // 42 ``` -------------------------------- ### get Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/command-kit-plugin-runtime.mdx Fetches an instance of a specific plugin. ```APIDOC ## get ### Description Fetches the instance of the given plugin. ### Method get ### Parameters - **plugin** (T) - The plugin class or constructor to fetch. ### Returns - The instance of the plugin or null if not found. ``` -------------------------------- ### Create New CommandKit Project Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/guide/01-getting-started/02-setup-commandkit.mdx Run this command in your terminal to start the interactive CLI for setting up a new CommandKit project. ```bash npm create commandkit@latest ``` -------------------------------- ### args Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/context.mdx Gets the command arguments (only available for message commands). ```APIDOC ## args ### Description Gets the command arguments (only available for message commands). ### Method `args() => string[]` ``` -------------------------------- ### CommandKit.getPath Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/command-kit.mdx Gets the path to either the commands or events directory. ```APIDOC ## getPath ### Description Get the path to the commands or events directory. ### Method `getPath(to: 'commands' | 'events')` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **to** ('commands' | 'events') - Specifies whether to get the path for 'commands' or 'events'. ``` -------------------------------- ### CommandKit.started Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/command-kit.mdx A boolean property indicating whether the CommandKit application has started. ```APIDOC ## started ### Description Whether or not the commandkit application has started. ### Property `started` (boolean) ``` -------------------------------- ### getAvailablePermits Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/get-available-permits.mdx Gets the number of available permits using the default semaphore. ```APIDOC ## getAvailablePermits ### Description Gets the number of available permits using the default semaphore. ### Method ```ts function getAvailablePermits(key: string): Promise ``` ### Parameters #### key - **key** (string) - Required - The key for which to retrieve available permits. ``` -------------------------------- ### getRemainingRequests Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/functions/get-remaining-requests.mdx Gets the remaining requests for a key using the default rate limiter. ```APIDOC ## getRemainingRequests ### Description Gets the remaining requests for a key using the default rate limiter. ### Parameters #### key - **key** (string) - The identifier for which to retrieve remaining requests. ### Returns - **Promise** - A promise that resolves to the number of remaining requests. ``` -------------------------------- ### Initialize Redis Pub/Sub Driver for CommandKit Queue Source: https://github.com/neplextech/commandkit/blob/main/skills/commandkit-queue/references/01-driver-setup.md Use this snippet to set up the Redis Pub/Sub driver for the CommandKit queue. Ensure you have 'ioredis' and '@discordjs/brokers' installed. ```typescript import Redis from 'ioredis'; import { PubSubRedisBroker } from '@discordjs/brokers'; import { RedisPubSubDriver } from '@commandkit/queue/discordjs'; import { setDriver } from '@commandkit/queue'; const broker = new PubSubRedisBroker(new Redis()); const driver = new RedisPubSubDriver(broker); setDriver(driver); ``` -------------------------------- ### Get Command Prefix Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/message-command-parser.mdx Returns the prefix that was used to identify the command in the message. ```typescript parser.getPrefix() ``` -------------------------------- ### Get Parsed Command Arguments Source: https://github.com/neplextech/commandkit/blob/main/apps/website/docs/api-reference/commandkit/classes/message-command-parser.mdx Retrieves the arguments that have been parsed from the message content. ```typescript parser.getArgs() ```