какая-то магия с загрузкой конфигурации

This commit is contained in:
lulzette 2024-05-20 21:38:39 +03:00
parent cbcf468009
commit 99e8c84ea6
2 changed files with 27 additions and 25 deletions

View File

@ -1,6 +1,7 @@
from dataclasses import dataclass, asdict
import configparser
@dataclass(slots=True, frozen=True)
class Config:
streamer: str
@ -11,26 +12,27 @@ class Config:
check_period: int
cleanup_msg: bool
def load_config(config_path: str = "twitch-tgbot.cfg") -> Config:
"""
Эта функция либо читает существующий конфиг, либо создает новый.
Возвращает объект конфига (configparser.ConfigParser())
"""
config_file = configparser.ConfigParser()
# Читаем конфиг, если пустой - заполняем
if not config_file.read(config_path) or not config_file.has_section('twitch'):
config_file.add_section('twitch')
twitch = config_file['twitch']
config = Config(
streamer=twitch.get('streamer',fallback='the_viox'),
app_id=twitch.get('app_id',fallback=''),
app_secret=twitch.get('app_secret',fallback=''),
target_tg_chat=twitch.get('target_tg_chat',fallback=''),
tg_token=twitch.get('tg_token',fallback=''),
check_period=twitch.getint('check_period',fallback=10),
cleanup_msg=twitch.getboolean('cleanup_msg',fallback=True)
)
with open(config_path, 'w') as cfg_file:
config_file.read_dict({'twitch': asdict(config)})
config_file.write(cfg_file)
return config
@classmethod
def load(cls, config_path: str = "twitch-tgbot.cfg") -> 'Config':
"""
Эта функция либо читает существующий конфиг, либо создает новый.
Возвращает объект конфига (configparser.ConfigParser())
"""
config_file = configparser.ConfigParser()
# Читаем конфиг, если пустой - заполняем
if not config_file.read(config_path) or not config_file.has_section('twitch'):
config_file.add_section('twitch')
twitch = config_file['twitch']
config = Config(
streamer=twitch.get('streamer',fallback='the_viox'),
app_id=twitch.get('app_id',fallback=''),
app_secret=twitch.get('app_secret',fallback=''),
target_tg_chat=twitch.get('target_tg_chat',fallback=''),
tg_token=twitch.get('tg_token',fallback=''),
check_period=twitch.getint('check_period',fallback=10),
cleanup_msg=twitch.getboolean('cleanup_msg',fallback=True)
)
with open(config_path, 'w') as cfg_file:
config_file.read_dict({'twitch': asdict(config)})
config_file.write(cfg_file)
return config

View File

@ -10,7 +10,7 @@ from datetime import datetime
import requests
import shutil
from parse_config import Config, load_config
from parse_config import Config
from log_msg import MyLog
@ -128,7 +128,7 @@ def check_alive():
if __name__ == '__main__':
log = MyLog().logger
log.info("Запущен")
config_python = load_config()
config_python = Config.load()
twitch_client = Twitch(config_python.app_id, config_python.app_secret)
bot = telebot.TeleBot(config_python.tg_token)