Skip to main content
Version: Next

i18n Plugin

The i18n plugin integrates i18next into CommandKit, allowing you to internationalize your Discord bot and translate your commands, responses, and other content into multiple languages.

Installation

npm install @commandkit/i18n

Basic Setup

Add the i18n plugin to your CommandKit configuration:

import { defineConfig } from 'commandkit';
import { i18n } from '@commandkit/i18n';

export default defineConfig({
plugins: [i18n()],
});

Advanced Configuration

You can customize the i18n plugin by passing options to it:

import { defineConfig } from 'commandkit';
import { i18n } from '@commandkit/i18n';
// Import any i18next plugins you want to use
import someI18nextPlugin from 'some-i18next-plugin';

export default defineConfig({
plugins: [
i18n({
plugins: [someI18nextPlugin],
// Add other i18next configuration options as needed
}),
],
});

Translation Files Structure

Create a locales directory inside your src/app folder with subdirectories for each language. The directory structure should look like this:

src
└── app
├── locales
│ ├── en-US
│ │ └── ping.json
│ └── fr
│ └── ping.json
└── commands
└── ping.ts

Translation File Format

Translation files should be named after the command they translate. For example, the translation for a ping command would be in ping.json.

If your translation file contains the special $command key, it will be used to localize the command name, description, and options:

{
"$command": {
"name": "Ping",
"description": "Ping the server",
"options": [
{
"name": "database",
"description": "Ping the database"
}
]
},
"response": "Pong! The latency is {{latency}}ms"
}

The $command key is used to localize the command's metadata for Discord, while other keys are available for localizing command responses.

Using Translations in Commands

Use the locale() function in your command context to access translations:

export const chatInput: ChatInputCommand = async (ctx) => {
// Get translation function and i18next instance for the current guild's locale
const { t, i18n } = ctx.locale();

// Use the translation function with variables
ctx.interaction.reply({
content: t('response', { latency: ctx.client.ws.ping }),
ephemeral: true,
});
};

You can also specify a particular locale:

// Use French locale explicitly
const { t } = ctx.locale('fr');

Using Translations Outside Command Context

If you need to use translations outside of a command context (such as in legacy commands), you can import the locale function directly:

import { locale } from '@commandkit/i18n';

export async function run({ interaction, client }) {
// This function can infer the locale automatically
const { t } = locale();

return interaction.reply({
content: t('response', { latency: client.ws.ping }),
ephemeral: true,
});
}

This function works the same way as the one in the command context and can also infer the locale automatically based on the interaction.