55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
import json
|
|
import logging
|
|
import os
|
|
import typing
|
|
from pathlib import Path
|
|
from typing import List, Literal
|
|
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
from ops_bot.matrix import MatrixClientSettings
|
|
|
|
env_path = os.getenv("BOT_ENV_FILE")
|
|
|
|
|
|
HookType = Literal["gitlab", "pagerduty", "aws-sns", "alertmanager"]
|
|
hook_types = typing.get_args(HookType)
|
|
|
|
|
|
class RoutingKey(BaseSettings):
|
|
name: str
|
|
path_key: str
|
|
secret_token: str
|
|
room_id: str
|
|
hook_type: HookType
|
|
|
|
|
|
class BotSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(
|
|
env_prefix="BOT_", env_file=env_path, env_file_encoding="utf-8"
|
|
)
|
|
routing_keys: List[RoutingKey]
|
|
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
|
|
matrix: MatrixClientSettings
|
|
|
|
def get_rooms(self) -> List[str]:
|
|
return list(set([key.room_id for key in self.routing_keys]))
|
|
|
|
|
|
def config_file_exists(filename: str) -> bool:
|
|
return Path(filename).exists()
|
|
|
|
|
|
def load_config(filename: str = "config.json") -> BotSettings:
|
|
if config_file_exists(filename):
|
|
with open(filename, "r") as f:
|
|
bot_settings = BotSettings.model_validate_json(f.read())
|
|
else:
|
|
bot_settings = BotSettings() # type: ignore[call-arg]
|
|
logging.getLogger().setLevel(bot_settings.log_level)
|
|
return bot_settings
|
|
|
|
|
|
def save_config(settings: BotSettings, filename: str = "config.json") -> None:
|
|
with open(filename, "w") as f:
|
|
f.write(json.dumps(settings.dict(), indent=2))
|