Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Localisation - support interaction locales #48

Merged
merged 4 commits into from
Jan 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions commands/fun/trivia.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ exports.run = async (client, message, args) => {
// Category & Difficulty
// cat | diff
const embed = new MessageEmbed()
.setAuthor("Trivia", "https://i.imgur.com/Z20hATC.png")
.setAuthor({ name: "Trivia", iconURL: "https://i.imgur.com/Z20hATC.png" })
.setColor("#6f99ff")
.setDescription(stripIndents`
**${client.l10n(message, "trivia.embed.question")}**
Expand All @@ -132,7 +132,7 @@ exports.run = async (client, message, args) => {

**${client.l10n(message, "trivia.embed.catdiff")}**
${quiz.category} | ${quiz.difficulty.toTitleCase()}`)
.setFooter(client.l10n(message, "trivia.embed.footer"), message.author.displayAvatarURL())
.setFooter({ text: client.l10n(message, "trivia.embed.footer"), iconURL: message.author.displayAvatarURL() })
.setTimestamp();

// Wait 60 seconds (awaitReply default "limit" property value) for user's answer
Expand Down
4 changes: 2 additions & 2 deletions commands/info/about.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ exports.run = async (client, message) => {

const embed = new MessageEmbed()
.setColor("#56dcff")
.setAuthor(`delet ${deletVersion} - About`, client.user.displayAvatarURL())
.setAuthor({ name: `delet ${deletVersion} - About`, iconURL: client.user.displayAvatarURL() })
.setDescription(stripIndents`
👥 **Users**: ${client.users.cache.size} | 💬 **Servers**: ${client.guilds.cache.size} | 🕙 **Uptime**: ${uptimeDays} days, ${uptimeUtc.format("HH:mm:ss")}
🧠 **Memory usage**: ~${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed()}MB | 🔑 **Owner**: ${ownerTag} | 🌐 **Translators**: [see list](https://github.com/suvanl/delet3/#translations)`)
.setFooter(`Made with Discord.js ${version}`, "https://i.imgur.com/RWcHLuz.png")
.setFooter({ text: `Made with Discord.js ${version}`, iconURL: "https://i.imgur.com/RWcHLuz.png"})
.setTimestamp();

return message.reply({ embeds: [embed], ephemeral: true });
Expand Down
2 changes: 1 addition & 1 deletion commands/info/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ exports.run = async (client, message) => {
✅ **${client.l10n(message, "server.verif")}**
${client.l10n(message, "server.verif.lvl")} ${vLevels[guild.verificationLevel]}
${client.l10n(message, "server.cFilter.lvl")} ${cFilter[guild.explicitContentFilter]}`)
.setFooter(`${client.l10n(message, "server.id").replace(/%id%/g, guild.id)} | ${client.l10n(message, "utc")}`);
.setFooter({ text: `${client.l10n(message, "server.id").replace(/%id%/g, guild.id)} | ${client.l10n(message, "utc")}` });

message.channel.send({ embeds: [embed] });
};
Expand Down
2 changes: 1 addition & 1 deletion commands/info/spotify.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ exports.run = async (client, message, args) => {

🎼 ${keyTxt}: **${key}** • ${timeSignature}: **${afData.time_signature}/4** • ${tempo}: ${tempoValue}
🔢 ${danceability}: **${Math.round(afData.danceability * 10)}/10** • ${energy}: **${Math.round(afData.energy * 10)}/10** • ${acousticness}: **${Math.round(afData.acousticness * 10)}/10**`)
.setFooter(`${tData.album.name} • ${client.l10n(message, "spotify.releaseDate").replace(/%date%/g, releaseDate)}`);
.setFooter({ text: `${tData.album.name} • ${client.l10n(message, "spotify.releaseDate").replace(/%date%/g, releaseDate)}` });

return message.channel.send({ embeds: [embed] });
};
Expand Down
2 changes: 1 addition & 1 deletion commands/info/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ exports.run = async (client, message, args) => {

📋 **${client.l10n(message, "user.roles")}**
${roles.slice(0, 3).join(", ")} ${roles.length >= 4 ? client.l10n(message, "user.roles.more").replace(/%num%/g, roles.length - 3) : ""}`)
.setFooter(`${client.l10n(message, "user.id")}: ${member.id}`);
.setFooter({ text: `${client.l10n(message, "user.id")}: ${member.id}` });

message.channel.send({ embeds: [embed] });
};
Expand Down
2 changes: 1 addition & 1 deletion commands/info/weather.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ exports.run = async (client, message, args) => {

🌅 ${client.l10n(message, "weather.sunrise")}: **${sunrise}**
🌇 ${client.l10n(message, "weather.sunset")}: **${sunset}**`)
.setFooter(client.l10n(message, "weather.footer"), "https://i.imgur.com/OodcJh8.jpg");
.setFooter({ text: client.l10n(message, "weather.footer"), iconURL: "https://i.imgur.com/OodcJh8.jpg" });

message.channel.send({ embeds: [embed] });
};
Expand Down
2 changes: 1 addition & 1 deletion commands/misc/help.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ exports.run = async (client, message, args, level) => {

**aliases**
${cmd.config.aliases.length !== 0 ? cmd.config.aliases.map(a => `\`${a}\``).join(", ") : "`[ none ]`"}`)
.setFooter("< > = required parameter \u2022 [ ] = optional parameter");
.setFooter({ text: "< > = required parameter \u2022 [ ] = optional parameter" });

// Send the embed
message.channel.send({ embeds: [embed] });
Expand Down
2 changes: 1 addition & 1 deletion commands/moderation/ban.js
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ exports.run = async (client, message, args) => {
#️⃣ ${client.l10n(message, "mod.embed.userID").replace(/%id%/g, `**${user.id}**`)}
⌛ ${client.l10n(message, "mod.embed.duration").replace(/%dur%/g, `**${relative}**`)}
❔ ${client.l10n(message, "mod.embed.reason").replace(/%rsn%/g, `**${reason ? reason : client.l10n(message, "mod.ban.reason.null")}**`)}`)
.setFooter(`${issuedBy} • ${caseNumber}`, message.author.displayAvatarURL());
.setFooter({ text: `${issuedBy} • ${caseNumber}`, iconURL: message.author.displayAvatarURL() });

