Initial commit
This commit is contained in:
52
config.py
Normal file
52
config.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user