Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/config/__init__.py

107 lines
2.9 KiB
Python
Raw Normal View History

import os
import toml
2021-03-21 08:14:28 +00:00
from os.path import abspath
2021-02-19 10:13:31 +00:00
2022-01-14 09:51:17 +00:00
from core.exceptions import ConfigFileNotFound
config_filename = 'config.toml'
2021-04-08 12:54:36 +00:00
config_path = abspath('./config/' + config_filename)
2021-03-21 08:14:28 +00:00
old_cfg_file_path = abspath('./config/config.cfg')
def convert_cfg_to_toml():
import configparser
config = configparser.ConfigParser()
config.read(old_cfg_file_path)
config_dict = {}
for section in config.sections():
config_dict[section] = dict(config[section])
for x in config_dict:
for y in config_dict[x]:
if config_dict[x][y] == "True":
config_dict[x][y] = True
elif config_dict[x][y] == "False":
config_dict[x][y] = False
elif config_dict[x][y].isdigit():
config_dict[x][y] = int(config_dict[x][y])
with open(config_path, 'w') as f:
f.write(toml.dumps(config_dict))
os.remove(old_cfg_file_path)
2021-04-08 12:52:51 +00:00
class CFG:
2023-07-05 15:14:43 +00:00
value = None
_ts = None
@classmethod
def load(cls):
if not os.path.exists(config_path):
if os.path.exists(old_cfg_file_path):
convert_cfg_to_toml()
else:
raise ConfigFileNotFound(config_path) from None
2023-07-05 15:14:43 +00:00
cls.value = toml.loads(open(config_path, 'r', encoding='utf-8').read())
cls._ts = os.path.getmtime(config_path)
2023-04-05 04:33:29 +00:00
2023-07-05 15:14:43 +00:00
@classmethod
def get(cls, q):
2023-06-29 13:41:01 +00:00
q = q.lower()
2023-07-05 15:14:43 +00:00
if os.path.getmtime(config_path) != cls._ts:
cls.load()
value_s = cls.value.get('secret')
value_n = cls.value.get('cfg')
value = value_s.get(q)
2023-06-29 13:38:53 +00:00
if value is None:
value = value_n.get(q)
2021-03-21 08:14:28 +00:00
return value
2021-04-08 12:52:51 +00:00
2023-07-05 15:14:43 +00:00
@classmethod
def write(cls, q, value, secret=False):
q = q.lower()
if os.path.getmtime(config_path) != cls._ts:
cls.load()
value_s = cls.value.get('secret')
value_n = cls.value.get('cfg')
if q in value_s:
value_s[q] = value
elif q in value_n:
value_n[q] = value
else:
if secret:
value_s[q] = value
else:
value_n[q] = value
cls.value['secret'] = value_s
cls.value['cfg'] = value_n
with open(config_path, 'w', encoding='utf-8') as f:
f.write(toml.dumps(cls.value))
cls.load()
@classmethod
def delete(cls, q):
q = q.lower()
if os.path.getmtime(config_path) != cls._ts:
cls.load()
value_s = cls.value.get('secret')
value_n = cls.value.get('cfg')
if q in value_s:
del value_s[q]
elif q in value_n:
del value_n[q]
else:
return False
cls.value['secret'] = value_s
cls.value['cfg'] = value_n
with open(config_path, 'w', encoding='utf-8') as f:
f.write(toml.dumps(cls.value))
cls.load()
return True
2021-04-08 12:52:51 +00:00
2023-07-05 15:14:43 +00:00
CFG.load()
Config = CFG.get