return modLog.send({ embeds: [embed] });
}
Expand Down
2 changes: 1 addition & 1 deletion commands/moderation/unban.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ exports.run = async (client, message, args) => {
👤 ${client.l10n(message, "mod.embed.member").replace(/%user%/g, `**${unban.tag}**`)}
#️⃣ ${client.l10n(message, "mod.embed.userID").replace(/%id%/g, `**${unban.id}**`)}
❔ ${client.l10n(message, "mod.embed.reason").replace(/%rsn%/g, `**${reason}**`)}`)
.setFooter(client.l10n(message, "mod.embed.issued").replace(/%user%/g, message.author.tag), message.author.displayAvatarURL());
.setFooter({ text: client.l10n(message, "mod.embed.issued").replace(/%user%/g, message.author.tag), iconURL: message.author.displayAvatarURL() });

// Send embed
return modLog.send({ embeds: [embed] });
Expand Down
50 changes: 45 additions & 5 deletions core/functions/l10n.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ const { readdirSync } = require("fs");
const { sep } = require("path");
const localeDir = `${process.cwd()}${sep}core${sep}locales`;

// Locales with regional variants in Discord's locale list
// Source: https://discord.com/developers/docs/dispatch/field-values#predefined-field-values-accepted-locales
const regional = [
"en-US",
"en-GB",
"zh-CN",
"zh-TW",
"pt-BR",
"es-ES",
"sv-SE"
];

module.exports = client => {
// Localisation (l10n)
// Language tag list: https://w.wiki/Lsd
Expand All @@ -10,13 +22,41 @@ module.exports = client => {
const localeFiles = readdirSync(localeDir);
const lf = localeFiles.map(file => file.split(".")[0]);

// If a locale file matching the value of the "locale" parameter can't be found, return an error message
if (!lf.includes(locale)) return client.logger.err(`Missing locale file: "${locale}"`);
// If the type of message is not an application command (assuming it is of type 'DEFAULT')...
if (message.type !== "APPLICATION_COMMAND") {
// If a locale file matching the value of the "locale" parameter can't be found, return an error message
if (!lf.includes(locale)) return client.logger.err(`Missing locale file: "${locale}"`);

// Define the locale file path
let locFile = require(`${localeDir}${sep}${locale}.json`);

// If the requested string key doesn't exist in the file, fall back to English (UK) [en-GB]
if (!locFile[str]) locFile = require(`${localeDir}${sep}en-GB.json`);

// Return the value of the specified key
return locFile[str];
}

// If the command is indeed an application command...
// Set the default locale to message.locale (docs: CommandInteraction.locale)
locale = message.locale;

// Define the locale file path
let locFile = require(`${localeDir}${sep}${locale}.json`);
let locFile;

// If the interaction locale doesn't have a locale file associated with it...
if (!lf.find(loc => loc.startsWith(locale))) {
// Fall back to en-GB
locFile = require(`${localeDir}${sep}en-GB.json`);
} else if (regional.includes(locale)) {
// If the interaction locale is in long-form (i.e., with a region tag), require the locale file
locFile = require(`${localeDir}${sep}${locale}.json`);
} else {
// If the interaction locale is in short-form (e.g., 'de'), find the first locale file name
// that starts with the short-form locale string
locFile = require(`${localeDir}${sep}${lf.find(loc => loc.startsWith(locale))}.json`);
}

// If a file does not exist at the specified path, fall back to English (UK) [en-GB]
// If the requested string key doesn't exist in the file, fall back to English (UK) [en-GB]
if (!locFile[str]) locFile = require(`${localeDir}${sep}en-GB.json`);

// Return the value of the specified key
Expand Down