48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
|
|
import json
|
||
|
|
import logging
|
||
|
|
from pathlib import Path
|
||
|
|
from typing import List, Literal
|
||
|
|
|
||
|
|
from pydantic import BaseSettings
|
||
|
|
|
||
|
|
from ops_bot.matrix import MatrixClientSettings
|
||
|
|
|
||
|
|
|
||
|
|
class RoutingKey(BaseSettings):
|
||
|
|
name: str
|
||
|
|
path_key: str
|
||
|
|
secret_token: str
|
||
|
|
room_id: str
|
||
|
|
hook_type: Literal["gitlab", "pagerduty", "aws-sns"]
|
||
|
|
|
||
|
|
|
||
|
|
class BotSettings(BaseSettings):
|
||
|
|
routing_keys: List[RoutingKey]
|
||
|
|
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
|
||
|
|
matrix: MatrixClientSettings
|
||
|
|
|
||
|
|
class Config:
|
||
|
|
env_prefix = "BOT_"
|
||
|
|
case_sensitive = False
|
||
|
|
|
||
|
|
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):
|
||
|
|
bot_settings = BotSettings.parse_file(filename)
|
||
|
|
else:
|
||
|
|
bot_settings = BotSettings(_env_file=".env", _env_file_encoding="utf-8")
|
||
|
|
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))
|