### Create CommandKit Project with CLI Options Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Demonstrates how to use the `create-commandkit` CLI with different flags to customize project setup. Options include skipping dependency installation (`--skip-install`), skipping git initialization (`--no-git`), specifying a project name for creation in a specific directory, and using a custom GitHub repository for examples (`--example`). ```bash bunx create-commandkit --skip-install bunx create-commandkit --no-git bunx create-commandkit my-bot bunx create-commandkit --example "https://github.com/user/repo" ``` -------------------------------- ### List Available CommandKit Examples with npm, Yarn, pnpm, or Bun Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Use these commands to list all available pre-built examples for CommandKit projects. This helps you choose a starting point for your bot development. Requires Node.js v24+. ```bash npm create commandkit@latest --list-examples ``` ```bash yarn create commandkit --list-examples ``` ```bash pnpm create commandkit --list-examples ``` ```bash bunx create-commandkit --list-examples ``` -------------------------------- ### Create CommandKit Project from Examples with npm, Yarn, pnpm, or Bun Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit These commands create a new CommandKit project using specific examples like 'basic-ts', 'basic-js', 'deno-ts', or 'without-cli'. The `--example` flag specifies the template to use. Node.js v24+ is required. ```bash # Create a basic TypeScript bot npm create commandkit@latest --example basic-ts # Create a basic JavaScript bot npm create commandkit@latest --example basic-js # Create a Deno TypeScript bot npm create commandkit@latest --example deno-ts # Create a bot without CLI integration npm create commandkit@latest --example without-cli ``` ```bash # Create a basic TypeScript bot yarn create commandkit --example basic-ts # Create a basic JavaScript bot yarn create commandkit --example basic-js # Create a Deno TypeScript bot yarn create commandkit --example deno-ts # Create a bot without CLI integration yarn create commandkit --example without-cli ``` ```bash # Create a basic TypeScript bot pnpm create commandkit --example basic-ts # Create a basic JavaScript bot pnpm create commandkit --example basic-js # Create a Deno TypeScript bot pnpm create commandkit --example deno-ts # Create a bot without CLI integration pnpm create commandkit --example without-cli ``` ```bash # Create a basic TypeScript bot bunx create-commandkit --example basic-ts # Create a basic JavaScript bot bunx create-commandkit --example basic-js # Create a Deno TypeScript bot bunx create-commandkit --example deno-ts # Create a bot without CLI integration bunx create-commandkit --example without-cli ``` -------------------------------- ### Initialize CommandKit Project with npm, Yarn, pnpm, or Bun Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit These commands initialize a new CommandKit project using the respective package managers. The CLI will guide you through an interactive setup process. Ensure you have Node.js v24 or higher installed. ```bash npm create commandkit@latest ``` ```bash yarn create commandkit ``` ```bash pnpm create commandkit ``` ```bash bunx create-commandkit ``` -------------------------------- ### Start CommandKit in Production Mode (npm) Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Launches the CommandKit application in production mode, loading environment variables from the `.env` file. This is the standard way to deploy your bot. ```bash npx commandkit start ``` -------------------------------- ### Install CommandKit using npm, Yarn, pnpm, or Bun Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Installs the CommandKit package with the next tag for the latest release candidate. This command can be executed using various package managers. ```bash npm install commandkit@next ``` ```bash yarn add commandkit@next ``` ```bash pnpm add commandkit@next ``` ```bash bun add commandkit@next ``` -------------------------------- ### Get Help for CommandKit CLI Options Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Demonstrates how to access help information for CommandKit CLI options using the `--help` flag. This is applicable across different package managers like npm, Yarn, pnpm, and Bun, providing details on available commands and usage. ```bash npm create commandkit@latest --help yarn create commandkit --help pnpm create commandkit --help bunx create-commandkit --help ``` -------------------------------- ### CommandKit CLI Options with npm, Yarn, pnpm, or Bun Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit These commands demonstrate various CLI options for customizing CommandKit project setup, such as skipping prompts, specifying package managers, skipping installations or git initialization, creating in a specific directory, or using a custom GitHub repository. Node.js v24+ is required. ```bash # Skip prompts and use defaults npm create commandkit@latest --yes # Use a specific package manager npm create commandkit@latest --use-pnpm npm create commandkit@latest --use-yarn npm create commandkit@latest --use-bun npm create commandkit@latest --use-deno # Skip dependency installation npm create commandkit@latest --skip-install # Skip git initialization npm create commandkit@latest --no-git # Create in a specific directory npm create commandkit@latest my-bot # Use a custom GitHub repository npm create commandkit@latest --example "https://github.com/user/repo" ``` ```bash # Skip prompts and use defaults yarn create commandkit --yes # Use a specific package manager yarn create commandkit --use-pnpm yarn create commandkit --use-yarn yarn create commandkit --use-bun yarn create commandkit --use-deno # Skip dependency installation yarn create commandkit --skip-install # Skip git initialization yarn create commandkit --no-git # Create in a specific directory yarn create commandkit my-bot # Use a custom GitHub repository yarn create commandkit --example "https://github.com/user/repo" ``` ```bash # Skip prompts and use defaults pnpm create commandkit --yes # Use a specific package manager pnpm create commandkit --use-pnpm pnpm create commandkit --use-yarn pnpm create commandkit --use-bun pnpm create commandkit --use-deno # Skip dependency installation pnpm create commandkit --skip-install # Skip git initialization pnpm create commandkit --no-git # Create in a specific directory pnpm create commandkit my-bot # Use a custom GitHub repository pnpm create commandkit --example "https://github.com/user/repo" ``` ```bash # Skip prompts and use defaults bunx create-commandkit --yes # Use a specific package manager bunx create-commandkit --use-pnpm bunx create-commandkit --use-yarn bunx create-commandkit --use-bun bunx create-commandkit --use-deno ``` -------------------------------- ### v0 Manual Setup Entry Point (JavaScript) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Shows the v0 manual setup for the entry point in JavaScript. This involved explicitly creating the CommandKit instance, specifying paths, and logging in the client. ```javascript 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'); ``` -------------------------------- ### Manually Start CommandKit in Production (Node.js) Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Allows for manual startup of the CommandKit application in production mode using a Node.js runtime. This method bypasses the CommandKit CLI and directly executes the compiled JavaScript files from the `dist` directory. ```bash node dist/index.js ``` -------------------------------- ### Start Production Application (Node.js) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Starts the CommandKit application in production mode by directly executing the main JavaScript file generated during the build process. ```bash node dist/index.js ``` -------------------------------- ### v1 Project Structure Example (TypeScript) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Illustrates the new v1 project structure for CommandKit, featuring an 'app' directory for commands and events. This structure enhances organization and enables features like automatic route discovery. ```tree . ├── src/ │ ├── app/ │ │ ├── commands/ │ │ │ └── ping.ts │ │ └── events/ │ │ └── clientReady/ │ │ └── log.ts │ └── app.ts ├── .env ├── commandkit.config.ts ├── package.json └── tsconfig.json ``` -------------------------------- ### v0 Project Structure Example (Legacy) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Shows the legacy v0 project structure for CommandKit, where commands and events were placed directly under the 'src' directory. This structure is being replaced by the v1 'app' directory approach. ```tree . ├── src/ │ ├── commands/ │ │ └── ping.ts │ ├── events/ │ │ └── clientReady/ │ │ └── log.ts │ └── index.ts ├── .env ├── commandkit.config.mjs ├── package.json └── tsconfig.json ``` -------------------------------- ### Start Production Application (CLI) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Starts the CommandKit application in production mode using the CommandKit CLI. This is the recommended method for running the application in a production environment. ```bash npx commandkit start ``` ```bash yarn dlx commandkit start ``` ```bash pnpm dlx commandkit start ``` ```bash bun x commandkit start ``` -------------------------------- ### Start Development Server (CLI) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Starts the CommandKit development server using the CommandKit CLI. This enables features like Hot Module Replacement (HMR) for rapid development. ```bash npx commandkit dev ``` ```bash yarn dlx commandkit dev ``` ```bash pnpm dlx commandkit dev ``` ```bash bun x commandkit dev ``` -------------------------------- ### Handle the clientReady Event Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Sets up an event handler for the `clientReady` event, which is emitted when the discord.js client has successfully logged in. This example logs the bot's username to the console. ```typescript import type { Client } from 'discord.js'; export default function (client: Client) { console.log(`Logged in as ${client.user.username}!`); } ``` ```javascript /** * Event handler for when the bot is ready * @param {import('discord.js').Client} client - The Discord client instance */ export default function (client) { console.log(`Logged in as ${client.user.username}!`); } ``` -------------------------------- ### Define Discord.js Client Entrypoint Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Creates the main application file that exports the discord.js client instance. CommandKit automatically handles client login and token management. Intents must be specified for the client. ```typescript import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds'], }); client.token = '...'; // Optional: Manually set a bot token export default client; ``` ```javascript import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds'], }); client.token = '...'; // Optional: Manually set a bot token export default client; ``` -------------------------------- ### CommandKit Application Entry Point (TypeScript) Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Shows the `src/app.ts` file, which serves as the main entry point for a CommandKit application. It initializes a discord.js client with specified intents and optionally sets the bot token. CommandKit handles the client login process automatically. ```typescript import { Client } from 'discord.js'; const client = new Client({ intents: ['Guilds', 'GuildMessages', 'MessageContent'], }); // Optional: Setting up the token manually client.token = process.env.MY_BOT_TOKEN; export default client; ``` -------------------------------- ### CommandKit Project Structure Overview Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Illustrates a typical file tree structure for a CommandKit project created via the CLI. Key directories include `src/app/commands` and `src/app/events`, with core files like `src/app.ts`, `.env`, `.gitignore`, `commandkit.config.ts`, `package.json`, and `tsconfig.json`. ```treeview . ├── src/ │ ├── app/ │ │ ├── commands/ │ │ │ └── ping.ts │ │ └── events/ │ │ └── clientReady/ │ │ └── log.ts │ └── app.ts ├── .env ├── .gitignore ├── commandkit.config.ts ├── package.json └── tsconfig.json ``` -------------------------------- ### Create CommandKit Project using Development Version Source: https://commandkit.dev/docs/guide/getting-started/setup-commandkit Instructions for creating a CommandKit project using the latest development build, indicated by the `@dev` tag. This applies to various package managers including npm, Yarn, pnpm, and Bun. ```bash npm create commandkit@dev yarn create commandkit@dev pnpm create commandkit@dev bunx create-commandkit@dev ``` -------------------------------- ### Configure CommandKit with defineConfig Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Sets up the CommandKit configuration file. This file is essential for configuring CommandKit and its plugins. The `defineConfig` function is used to create the configuration object. ```typescript import { defineConfig } from 'commandkit'; export default defineConfig({}); ``` ```javascript import { defineConfig } from 'commandkit'; export default defineConfig({}); ``` -------------------------------- ### Basic Translation File Example Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-i18n Provides an example of a basic translation file for a command, containing keys for different response scenarios like 'response', 'error', and 'database_response'. These keys can be used within the bot's code to fetch localized strings. ```json { "response": "🏓 Pong! Latency: **{{latency}}ms**", "error": "❌ Failed to ping the server", "database_response": "📊 Database latency: **{{dbLatency}}ms**" } ``` -------------------------------- ### Install CommandKit Queue Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-queue Installs the CommandKit Queue package. For Discord.js integration with Redis, additional packages are required. ```bash npm install @commandkit/queue@next ``` ```bash npm install @commandkit/queue@next @discordjs/brokers ioredis ``` -------------------------------- ### Install CommandKit v1 (Bun) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Installs the latest v1 version of CommandKit using Bun. This command updates your package.json to include the new version. ```bash bun add commandkit@next ``` -------------------------------- ### Install CommandKit CLI API (Bun) Source: https://commandkit.dev/docs/guide/advanced/using-cli-api Installs the next version of CommandKit, which includes the CLI API, using Bun. Bun is a fast all-in-one JavaScript runtime. ```bash bun add commandkit@next ``` -------------------------------- ### Configure Redis Connection Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-queue Demonstrates various ways to configure a Redis connection using the ioredis library, including local and cloud-based setups. ```typescript import Redis from 'ioredis'; // Local Redis const redis = new Redis(); // Or with configuration const redis = new Redis({ host: 'localhost', port: 6379, password: 'your-password', db: 0, }); // Cloud Redis (example with Redis Cloud) const redis = new Redis({ host: 'your-redis-host.redis.cloud.com', port: 6379, password: 'your-redis-password', tls: {}, }); ``` -------------------------------- ### Install @commandkit/legacy with Bun Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-legacy Installs the @commandkit/legacy package using Bun. This command adds the legacy plugin to your project's dependencies. ```bash bun add @commandkit/legacy@next ``` -------------------------------- ### Install Google AI SDK Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-ai Installs the Google AI SDK, required for using Google Gemini models with the @commandkit/ai plugin. Choose the package manager that suits your project. ```bash npm install @ai-sdk/google ``` ```bash yarn add @ai-sdk/google ``` ```bash pnpm add @ai-sdk/google ``` ```bash bun add @ai-sdk/google ``` -------------------------------- ### Implement `onBeforeClientLogin` Hook in TypeScript Source: https://commandkit.dev/docs/guide/creating-plugins/creating-runtime-plugin Provides an example of the `onBeforeClientLogin` hook, which is called just before the Discord client attempts to log in. This hook is useful for performing last-minute setup or checks before the bot connects. It receives the runtime context `ctx`. ```typescript async onBeforeClientLogin(ctx: CommandKitPluginRuntime): Promise { console.log('Bot is about to connect to Discord...'); // Last minute preparations before login } ``` -------------------------------- ### Cache Database Queries Example Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-cache Illustrates caching database queries using 'use cache', 'cacheTag', and 'cacheLife'. This example caches user profiles and sets a cache duration of 1 hour, suitable for data that does not change frequently. ```typescript async function getUserProfile(userId: string) { 'use cache'; cacheTag(`user:${userId}`); cacheLife('1h'); // User profiles don't change often return await db.users.findOne({ where: { id: userId }, include: ['profile', 'settings'], }); } ``` -------------------------------- ### Install CommandKit CLI API (npm) Source: https://commandkit.dev/docs/guide/advanced/using-cli-api Installs the next version of CommandKit, which includes the CLI API, using npm. This is the first step to using the programmatic interface. ```bash npm install commandkit@next ``` -------------------------------- ### Install @commandkit/ai Plugin Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-ai Installs the @commandkit/ai plugin for various package managers. This is the first step to enable AI-powered command execution in your bot. ```bash npm install @commandkit/ai@next ``` ```bash yarn add @commandkit/ai@next ``` ```bash pnpm add @commandkit/ai@next ``` ```bash bun add @commandkit/ai@next ``` -------------------------------- ### Setup Redis Driver for CommandKit Queue Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-queue Configures and sets the Redis PubSub driver for CommandKit Queue, enabling inter-service communication via Redis. ```typescript import { setDriver } from '@commandkit/queue'; import { RedisPubSubDriver } from '@commandkit/queue/discordjs'; import { PubSubRedisBroker } from '@discordjs/brokers'; import Redis from 'ioredis'; // Create a Redis connection const redis = new Redis(); // Create a broker const broker = new PubSubRedisBroker(redis); // Create a driver const driver = new RedisPubSubDriver(broker); // Set the driver setDriver(driver); ``` -------------------------------- ### Cache API Responses Example Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-cache Provides an example of caching API responses using 'use cache', 'cacheTag', and 'cacheLife'. This specific example caches game statistics and sets the cache duration to 30 minutes, aligning with the API's update frequency. ```typescript async function fetchGameStats(gameId: string) { 'use cache'; cacheTag(`game:${gameId}`); cacheLife('30m'); // API updates every 30 minutes const response = await fetch(`https://api.game.com/stats/${gameId}`); return response.json(); } ``` -------------------------------- ### Install @commandkit/cache Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-cache Installs the @commandkit/cache package for npm, Yarn, pnpm, and Bun. This is the first step to enable the caching system in your CommandKit project. ```bash npm install @commandkit/cache@next ``` ```bash yarn add @commandkit/cache@next ``` ```bash pnpm add @commandkit/cache@next ``` ```bash bun add @commandkit/cache@next ``` -------------------------------- ### Start Workflow from Command Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-workflow Initiates a workflow from a CommandKit chat input command. It uses the `start` function from `workflow/api` to execute the `greetUserWorkflow` with the user's ID. ```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]); }; ``` -------------------------------- ### Install @commandkit/i18n with Bun Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-i18n Installs the next release candidate version of the @commandkit/i18n package using Bun. Bun is a fast JavaScript runtime, bundler, transpiler, and package manager. ```bash bun add @commandkit/i18n@next ``` -------------------------------- ### Send Messages with Appropriate Sizes Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-queue Illustrates the importance of using appropriate message sizes when sending data. It shows an example of a reasonable message size and contrasts it with an example of a very large message that should be avoided. ```javascript // Good - reasonable message size await send('user-profile-updates', { userId: '123', changes: { displayName: 'New Name', avatar: 'https://example.com/avatar.jpg', }, }); // Avoid - very large messages await send('user-profile-updates', { userId: '123', fullProfile: { /* massive object */ }, }); ``` -------------------------------- ### Install CommandKit CLI API (Yarn) Source: https://commandkit.dev/docs/guide/advanced/using-cli-api Installs the next version of CommandKit, which includes the CLI API, using Yarn. This command is an alternative to npm for package management. ```bash yarn add commandkit@next ``` -------------------------------- ### Workflow vs. Step Organization (TypeScript) Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-workflow Illustrates the best practice of separating workflow orchestration from step execution. The 'Good' example shows a workflow calling steps for distinct tasks, while the 'Avoid' example shows a workflow performing actual work, which should be delegated to steps. ```typescript // Good - workflow orchestrates, steps do work export async function memberVerificationWorkflow( userId: string, guildId: string, ) { 'use workflow'; const member = await fetchMember(userId, guildId); const verified = await verifyMember(member); return { userId, verified, status: 'completed' }; } // Avoid - doing too much in the workflow export async function badWorkflow(userId: string) { 'use workflow'; // Don't do actual work here - use steps instead const user = await fetch('...'); // ❌ } ``` -------------------------------- ### Basic CommandKit Setup with Tasks Plugin Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-tasks Configures CommandKit to use the tasks plugin. This involves importing defineConfig and tasks, then including tasks() in the plugins array. ```typescript import { defineConfig } from 'commandkit'; import { tasks } from '@commandkit/tasks'; export default defineConfig({ plugins: [tasks()], }); ``` -------------------------------- ### User Onboarding Workflow Example Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-workflow An advanced workflow demonstrating a multi-step user onboarding process. It includes sending messages, assigning roles, and scheduling a follow-up message after a delay. ```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' }; } ``` -------------------------------- ### Run CommandKit in Development Mode (npm, Yarn, pnpm, Bun) Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Starts the CommandKit application in development mode, enabling Hot Module Replacement (HMR) for faster iteration. This command is compatible with npm, Yarn, pnpm, and Bun package managers. A `.commandkit` folder will be generated and should be ignored by version control. ```bash npx commandkit dev ``` ```bash yarn dlx commandkit dev ``` ```bash pnpm dlx commandkit dev ``` ```bash bun x commandkit dev ``` -------------------------------- ### Custom Development Server with CommandKit CLI API Source: https://commandkit.dev/docs/guide/advanced/using-cli-api This example shows how to set up a custom development server using the CommandKit CLI API. It allows for setting custom environment variables, bootstrapping the server, and adding custom file watchers for real-time updates. ```typescript import { development, env } from 'commandkit/cli'; async function customDevServer() { // Set custom environment variables process.env.CUSTOM_DEV_FLAG = 'true'; // Bootstrap development server const devServer = await development.bootstrapDevelopmentServer( './commandkit.config.ts', ); // Add custom file watchers devServer.watcher.on('change', (path) => { console.log(`File changed: ${path}`); // Custom logic here }); // Access the running process const process = devServer.getProcess(); return devServer; } customDevServer(); ``` -------------------------------- ### Install CommandKit v1 (pnpm) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Installs the latest v1 version of CommandKit using pnpm. This command updates your package.json to include the new version. ```bash pnpm add commandkit@next ``` -------------------------------- ### Install CommandKit v1 (Yarn) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Installs the latest v1 version of CommandKit using Yarn. This command updates your package.json to include the new version. ```bash yarn add commandkit@next ``` -------------------------------- ### Install CommandKit v1 (npm) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Installs the latest v1 version of CommandKit using npm. This command updates your package.json to include the new version. ```bash npm install commandkit@next ``` -------------------------------- ### Configuring Multiple AI Providers Dynamically Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-ai Illustrates how to set up and dynamically select between multiple AI providers (Google Generative AI and OpenAI) based on message channel ID, with configurable max steps for each. ```typescript import { createGoogleGenerativeAI } from '@ai-sdk/google'; import { createOpenAI } from '@ai-sdk/openai'; const google = createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY, }); const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY, }); configureAI({ selectAiModel: async (ctx, message) => { // Use different models for different channels if (message.channelId === 'premium-channel-id') { return { model: openai('gpt-4'), maxSteps: 10, }; } // Default to Google Gemini return { model: google.languageModel('gemini-2.0-flash'), maxSteps: 5, }; }, }); ``` -------------------------------- ### Build CommandKit for Production (npm) Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Creates a production-ready build of the CommandKit application. This command generates a `dist` folder containing compiled files, which should be excluded from version control. ```bash npx commandkit build ``` -------------------------------- ### Create a Ping/Pong Command Source: https://commandkit.dev/docs/guide/advanced/setup-commandkit-manually Defines a command that responds with 'Pong!' to both chat input (slash) commands and message commands. It includes the command data and handlers for both interaction types. ```typescript 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!'); }; ``` ```javascript /** * @typedef {import('commandkit').ChatInputCommand} ChatInputCommand * @typedef {import('commandkit').CommandData} CommandData * @typedef {import('commandkit').MessageCommand} MessageCommand */ /** @type {CommandData} */ export const command = { name: 'ping', description: 'Pong!', }; /** @type {ChatInputCommand} */ export const chatInput = async ({ interaction }) => { await interaction.reply('Pong!'); }; /** @type {MessageCommand} */ export const message = async ({ message }) => { await message.reply('Pong!'); }; ``` -------------------------------- ### v1 Streamlined Entry Point (TypeScript) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Illustrates the v1 entry point transformation in TypeScript. You now export a configured Discord.js client, and CommandKit handles the rest, simplifying bot initialization. ```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 ``` -------------------------------- ### Install @commandkit/devtools with npm Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-devtools Installs the @commandkit/devtools plugin using npm. This command fetches the latest release candidate version of the package. ```bash npm install @commandkit/devtools@next ``` -------------------------------- ### Control Async Queue State (Pause, Resume) in JavaScript Source: https://commandkit.dev/docs/guide/useful-utilities/commandkit-async-queue Shows how to manage the state of a CommandKit async queue. This example demonstrates pausing the queue, adding tasks that will wait for resumption, and then resuming execution. It also shows how to check the queue's running, pending, and paused status. ```javascript import { createAsyncQueue } from 'commandkit/async-queue'; const queue = createAsyncQueue({ concurrency: 2 }); // Pause the queue queue.pause(); // Add tasks (they won't execute until resumed) const promise1 = queue.add(async () => await task1()); const promise2 = queue.add(async () => await task2()); // Resume the queue queue.resume(); // Check queue status console.log(`Running: ${queue.getRunning()}`); console.log(`Pending: ${queue.getPending()}`); console.log(`Paused: ${queue.isPaused()}`); ``` -------------------------------- ### Create Production Build and Bootstrap Server (JavaScript) Source: https://commandkit.dev/docs/guide/advanced/using-cli-api Utilizes the `production` module from `commandkit/cli` to first create an optimized production build of the application and then bootstrap the production server. Both operations require a configuration path. ```javascript 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', ); ``` -------------------------------- ### Install @commandkit/analytics Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-analytics Installs the @commandkit/analytics package using npm, yarn, pnpm, or bun. This is the first step to integrating analytics into your CommandKit project. ```bash npm install @commandkit/analytics@next ``` ```bash yarn add @commandkit/analytics@next ``` ```bash pnpm add @commandkit/analytics@next ``` ```bash bun add @commandkit/analytics@next ``` -------------------------------- ### v1 Simplified Configuration (TypeScript) Source: https://commandkit.dev/docs/guide/advanced/migrating-from-v0 Demonstrates the simplified v1 configuration file in TypeScript. CommandKit v1 automatically detects the project structure, making explicit configuration often optional. ```typescript import { defineConfig } from 'commandkit'; export default defineConfig({ // Configuration is now optional for most use cases // CommandKit automatically detects your app structure }); ``` -------------------------------- ### Configuring KV Store Options in JavaScript Source: https://commandkit.dev/docs/guide/useful-utilities/commandkit-kv Shows how to customize the CommandKit KV store using the `openKV` function. This includes specifying a custom database file, using an in-memory store for testing, and creating stores with specific namespaces. ```javascript 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', }); ``` -------------------------------- ### Install @commandkit/legacy with pnpm Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-legacy Installs the @commandkit/legacy package using pnpm. This command adds the legacy plugin to your project's dependencies. ```bash pnpm add @commandkit/legacy@next ``` -------------------------------- ### Install @commandkit/legacy with Yarn Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-legacy Installs the @commandkit/legacy package using Yarn. This command adds the legacy plugin to your project's dependencies. ```bash yarn add @commandkit/legacy@next ``` -------------------------------- ### Install @commandkit/tasks Plugin Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-tasks Installs the CommandKit tasks plugin using npm. This command is essential for adding the tasks functionality to your project. ```bash npm install @commandkit/tasks@next ``` -------------------------------- ### Create and Use Sequential Async Queue in JavaScript Source: https://commandkit.dev/docs/guide/useful-utilities/commandkit-async-queue Demonstrates the basic usage of CommandKit's async queue for sequential task processing. It shows how to import the function, create a default queue, and add asynchronous tasks to it, retrieving their results. ```javascript import { createAsyncQueue } from 'commandkit/async-queue'; // Create a sequential queue (default) const queue = createAsyncQueue(); // Add tasks to the queue const result1 = await queue.add(async () => { return await processTask1(); }); const result2 = await queue.add(async () => { return await processTask2(); }); ``` -------------------------------- ### Basic KV Store Usage in JavaScript Source: https://commandkit.dev/docs/guide/useful-utilities/commandkit-kv Demonstrates the fundamental operations of the CommandKit KV store, including creating an instance, setting key-value pairs, and retrieving values. It supports storing various JSON-serializable data types. ```javascript 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 ``` -------------------------------- ### Install @commandkit/devtools with pnpm Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-devtools Installs the @commandkit/devtools plugin using pnpm. This command ensures the latest release candidate version of the package is added to your project. ```bash pnpm add @commandkit/devtools@next ``` -------------------------------- ### Install @commandkit/devtools with Yarn Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-devtools Installs the @commandkit/devtools plugin using Yarn. This command adds the latest release candidate version of the package to your project dependencies. ```bash yarn add @commandkit/devtools@next ``` -------------------------------- ### Install @commandkit/legacy with npm Source: https://commandkit.dev/docs/guide/official-plugins/commandkit-legacy Installs the @commandkit/legacy package using npm. This command is used to add the legacy plugin to your project's dependencies. ```bash npm install @commandkit/legacy@next ``` -------------------------------- ### Create a Basic Runtime Plugin in TypeScript Source: https://commandkit.dev/docs/guide/creating-plugins/creating-runtime-plugin Demonstrates how to create a basic runtime plugin by extending the `RuntimePlugin` class from CommandKit. This example shows how to override the `onAfterClientLogin` hook to log a message when the bot successfully logs in. It requires the 'commandkit' package. ```typescript import { type CommandKitPluginRuntime, RuntimePlugin } from 'commandkit'; export class MyRuntimePlugin extends RuntimePlugin { // Override any hooks you want to use async onAfterClientLogin(ctx: CommandKitPluginRuntime): Promise { console.log('Bot has logged in!'); } } ```