LibBotUniversal/libbot/__main__.py
2023-05-11 20:23:51 +02:00

40 lines
1.1 KiB
Python

from pathlib import Path
from typing import Any, Union
import aiofiles
from ujson import dumps, loads
async def json_read(path: Union[str, Path]) -> Any:
async with aiofiles.open(str(path), mode="r", encoding="utf-8") as f:
data = await f.read()
return loads(data)
async def json_write(data: Any, path: Union[str, Path]) -> None:
async with aiofiles.open(str(path), mode="w", encoding="utf-8") as f:
await f.write(dumps(data, ensure_ascii=False, escape_forward_slashes=False))
async def config_get(key: str, *path: str, config_file: str = "config.json") -> Any:
this_key = await json_read(config_file)
for dict_key in path:
this_key = this_key[dict_key]
return this_key[key]
async def config_set(
key: str, value: Any, *path: str, config_file: str = "config.json"
) -> None:
this_dict = await json_read(config_file)
string = "this_dict"
for arg in path:
string += f'["{arg}"]'
if type(value) in [str]:
string += f'["{key}"] = "{value}"'
else:
string += f'["{key}"] = {value}'
exec(string)
await json_write(this_dict, config_file)
return