Skip to main content
Version: Next

Custom command prefixes

Message commands in Discord bots traditionally use prefixes to distinguish commands from regular messages. CommandKit allows you to customize these prefixes to suit your bot's needs.

Basic Usage

The simplest way to set a custom prefix is using the setPrefixResolver method:

src/app.ts
import { commandkit } from 'commandkit';

commandkit.setPrefixResolver(async (message) => {
return '?';
});

This sets a global prefix of ? for all message commands. Your bot will now respond to commands like ?help or ?ping.

tip

You can return an array of strings to support multiple prefixes simultaneously:

return ['?', '!', '>'];

Advanced Usage

Guild-Specific Prefixes

For more complex applications, you might want different prefixes for different servers. Here's how to implement that:

src/app.ts
import { onApplicationBootstrap, cacheTag } from 'commandkit';
import { database } from '../database.ts';

async function fetchGuildPrefix(guildId: string) {
'use cache';

// Tag the cache with the guild ID for proper cache invalidation
cacheTag(`prefix:${guildId}`);

const setting = await database.findUnique({
where: { guildId },
select: { prefix: true },
});

return setting?.prefix ?? '!';
}

onApplicationBootstrap((commandkit) => {
commandkit.setPrefixResolver((message) => {
return fetchGuildPrefix(message.guildId);
});
});
info

The "use cache" directive is a custom directive that tells CommandKit to cache the result of the function automatically. See the Caching in CommandKit guide for more details.

Best Practices

  1. Caching: Use CommandKit's built-in caching system to reduce database queries
  2. Fallback: Always provide a default prefix as fallback
  3. Validation: Consider adding prefix validation to prevent conflicts
  4. Performance: Cache frequently used prefixes to improve response time

Example with Validation

Here's a more robust implementation with validation:

src/app.ts
import { commandkit, cacheTag } from 'commandkit';
import { database } from '../database.ts';

const DEFAULT_PREFIX = '!';
const MAX_PREFIX_LENGTH = 5;

async function fetchGuildPrefix(guildId: string) {
'use cache';
cacheTag(`prefix:${guildId}`);

const setting = await database.findUnique({
where: { guildId },
select: { prefix: true },
});

const prefix = setting?.prefix ?? DEFAULT_PREFIX;

// Validate prefix
if (prefix.length > MAX_PREFIX_LENGTH) {
return DEFAULT_PREFIX;
}

return prefix;
}

commandkit.setPrefixResolver((message) => {
return fetchGuildPrefix(message.guildId);
});
note

The prefix resolver is called for every message, so ensure your implementation is efficient and properly cached when possible.

warning

Avoid using prefixes that might conflict with other bots or common Discord features. For example, / is reserved for slash commands.