Files
2026-matrix-down/config.py
2026-09-07 01:25:32 +03:00

52 lines
1.2 KiB
Python

"""Module for generating and reading config"""
import json
import aiofiles
import os
import traceback
from mab import MatrixBotConfig
DEFAULT_CONFIG = {
"matrix_homeserver_url": "https://matrix.domain.net",
"matrix_username_localpart": "short_username",
"storage_directory": "session_storage"
}
#
# PRIVATE
#
async def write_default_config(path: str) -> None:
try:
async with aiofiles.open(path, "w") as f:
await f.write(json.dumps(DEFAULT_CONFIG, indent=4))
except:
traceback.print_exc()
#
# PUBLIC
#
async def load_config(path: str = "config.json") -> MatrixBotConfig | None:
"""Load config from specified path. Creates default config if it does not exist (but still returns None)."""
# no file
if not os.path.isfile(path):
await write_default_config(path)
return None
# open and read
try:
async with aiofiles.open(path, "r") as f:
j = json.loads((await f.read()).strip())
except:
traceback.print_exc()
return None
# parse
try:
cfg = MatrixBotConfig(**j)
return cfg
except:
traceback.print_exc()
return None