-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata_store.py
More file actions
39 lines (27 loc) · 1.09 KB
/
data_store.py
File metadata and controls
39 lines (27 loc) · 1.09 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
"""Utility helpers for reading and writing persistent user data."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Dict
BASE_DIR = Path(__file__).resolve().parent
DATA_PATH = BASE_DIR / "user_data.json"
def load_user_data() -> Dict[str, Any]:
"""Return the persisted user data as a dictionary.
The data file is created automatically the first time this function is
called so that other modules can rely on its existence.
"""
if not DATA_PATH.exists():
save_user_data({})
return {}
with DATA_PATH.open("r", encoding="utf-8") as file:
try:
return json.load(file)
except json.JSONDecodeError:
# If the file somehow becomes corrupted we start with a clean slate
# to avoid crashing the bot and blocking whitelist updates.
save_user_data({})
return {}
def save_user_data(data: Dict[str, Any]) -> None:
"""Persist the provided user data to disk."""
with DATA_PATH.open("w", encoding="utf-8") as file:
json.dump(data, file, indent=4)