-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSettings.py
98 lines (87 loc) · 4.43 KB
/
Settings.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import json, os, logging
logger = logging.getLogger(__name__)
# Note, this logger will be overridden due the logger
# itself using this module for a logging file name
class FileErrorHandler:
"""
This class acts as a Context Manager for handling,
guiding and modifying errors regarding the settings.json file.
"""
def __init__(self):
super().__init__()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
if exc_type in (ValueError, json.decoder.JSONDecodeError):
# If there is a ValueError or json.decoder.JSONDecodeError,
# we want to let the user know their settings.json file is incorrect.
raise ValueError("There is an error in your settings file.")
elif exc_type is FileNotFoundError:
# If the file is missing, create a standardised settings.json file
# With all parameters required.
with open(Settings.PATH, "w") as f:
standard_dict = {
"Host": "irc.chat.twitch.tv",
"Port": 6667,
"Channel": "#<channel>",
"Nickname": "<name>",
"Authentication": "oauth:<auth>",
"Cooldown": 20,
"X-Access-Token": "<accessToken>",
"AllowedRanks": [
"broadcaster",
"moderator",
"vip"
],
"AllowedUsers": [],
"CustomPrompt": "You are Bot, a wizard living in the kingdom of Larion. You have a staff and a spellbook. You finish your long journey and finally arrive at the ruin you've been looking for. You look around and see that it's not much different than when you left it. A few more trees here and there, but nothing has changed."
}
f.write(json.dumps(standard_dict, indent=4, separators=(",", ": ")))
raise ValueError("Please fix your settings.json file that was just generated.")
return False
class Settings:
""" Loads data from settings.json into the bot """
PATH = os.path.join(os.getcwd(), "settings.json")
def __init__(self, bot):
with FileErrorHandler():
# Try to load the file using json.
# And pass the data to the Bot class instance if this succeeds.
logger.debug("Starting setting settings...")
with open(Settings.PATH, "r") as f:
settings = f.read()
data = json.loads(settings)
bot.set_settings(data["Host"],
data["Port"],
data["Channel"],
data["Nickname"],
data["Authentication"],
data["Cooldown"],
data["X-Access-Token"],
data["AllowedRanks"],
data["AllowedUsers"],
data["CustomPrompt"])
logger.debug("Finished setting settings.")
@staticmethod
def update_cooldown(cooldown):
with FileErrorHandler():
logger.info(f"Updating cooldown to {cooldown}s...")
with open(Settings.PATH, "r") as f:
settings = f.read()
data = json.loads(settings)
data["Cooldown"] = cooldown
with open(Settings.PATH, "w") as f:
f.write(json.dumps(data, indent=4, separators=(",", ": ")))
logger.info(f"Finished updating cooldown.")
@staticmethod
def get_channel():
with FileErrorHandler():
with open(Settings.PATH, "r") as f:
settings = f.read()
data = json.loads(settings)
return data["Channel"].replace("#", "").lower()
@staticmethod
def set_logger():
# Update logger. This is required as this class is used to set up the logging file
global logger
logger = logging.getLogger(__name__)