Compare commits

..

4 commits

Author SHA1 Message Date
8f0096a73c
* load locales into the client
* extract specific text from locales and fallback to en-US in case of failure
2022-07-21 17:10:25 +02:00
2bde673cb1
don't require default language 2022-07-21 17:09:47 +02:00
a819ed0ea8
use localization 2022-07-21 17:09:34 +02:00
4c42fa101b
Add Ping command name and desc 2022-07-21 17:09:18 +02:00
4 changed files with 64 additions and 3 deletions

View file

@ -4,8 +4,8 @@ import { getLocale } from '../../utils/locales';
export default {
data: (client: Client) => new SlashCommandBuilder()
.setNameLocalizations(getLocale(client, 'ping_name'))
.setDescriptionLocalizations(getLocale(client, 'ping_desc')),
.setNameLocalizations(getLocale(client, 'c_ping_name'))
.setDescriptionLocalizations(getLocale(client, 'c_ping_desc')),
interaction: async (interaction: CommandInteraction, client: Client) => {
const loc = client.locales.get(interaction.locale) ?? client.locales.get(client.config.default_lang);

View file

@ -1,6 +1,8 @@
{
"e_interacreate": "Sorry, the command probably no longer exists...",
"c_ping_name": "Ping",
"c_ping_desc": "Pong",
"c_ping1": "Roundtrip latency",
"c_ping2": "Websocket heartbeat"
}

View file

@ -43,7 +43,7 @@ export default async () => {
client.commands = new Collection();
client.locales = await loadLocales(client.config.default_lang);
client.locales = await loadLocales();
return client;
};

59
src/utils/locales.ts Normal file
View file

@ -0,0 +1,59 @@
import { Client } from 'discord.js';
import { readdir } from 'fs/promises';
/**
* Load the localizations files
*/
export const loadLocales = async () => {
// Check if there is a defined valid value
const old_path = __dirname.split('/');
old_path.pop();
const files = await readdir(`${old_path.join('/')}/locales`);
const locales = new Map();
await Promise.all(
files.map(async lang => {
const content: {
[key: string]: string
} = await import(
`../locales/${lang}`
);
locales.set(
lang.split('.')[0],
new Map(
Object.keys(content).map(str => {
return [str, content[str]];
}),
)
);
})
);
return locales;
};
/**
* Builds a dictionary, if a translation is not available,
* we fallback to en-US.
* @param client Client
* @param text Name of string to fetch
* @returns the dictionary
*/
export const getLocale = (client: Client, text: string) => {
const data: Record<string, string> = {};
client.locales.forEach((locale, lang) => {
const str = locale.get(text)
?? client.locales.get(client.config.default_lang)?.get(text);
if (str === undefined) {
throw 'Missing locales';
}
data[lang] = str;
});
return data;
};