Compare commits

...

5 commits

Author SHA1 Message Date
8ec15b7803
* language relative to user, not global anymore
* add comments
* store all the localizations instead of unique one
* move localization function to utils/ folder
2022-07-21 15:13:39 +02:00
1b4a594880
relative locale 2022-07-21 15:11:49 +02:00
0f2078b794
static string 2022-07-21 15:10:54 +02:00
d3aee129e0
locales relative to user 2022-07-21 15:10:48 +02:00
6830f5ffd9
turn string to static ones 2022-07-21 15:10:14 +02:00
9 changed files with 22 additions and 64 deletions

View file

@ -35,7 +35,6 @@ services:
| Nom | Commentaire | Valeur par défaut | Nom | Commentaire | Valeur par défaut
| :-----------: | :-----------: | :-: | :-----------: | :-----------: | :-:
| TOKEN_DISCORD | Token Discord | Aucune | TOKEN_DISCORD | Token Discord | Aucune
| LANGUAGE | Langue du bot | en
--- ---
### Références ### Références

View file

@ -25,9 +25,9 @@ export default async (client: Client) => {
).default; ).default;
// Add it to the collection so the interaction will work // Add it to the collection so the interaction will work
client.commands.set(command.data.name, command); client.commands.set(command.data(client).name, command);
return command.data.toJSON(); return command.data(client).toJSON();
}), }),
); );
}), }),

View file

@ -1,19 +1,20 @@
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from '@discordjs/builders';
import { Client, CommandInteraction, Message } from 'discord.js'; import { Client, CommandInteraction, Message } from 'discord.js';
import { getLocale } from '../../utils/locales';
export default { export default {
data: new SlashCommandBuilder() data: (client: Client) => new SlashCommandBuilder()
.setName('ping') .setNameLocalizations(getLocale(client, 'ping_name'))
.setDescription('Pong!'), .setDescriptionLocalizations(getLocale(client, 'ping_desc')),
interaction: async (interaction: CommandInteraction, client: Client) => { interaction: async (interaction: CommandInteraction, client: Client) => {
const loc = client.locale; const loc = client.locales.get(interaction.locale) ?? client.locales.get(client.config.default_lang);
const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true }) as Message; const sent = await interaction.reply({ content: 'Pinging...', fetchReply: true }) as Message;
interaction.editReply( interaction.editReply(
`${loc.get('c_ping1')}: \ `${loc?.get('c_ping1')}: \
${sent.createdTimestamp - interaction.createdTimestamp}ms ${sent.createdTimestamp - interaction.createdTimestamp}ms
${loc.get('c_ping2')}: ${client.ws.ping}ms.`); ${loc?.get('c_ping2')}: ${client.ws.ping}ms.`);
}, },
}; };

View file

@ -1,8 +1,6 @@
import { Client } from 'discord.js';
export const once = true; export const once = true;
/** https://discord.js.org/#/docs/discord.js/main/class/Client?scrollTo=e-ready */ /** https://discord.js.org/#/docs/discord.js/main/class/Client?scrollTo=e-ready */
export default async (client: Client) => { export default async () => {
console.log(client.locale.get('e_ready')); console.log('Connected to Discord!');
}; };

View file

@ -6,7 +6,7 @@ export default (interaction: Interaction, client: Client) => {
const command = client.commands.get(interaction.commandName); const command = client.commands.get(interaction.commandName);
if (!command) { if (!command) {
return interaction.reply({ return interaction.reply({
content: client.locale.get('e_interacreate'), content: client.locales.get(interaction.locale)?.get('e_interacreate'),
ephemeral: true, ephemeral: true,
}); });
} }

View file

@ -40,7 +40,7 @@ const run = async () => {
throw logStart(commands_name, false); throw logStart(commands_name, false);
}); });
console.log(`Botanique "${client.user?.username}" v${client.config.version} ${client.locale.get('started')}!`); console.log(`Botanique "${client.user?.username}" v${client.config.version} started!`);
}) })
.catch(() => { .catch(() => {
throw logStart(client_name, false); throw logStart(client_name, false);

View file

@ -1,10 +1,6 @@
{ {
"started": "started",
"e_interacreate": "Sorry, the command probably no longer exists...", "e_interacreate": "Sorry, the command probably no longer exists...",
"e_ready": "Connected to Discord!",
"c_ping1": "Roundtrip latency", "c_ping1": "Roundtrip latency",
"c_ping2": "Websocket heartbeat" "c_ping2": "Websocket heartbeat"
} }

View file

@ -1,10 +1,6 @@
{ {
"started": "démarré ",
"e_interacreate": "Désolé, la commande n'existe plus...", "e_interacreate": "Désolé, la commande n'existe plus...",
"e_ready": "Connecté à Discord !",
"c_ping1": "Latence totale", "c_ping1": "Latence totale",
"c_ping2": "Latence du Websocket" "c_ping2": "Latence du Websocket"
} }

View file

@ -1,17 +1,20 @@
import { Client, Collection, Intents } from 'discord.js'; import { Client, Collection, Intents } from 'discord.js';
import { readFileSync, existsSync } from 'fs'; import { readFileSync } from 'fs';
import { SlashCommandBuilder } from '@discordjs/builders'; import { SlashCommandBuilder } from '@discordjs/builders';
import { loadLocales } from './locales';
const { version } = JSON.parse(readFileSync('./package.json').toString()); const { version } = JSON.parse(readFileSync('./package.json').toString());
declare module 'discord.js' { declare module 'discord.js' {
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
export interface Client { export interface Client {
/** Store the configuration */
config: { config: {
version: string, version: string,
token_discord: string | undefined, token_discord: string | undefined,
lang: string default_lang: string
}, },
/** Store all the slash commands */
commands: Collection< commands: Collection<
string, string,
{ {
@ -19,7 +22,8 @@ declare module 'discord.js' {
interaction: (interaction: CommandInteraction, client: Client) => unknown interaction: (interaction: CommandInteraction, client: Client) => unknown
} }
>, >,
locale: Map<string, string> /** Store all the localizations */
locales: Map<string, Map<string, string>>
} }
} }
@ -31,51 +35,15 @@ export default async () => {
], ],
}); });
// Store the client configuration
client.config = { client.config = {
version: version, version: version,
token_discord: process.env.TOKEN_DISCORD, token_discord: process.env.TOKEN_DISCORD,
lang: process.env.LANGUAGE ?? '', default_lang: 'en-US',
}; };
// Store the commands available
client.commands = new Collection(); client.commands = new Collection();
// Store all the strings client.locales = await loadLocales(client.config.default_lang);
client.locale = await getLocale(client);
return client; return client;
}; };
/**
* Get all the strings corresponding to the locales specified in env variable
* @returns Collection of strings
*/
const getLocale = async (client: Client) => {
const default_lang = 'en-US';
// Check if there is a defined valid value
const old_path = __dirname.split('/');
old_path.pop();
const lang = client.config.lang === undefined ? default_lang : existsSync(
`${old_path.join('/')}/locales/${client.config.lang}.json`,
) ? client.config.lang : default_lang;
// Fallback to default language in case lang isn't valid
if (client.config.lang !== lang) {
client.config.lang = lang;
}
const file: {
[key: string]: string
} = await import(
`../locales/${lang}.json`
);
return new Map(
Object.keys(file).map(key => {
return [key, file[key]];
}),
);
};