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:
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
.
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:
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);
});
});
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
- Caching: Use CommandKit's built-in caching system to reduce database queries
- Fallback: Always provide a default prefix as fallback
- Validation: Consider adding prefix validation to prevent conflicts
- Performance: Cache frequently used prefixes to improve response time
Example with Validation
Here's a more robust implementation with validation:
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);
});
The prefix resolver is called for every message, so ensure your implementation is efficient and properly cached when possible.
Avoid using prefixes that might conflict with other bots or common Discord features. For example, /
is reserved for slash commands.