[docs]classBotLocale:"""Small addon that can be used by bot clients' classes in order to minimize I/O"""def__init__(self,default_locale:str|None="en",locales_root:str|Path=Path("locale"),)->None:""" Args: default_locale (str | None): Default bot's locale. Defaults to `"en"` locales_root (str | Path): Folder where locales are located. Defaults to `Path("locale")` """ifisinstance(locales_root,str):locales_root=Path(locales_root)elifnotisinstance(locales_root,Path):raiseTypeError("'locales_root' must be a valid path or path-like object")files_locales:List[str]=listdir(locales_root)valid_locales:List[str]=[".".join(entry.split(".")[:-1])forentryinfiles_locales]self.default:str=config_get("locale")ifdefault_localeisNoneelsedefault_localeself.locales:Dict[str,Any]={}forlocaleinvalid_locales:self.locales[locale]=json_read(Path(f"{locales_root}/{locale}.json"))def_(self,key:str,*args:str,locale:str|None=None)->Any:"""Get value of locale string. Args: key (str): The last key of the locale's keys path *args (str): Path to key like: `dict[args][key]` locale (str | None, optional): Locale to be looked up in. Defaults to config's `"locale"` value Returns: Any: Value of provided locale key. Is usually `str`, `Dict[str, Any]` or `List[Any]` """iflocaleisNone:locale:str=self.defaulttry:this_dict:Dict[str,Any]=self.locales[locale]exceptKeyError:try:this_dict:Dict[str,Any]=self.locales[self.default]exceptKeyError:return(f'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"')this_key:Dict[str,Any]=this_dictfordict_keyinargs:this_key=this_key[dict_key]try:returnthis_key[key]exceptKeyError:returnf'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"'
[docs]defin_all_locales(self,key:str,*args:str)->List[Any]:"""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 (str): Path to key like: `dict[args][key]` Returns: List[Any]: List of values in all locales """output:List[Any]=[]forname,localeinself.locales.items():try:this_dict:Dict[str,Any]=localeexceptKeyError:continuethis_key:Dict[str,Any]=this_dictfordict_keyinargs:this_key=this_key[dict_key]try:output.append(this_key[key])exceptKeyError:continuereturnoutput
[docs]defin_every_locale(self,key:str,*args:str)->Dict[str,Any]:"""Get value of the provided key and path in every available locale with locale tag. Args: key (str): The last key of the locale's keys path *args (str): Path to key like: `dict[args][key]` Returns: Dict[str, Any]: Locale is a key, and it's value from locale file is a value """output:Dict[str,Any]={}forname,localeinself.locales.items():try:this_dict:Dict[str,Any]=localeexceptKeyError:continuethis_key:Dict[str,Any]=this_dictfordict_keyinargs:this_key=this_key[dict_key]try:output[name]=this_key[key]exceptKeyError:continuereturnoutput