This repository has been archived on 2024-08-21. You can view files and clone it, but cannot push or open issues or pull requests.
TelegramPoster/modules/utils.py

138 lines
4.0 KiB
Python
Raw Normal View History

2023-03-12 15:54:06 +02:00
from os import kill
2022-09-18 19:27:13 +03:00
from os import name as osname
2023-03-12 15:54:06 +02:00
from os import sep
from sys import exit
2022-09-18 19:27:13 +03:00
from traceback import print_exc
from typing import Any
2022-08-11 12:27:17 +03:00
2023-03-12 15:54:06 +02:00
from ujson import JSONDecodeError, dumps, loads
2023-01-17 12:43:10 +02:00
from modules.logger import logWrite
2022-08-08 15:53:26 +03:00
2023-03-09 12:33:02 +02:00
def jsonLoad(filename: str) -> Any:
2022-08-08 15:53:26 +03:00
"""Loads arg1 as json and returns its contents"""
2023-03-09 12:33:02 +02:00
with open(filename, "r", encoding="utf8") as file:
2022-08-11 12:27:17 +03:00
try:
2022-08-31 15:31:24 +03:00
output = loads(file.read())
2022-08-11 12:27:17 +03:00
except JSONDecodeError:
2023-03-09 12:33:02 +02:00
logWrite(
f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}"
)
2022-08-11 21:39:03 +03:00
raise
2022-08-11 12:27:17 +03:00
except FileNotFoundError:
2023-03-09 12:33:02 +02:00
logWrite(
f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}"
)
2022-08-11 21:39:03 +03:00
raise
2022-08-08 15:53:26 +03:00
file.close()
return output
2023-03-09 12:33:02 +02:00
def jsonSave(contents: Any, filename: str) -> None:
2022-08-08 15:53:26 +03:00
"""Dumps dict/list arg1 to file arg2"""
2022-08-11 12:27:17 +03:00
try:
2023-03-09 12:33:02 +02:00
with open(filename, "w", encoding="utf8") as file:
2023-03-12 23:14:41 +02:00
file.write(
dumps(
contents, ensure_ascii=False, indent=4, escape_forward_slashes=False
)
)
2022-08-11 12:27:17 +03:00
file.close()
except Exception as exp:
2022-09-18 19:27:13 +03:00
logWrite(f"Could not save json file {filename}: {exp}\n{print_exc()}")
2022-08-08 15:53:26 +03:00
return
def configSet(key: str, value, *args: str):
"""Set key to a value
Args:
* key (str): The last key of the keys path.
* value (str/int/float/list/dict/None): Some needed value.
* *args (str): Path to key like: dict[args][key].
2023-03-09 12:33:02 +02:00
"""
2022-08-08 15:53:26 +03:00
this_dict = jsonLoad("config.json")
string = "this_dict"
for arg in args:
string += f'["{arg}"]'
if type(value) in [str]:
string += f'["{key}"] = "{value}"'
else:
string += f'["{key}"] = {value}'
exec(string)
jsonSave(this_dict, "config.json")
return
2023-03-09 12:33:02 +02:00
2022-08-08 15:53:26 +03:00
def configGet(key: str, *args: str):
"""Get value of the config key
Args:
* key (str): The last key of the keys path.
* *args (str): Path to key like: dict[args][key].
Returns:
* any: Value of provided key
2023-03-09 12:33:02 +02:00
"""
2022-08-08 15:53:26 +03:00
this_dict = jsonLoad("config.json")
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key]
2022-08-10 14:08:15 +03:00
return this_key[key]
2023-03-09 12:33:02 +02:00
2022-08-11 21:39:03 +03:00
def locale(key: str, *args: str, locale=configGet("locale")):
2022-08-10 14:08:15 +03:00
"""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
2023-03-09 12:33:02 +02:00
"""
if locale == None:
2022-08-10 14:08:15 +03:00
locale = configGet("locale")
2023-03-09 12:33:02 +02:00
2022-08-10 14:08:15 +03:00
try:
2022-09-18 19:27:13 +03:00
this_dict = jsonLoad(f'{configGet("locale", "locations")}{sep}{locale}.json')
2022-08-10 14:08:15 +03:00
except FileNotFoundError:
try:
2023-03-09 12:33:02 +02:00
this_dict = jsonLoad(
f'{configGet("locale", "locations")}{sep}{configGet("locale")}.json'
)
2022-08-10 14:08:15 +03:00
except FileNotFoundError:
try:
2023-03-09 12:33:02 +02:00
this_dict = jsonLoad(
f'{configGet("locale_fallback", "locations")}{sep}{configGet("locale")}.json'
)
2022-08-10 14:08:15 +03:00
except:
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]
2023-03-09 12:33:02 +02:00
2022-08-10 14:08:15 +03:00
try:
return this_key[key]
except KeyError:
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
2023-03-09 12:33:02 +02:00
2022-08-11 12:27:17 +03:00
try:
2022-09-18 19:27:13 +03:00
from psutil import Process
2022-08-11 12:27:17 +03:00
except ModuleNotFoundError:
print(locale("deps_missing", "console", locale=configGet("locale")), flush=True)
2022-09-18 19:27:13 +03:00
exit()
2022-08-11 12:27:17 +03:00
2023-03-09 12:33:02 +02:00
def killProc(pid: int) -> None:
"""Kill process by its PID. Meant to be used to kill the main process of bot itself.
### Args:
* pid (`int`): PID of the target
"""
2022-09-18 19:27:13 +03:00
if osname == "posix":
2023-01-10 13:52:44 +02:00
from signal import SIGKILL
2023-03-09 12:33:02 +02:00
2022-09-18 19:27:13 +03:00
kill(pid, SIGKILL)
2022-08-10 14:08:15 +03:00
else:
2023-03-09 12:33:02 +02:00
Process(pid).kill()