Skip to main content

💬 Command CustomId Codec

The CommandCustomIdCodec is the object responsible for encoding and decoding command custom ids. That is, custom ids that refer to commands. With this object you can easily create components that will trigger commands when they are used. It's stored by a CommandManager, and you can get it via CommandManager#getCustomIdCodec().

danger

It's advised that you only use this API for simple user actions. If you're looking for something more complex, you should use a dedicated handler or the 👤 Sessions API.

✨ Examples

🚧 Usage examples

These are short examples on how the API is used overall. For "real world" examples, read the next section.

// Get the command instance
const myCommand = commandManager.getRepository().locateByTree(MyCommandClass);
if (!myCommand) throw new Error('Command not found');

// Get the customId
const customIdCodec = commandManager.getCustomIdCodec();
const customId = customIdCodec.serializeToCustomId(myCommand);

✅ Implementation examples

These are "real world" examples on how the API can be used. For "short", concrete examples, read the last section.

// Assume this command is registered
class PingCommand extends AbstractStandaloneCommand {
public async handleInteraction(interaction: ComponentCommandInteraction) {
await interaction.reply('Pong!');
}
}

class MyReferralCommand extends AbstractStandaloneCommand {
public async execute(
interaction: ChatInputCommandInteraction,
metadata: CommandExecutionMeta,
) {
const bot = metadata.getBot();
const commandManager = bot.getCommandManager();

// Get the command instance
const pingCommand = commandManager.getRepository().locateByTree(PingCommand);
if (!pingCommand) throw new Error('Ping command not found');

// Get the customId
const customIdCodec = bot.getCommandManager().getCustomIdCodec();
const customId = customIdCodec.serializeToCustomId(pingCommand);

// Create your component

const button = new ButtonBuilder()
// When this button is clicked, it will trigger PingCommand#handleInteraction()
.setCustomId(customId)
.setLabel('Click to check your ping!')
.setStyle(ButtonStyle.Primary);

const row = new ActionRowBuilder().addComponents(button);
await interaction.reply({ components: [row] });
}
}

👷 Creation

You can create a command custom ID codec by either:

  • Extending DefaultCommandCustomIdCodec from @framework (recommended).
  • Implementing the CommandCustomIdCodec interface from @core.
class MyCommandCustomIdCodec extends DefaultCommandCustomIdCodec {
// ...
}

const myCodec = new MyCommandCustomIdCodec();

const myBot = Bot.create((bot) => ({
commands: DefaultCommandManager.create(bot, client, clientBus, { customIdCodec: myCodec }),
}));