This repository has been archived on 2024-10-14. You can view files and clone it, but cannot push or open issues or pull requests.
AutoZoomTelegram/modules/functions_bot.py

180 lines
5.9 KiB
Python

# -*- 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, listdir
def configGet(key: str, *args: str) -> any:
"""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
"""
this_dict = jsonLoad("config.json")
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key]
return this_key[key]
def configAppend(key: str, value: Union[str, float, int, bool, dict, list, None], *args: str) -> None:
"""Set key to a value
### Args:
* key (str): The last key of the keys path.
* 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")
string = "this_dict"
for arg in args:
string += f'["{arg}"]'
if type(value) in [str]:
string += f'["{key}"].append("{value}")'
else:
string += f'["{key}"].append({value})'
exec(string)
jsonSave(this_dict, "config.json")
return
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")) -> str:
"""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
"""
if (locale == None):
locale = configGet("locale")
locales = configGet("locales")
try:
this_dict = jsonLoad(f'{locales}{sep}{locale}.json')
except FileNotFoundError:
try:
this_dict = jsonLoad(f'{locales}{sep}{configGet("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}"'
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)
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]
except KeyError:
return None
except FileNotFoundError:
return None
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")
del user[key]
jsonSave(f"{data}{sep}users{sep}{userid}.json", user)
except KeyError:
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