Multilingual support, custom paths
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Some set of functions needed for discord/telegram bots and other types of apps"""
|
||||
|
||||
from os import sep, stat, makedirs
|
||||
from os import sep, stat, makedirs, kill
|
||||
from os import name as osname
|
||||
from datetime import datetime
|
||||
from typing import Union
|
||||
from ujson import loads, dumps
|
||||
from shutil import copyfileobj
|
||||
from gzip import open as gzipopen
|
||||
from psutil import Process
|
||||
|
||||
|
||||
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"):
|
||||
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y") -> str:
|
||||
"""Return current local time formatted as arg.
|
||||
|
||||
### Args:
|
||||
@@ -20,7 +23,7 @@ def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"):
|
||||
return datetime.now().strftime(format)
|
||||
|
||||
|
||||
def checkSize(logs_folder=f"logs{sep}", log_size=1024):
|
||||
def checkSize(logs_folder=f"logs{sep}", log_size=1024) -> None:
|
||||
"""Checks latest log file size and rotates it if needed.
|
||||
|
||||
### Args:
|
||||
@@ -51,7 +54,7 @@ def checkSize(logs_folder=f"logs{sep}", log_size=1024):
|
||||
i += 1
|
||||
|
||||
|
||||
def logWrite(message, logs_folder=f"logs{sep}", level="INFO"):
|
||||
def logWrite(message: str, logs_folder=f"logs{sep}", level="INFO") -> None:
|
||||
"""Append some message to latest log file.
|
||||
|
||||
### Args:
|
||||
@@ -79,28 +82,42 @@ def logWrite(message, logs_folder=f"logs{sep}", level="INFO"):
|
||||
log.close()
|
||||
|
||||
|
||||
def jsonSave(filename, value):
|
||||
def jsonSave(filename: str, value: Union[list, dict]) -> None:
|
||||
"""Save some list or dict as json file.
|
||||
|
||||
Args:
|
||||
### Args:
|
||||
* filename (str): File to which value will be written.
|
||||
* value (list or dict): Some object that will be written to filename.
|
||||
* value (Union[list, dict]): Some object that will be written to filename.
|
||||
"""
|
||||
with open(filename, 'w', encoding="utf-8") as f:
|
||||
f.write(dumps(value, indent=4, ensure_ascii=False))
|
||||
f.close()
|
||||
|
||||
|
||||
def jsonLoad(filename):
|
||||
def jsonLoad(filename: str) -> any:
|
||||
"""Load json file and return python dict or list.
|
||||
|
||||
Args:
|
||||
### Args:
|
||||
* filename (str): File which should be loaded.
|
||||
|
||||
Returns:
|
||||
* list or dict: Content of json file provided.
|
||||
### Returns:
|
||||
* any: Content of json file provided.
|
||||
"""
|
||||
with open(filename, 'r', encoding="utf-8") as f:
|
||||
value = loads(f.read())
|
||||
f.close()
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
def killProc(pid: int) -> None:
|
||||
"""Kill the process by its PID
|
||||
|
||||
### Args:
|
||||
* pid (int): Process ID to be killed
|
||||
"""
|
||||
if osname == "posix":
|
||||
from signal import SIGKILL
|
||||
kill(pid, SIGKILL)
|
||||
else:
|
||||
p = Process(pid)
|
||||
p.kill()
|
@@ -1,15 +1,17 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Essential set of functions needed for discord/telegram bots and other types of apps"""
|
||||
|
||||
from typing import Union
|
||||
from modules.functions import jsonLoad, jsonSave
|
||||
from os import sep
|
||||
from os import sep, listdir
|
||||
|
||||
def configGet(key: str, *args: str):
|
||||
|
||||
def configGet(key: str, *args: str) -> any:
|
||||
"""Get value of the config key
|
||||
Args:
|
||||
### Args:
|
||||
* key (str): The last key of the keys path.
|
||||
* *args (str): Path to key like: dict[args][key].
|
||||
Returns:
|
||||
### Returns:
|
||||
* any: Value of provided key
|
||||
"""
|
||||
this_dict = jsonLoad("config.json")
|
||||
@@ -18,11 +20,12 @@ def configGet(key: str, *args: str):
|
||||
this_key = this_key[dict_key]
|
||||
return this_key[key]
|
||||
|
||||
def configAppend(key: str, value, *args: str):
|
||||
|
||||
def configAppend(key: str, value: Union[str, float, int, bool, dict, list, None], *args: str) -> None:
|
||||
"""Set key to a value
|
||||
Args:
|
||||
### Args:
|
||||
* key (str): The last key of the keys path.
|
||||
* value (str/int/float/list/dict/None): Some needed value.
|
||||
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
|
||||
* *args (str): Path to key like: dict[args][key].
|
||||
"""
|
||||
this_dict = jsonLoad("config.json")
|
||||
@@ -37,34 +40,40 @@ def configAppend(key: str, value, *args: str):
|
||||
jsonSave(this_dict, "config.json")
|
||||
return
|
||||
|
||||
def configRemove(key, value):
|
||||
|
||||
def configRemove(key: str, value: Union[str, float, int, bool, dict, list, None]) -> None:
|
||||
"""Remove value from config's list key
|
||||
|
||||
### Args:
|
||||
* key (str): The last key of the keys path.
|
||||
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
|
||||
"""
|
||||
config = jsonLoad("config.json")
|
||||
config[key].remove(value)
|
||||
jsonSave("config.json", config)
|
||||
|
||||
|
||||
def locale(key: str, *args: str, locale=configGet("locale")):
|
||||
def locale(key: str, *args: str, locale=configGet("locale")) -> str:
|
||||
"""Get value of locale string
|
||||
Args:
|
||||
### 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:
|
||||
### Returns:
|
||||
* any: Value of provided locale key
|
||||
"""
|
||||
if (locale == None):
|
||||
locale = configGet("locale")
|
||||
|
||||
locales = configGet("locales")
|
||||
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json')
|
||||
this_dict = jsonLoad(f'{locales}{sep}{locale}.json')
|
||||
except FileNotFoundError:
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json')
|
||||
this_dict = jsonLoad(f'{locales}{sep}{configGet("locale")}.json')
|
||||
except FileNotFoundError:
|
||||
try:
|
||||
this_dict = jsonLoad(f'{configGet("locale_fallback", "locations")}{sep}{configGet("locale")}.json')
|
||||
except:
|
||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||
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:
|
||||
@@ -73,26 +82,99 @@ def locale(key: str, *args: str, locale=configGet("locale")):
|
||||
try:
|
||||
return this_key[key]
|
||||
except KeyError:
|
||||
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||
return f'⚠ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
|
||||
|
||||
|
||||
def userSet(userid, key, value):
|
||||
user = jsonLoad(f"data{sep}users{sep}{userid}.json")
|
||||
def userSet(userid: Union[str, int], key: str, value: Union[str, float, int, bool, dict, list, None]) -> None:
|
||||
"""Set user's variable
|
||||
|
||||
### Args:
|
||||
* userid (Union[str, int]): ID of a user.
|
||||
* key (str): Key of a user's variable.
|
||||
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
|
||||
"""
|
||||
data = configGet("data")
|
||||
user = jsonLoad(f"{data}{sep}users{sep}{userid}.json")
|
||||
user[key] = value
|
||||
jsonSave(f"data{sep}users{sep}{userid}.json", user)
|
||||
jsonSave(f"{data}{sep}users{sep}{userid}.json", user)
|
||||
|
||||
def userGet(userid, key):
|
||||
|
||||
def userGet(userid: Union[str, int], key: str) -> any:
|
||||
"""Get user's variable
|
||||
|
||||
### Args:
|
||||
* userid (Union[str, int]): ID of a user.
|
||||
* key (str): Key of a user's variable.
|
||||
|
||||
### Returns:
|
||||
* any: Value of requested key or None
|
||||
"""
|
||||
data = configGet("data")
|
||||
try:
|
||||
return jsonLoad(f"data{sep}users{sep}{userid}.json")[key]
|
||||
return jsonLoad(f"{data}{sep}users{sep}{userid}.json")[key]
|
||||
except KeyError:
|
||||
return None
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
|
||||
def userClear(userid, key):
|
||||
|
||||
def userClear(userid: Union[str, int], key: str) -> None:
|
||||
"""Clear user's variable
|
||||
|
||||
### Args:
|
||||
* userid (Union[str, int]): ID of a user.
|
||||
* key (str): Key of a user's variable.
|
||||
"""
|
||||
data = configGet("data")
|
||||
try:
|
||||
user = jsonLoad(f"data{sep}users{sep}{userid}.json")
|
||||
user = jsonLoad(f"{data}{sep}users{sep}{userid}.json")
|
||||
del user[key]
|
||||
jsonSave(f"data{sep}users{sep}{userid}.json", user)
|
||||
jsonSave(f"{data}{sep}users{sep}{userid}.json", user)
|
||||
except KeyError:
|
||||
pass
|
||||
pass
|
||||
|
||||
|
||||
def localeName(command: str, option: Union[str, None]):
|
||||
"""Get name of a command or command's option
|
||||
|
||||
### Args:
|
||||
* command (str): Command that is set in locale file
|
||||
* option (Union[str, NoneType]): Option's name or None (if command's name requested)
|
||||
|
||||
### Returns:
|
||||
* str: Name of a command or an option
|
||||
"""
|
||||
output = {}
|
||||
locales = configGet("locales")
|
||||
for entry in listdir(locales):
|
||||
if entry.endswith(".json"):
|
||||
if entry.replace(".json", "") != configGet("locale"):
|
||||
all_commands = locale("cmd", locale=entry.replace(".json", ""))
|
||||
if option != None:
|
||||
output[entry.replace(".json", "")] = all_commands[command]["options"][option]["name"]
|
||||
else:
|
||||
output[entry.replace(".json", "")] = all_commands[command]["name"]
|
||||
return output
|
||||
|
||||
|
||||
def localeDescription(command: str, option: Union[str, None]):
|
||||
"""Get description of a command or command's option
|
||||
|
||||
### Args:
|
||||
* command (str): Command that is set in locale file
|
||||
* option (Union[str, NoneType]): Option's name or None (if command's description requested)
|
||||
|
||||
### Returns:
|
||||
* str: Description of a command or an option
|
||||
"""
|
||||
output = {}
|
||||
locales = configGet("locales")
|
||||
for entry in listdir(locales):
|
||||
if entry.endswith(".json"):
|
||||
if entry.replace(".json", "") != configGet("locale"):
|
||||
all_commands = locale("cmd", locale=entry.replace(".json", ""))
|
||||
if option != None:
|
||||
output[entry.replace(".json", "")] = all_commands[command]["options"][option]["description"]
|
||||
else:
|
||||
output[entry.replace(".json", "")] = all_commands[command]["description"]
|
||||
return output
|
Reference in New Issue
Block a user