From 5274d446f2ecfc32272b1dd7f274fccaa1d9a4d4 Mon Sep 17 00:00:00 2001 From: Profitroll <47523801+profitrollgame@users.noreply.github.com> Date: Thu, 11 May 2023 21:55:43 +0200 Subject: [PATCH] Added i11n support --- libbot/i11n/__init__.py | 82 +++++++++++++++++++++++++++++++++++++++++ setup.py | 1 + 2 files changed, 83 insertions(+) create mode 100644 libbot/i11n/__init__.py diff --git a/libbot/i11n/__init__.py b/libbot/i11n/__init__.py new file mode 100644 index 0000000..cb013ab --- /dev/null +++ b/libbot/i11n/__init__.py @@ -0,0 +1,82 @@ +from os import listdir +from pathlib import Path +from typing import Any + +from libbot import config_get, json_read, sync + + +async def _(key: str, *args: str, locale: str = sync.config_get("locale")) -> Any: + """Get value of locale string + + ### Args: + * key (`str`): The last key of the locale's keys path + * *args (`list`): Path to key like: `dict[args][key]` + * locale (`str`): Locale to looked up in. Defaults to config's `"locale"` value + + ### Returns: + * `Any`: Value of provided locale key. Is usually `str`, `dict` or `list` + """ + if locale is None: + locale = sync.config_get("locale") + + try: + this_dict = await json_read( + Path(f'{await config_get("locale", "locations")}/{locale}.json') + ) + except FileNotFoundError: + try: + this_dict = await json_read( + Path( + f'{await config_get("locale", "locations")}/{await config_get("locale")}.json' + ) + ) + except FileNotFoundError: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + return this_key[key] + except KeyError: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"' + + +async def in_all_locales(key: str, *args: str) -> list: + """Get value of the provided key and path in all available locales + + ### Args: + * key (`str`): The last key of the locale's keys path. + * *args (`list`): Path to key like: `dict[args][key]`. + + ### Returns: + * `list`: List of values in all locales + """ + + output = [] + valid_locales = [] + + files_locales = listdir(await config_get("locale", "locations")) + + for entry in files_locales: + valid_locales.append(".".join(entry.split(".")[:-1])) + + for lc in valid_locales: + try: + this_dict = await json_read( + Path(f'{await config_get("locale", "locations")}/{lc}.json') + ) + except FileNotFoundError: + continue + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + output.append(this_key[key]) + except KeyError: + continue + + return output diff --git a/setup.py b/setup.py index 013a91e..5fe86d6 100644 --- a/setup.py +++ b/setup.py @@ -16,6 +16,7 @@ setup( }, packages=[ "libbot", + "libbot.i11n", "libbot.sync", ], install_requires=["aiofiles~=23.1.0", "ujson==5.7.0"],