forked from SlashBotDiscord/i18n
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (35 loc) · 1.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const {readdirSync, readFileSync} = require("fs")
class SlashBotLocalizationManager {
#languages = {}
constructor() {
this.loadLanguages()
}
get languages() {
return this.#languages
}
loadLanguages() {
let i18n = {};
readdirSync(`${__dirname}/localizations`)
.filter((f) => f.replace(".json", "").length === 2)
.forEach((f) => {
i18n[f.replace(".json", "")] = JSON.parse(
readFileSync(`${__dirname}/localizations/${f}`).toString("utf-8")
);
});
this.language
this.#languages = i18n
}
getTranslation(locale, key, ...args) {
let language = locale
language = language.split("-")[0]
if (!(language in this.languages)) language = "en";
const strings = this.languages[language],
english = this.languages["en"];
let value;
if (key in strings) value = strings[key];
if (!value && key in english) value = english[key];
if (!value) throw new Error("Unknown key " + key);
return value.replace(/{(\d+)}/g, (_, i) => args[i]?.toString() ?? _);
}
}
module.exports = {SlashBotLocalizationManager}