forked from ManicJamie/HornetBot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave.py
More file actions
86 lines (72 loc) · 3.1 KB
/
save.py
File metadata and controls
86 lines (72 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import json, os, shutil, copy, logging
JSON_PATH = "save.json"
data : dict = {} # Do not access directly - use getGuildData or getModuleData instead.
VERSION = 0.1
FULL_TEMPLATE = {
"version": VERSION,
"module_templates": {},
"guild_template": {
"nick" : "", # NB: automatically set to guild name on addition
"adminRoles" : [],
"spoileredPlayers": [],
"modules" : {} # NB: filled with module_templates on guild instantiation
},
"guilds": {}
}
class TemplateEnforcementError(Exception):
"""Raised when enforcing a module's template"""
def save():
shutil.copy2(JSON_PATH, JSON_PATH + ".bak")
# For write-time safety - if we error mid-write then contents of the file won't be completed!
with open(JSON_PATH, "w") as f:
json.dump(data, f, indent=4)
if not os.path.exists(JSON_PATH):
data = FULL_TEMPLATE
save()
else:
with open(JSON_PATH) as f:
try:
data = json.load(f)
except json.JSONDecodeError:
logging.warn("Could not deserialise save.json - loading backup")
with open(JSON_PATH + ".bak") as f2:
data = json.load(f2)
if VERSION > data["version"]:
logging.error(f"Save json is out of date! Json ver: {data['version']} < Save ver: {VERSION}")
exit(11)
def add_module_template(module_name: str, init_data: dict):
data["module_templates"][module_name] = copy.deepcopy(init_data)
save()
def enforce_template_dict(target: dict, template: dict):
"""Recursive method to enforce a module save template. Verifies only by type. Does not remove extra keys.
Raises `TemplateEnforcementError` if existing key type differs."""
for k, template_value in template.items():
target_value = target.get(k, None)
if target_value is None:
target[k] = template_value
continue
if type(target_value) != type(template_value): raise TemplateEnforcementError(k)
if isinstance(target_value, dict): enforce_template_dict(target_value, template_value)
def get_guild_ids() -> list[str]:
return data["guilds"].keys()
def get_module_data(guild_id, module_name):
return get_guild_data(guild_id)["modules"][module_name]
def get_guild_data(guild_id):
if str(guild_id) not in data["guilds"].keys():
init_guild_data(guild_id)
return data["guilds"][str(guild_id)]
def init_guild_data(guild_id : str, guild_name : str = ""):
data["guilds"][guild_id] = FULL_TEMPLATE
data["guilds"][guild_id]["nick"] = guild_name
data["guilds"][guild_id]["modules"] = copy.deepcopy(data["module_templates"])
def init_module(module_name, init_data=None):
if init_data is None:
if module_name not in data["module_templates"]: return # No template added by module, ignore it
init_data = data["module_templates"][module_name]
for guild_id in get_guild_ids():
modules = get_guild_data(guild_id)["modules"]
if module_name in modules:
enforce_template_dict(modules[module_name], init_data)
else:
modules[module_name] = copy.deepcopy(init_data)
save()