Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make multi-languages in discord bot?

I have en.json and ru.json files, I use variables by type there:

levelupmessage: "Congratulations on the new $ {level}"

because in json you cannot put `` what needs to be done so that there is not just a string?

like image 962
KristalkillPlay Avatar asked Oct 22 '25 22:10

KristalkillPlay


1 Answers

You need to create a module that loads all messages from en.json and ru.json and saves them in an object. Then, create a function that finds the specified string inside your object. This function also replaces %VAR% with a parameter you pass to that function.

Take a look at this example:

let strings = {
   en: {
      // I prefer % for variables
      levelUp: "Congratulations on leveling up: %VAR%"
   },
   ru: {
      levelUp: "Поздравляем с новым уровнем: %VAR%"
   }
};

// Function to get locales and replace variables
function getLocale(language, string, ...vars) {
   let locale = strings[language][string];

   let count = 0;
   locale = locale.replace(/%VAR%/g, () => vars[count] !== null ? vars[count] : "%VAR%");

   return locale;
}

getLocale("en", "levelUp", "10");   // Congratulations on leveling up: 10
getLocale("ru", "levelUp", "10");   // Поздравляем с новым уровнем: 10

That's how many popular Discord bots handle internationalization.

like image 200
wgumenyuk Avatar answered Oct 25 '25 12:10

wgumenyuk