-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathcog.py
178 lines (161 loc) · 6.43 KB
/
cog.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""
Cog for dynamically changing config.
"""
import re
import shlex
from typing import Any
import disnake
import toml
from disnake.ext import commands
from cogs.base import Base
from config.app_config import CONFIG_PATH, config_get_keys, load_config
from rubbergod import Rubbergod
from utils.checks import PermissionsCheck
from .messages_cz import MessagesCZ
async def autocomp_keys(inter: disnake.ApplicationCommandInteraction, user_input: str) -> list[str]:
return [key for key in config_get_keys() if user_input.lower() in key][:25]
class DynamicConfig(Base, commands.Cog):
def __init__(self, bot: Rubbergod):
super().__init__()
self.bot = bot
@PermissionsCheck.is_bot_admin()
@commands.slash_command(name="config")
async def config_cmd(self, inter: disnake.ApplicationCommandInteraction):
"""
Group of commands for dynamically changing config
"""
pass
@config_cmd.sub_command(name="set", description=MessagesCZ.set_brief)
async def set_value(
self,
inter: disnake.ApplicationCommandInteraction,
key: str = commands.Param(autocomplete=autocomp_keys),
value: str = commands.Param(),
):
"""
Dynamically change config values
"""
await self.change_value(inter, key, value, False)
load_config()
@config_cmd.sub_command(description=MessagesCZ.append_brief)
async def append(
self,
inter: disnake.ApplicationCommandInteraction,
key: str = commands.Param(autocomplete=autocomp_keys),
value: str = commands.Param(),
):
"""
Append value(s) to existing config
For string and int types command has same behaviour as `set_value`.
"""
await self.change_value(inter, key, value, True)
load_config()
@config_cmd.sub_command(description=MessagesCZ.load_brief)
async def load(self, inter: disnake.ApplicationCommandInteraction):
"""
Load config from `config.toml`
"""
load_config()
await inter.send(MessagesCZ.config_loaded)
@config_cmd.sub_command(name="list", description=MessagesCZ.list_brief)
async def list_all(self, inter: disnake.ApplicationCommandInteraction, regex: str = None):
if regex is not None:
try:
regex_pat = re.compile(regex)
except re.error as ex:
await inter.send(MessagesCZ.list_invalid_regex(regex_err=str(ex)))
return
output = "```\n"
for key in config_get_keys()[:]:
if regex_pat is None or regex_pat.match(key) is not None:
output += key + "\n"
output += "```"
await inter.send(output)
@config_cmd.sub_command(description=MessagesCZ.get_brief)
async def get(
self,
inter: disnake.ApplicationCommandInteraction,
key: str = commands.Param(autocomplete=autocomp_keys),
):
"""
Get value of specified key
"""
if not hasattr(self.config, key) or key in self.config.config_static:
await inter.send(MessagesCZ.wrong_key)
return
value = getattr(self.config, key)
embed = disnake.Embed(title=key, description=str(value))
await inter.send(embed=embed)
@config_cmd.sub_command(description=MessagesCZ.sync_template_brief)
async def update(self, inter: disnake.ApplicationCommandInteraction):
template_path = self.config_dir.joinpath("config.template.toml")
template = toml.load(template_path, _dict=dict)
for section in template:
if section in self.config.toml_dict:
for key in template[section]:
if key not in self.config.toml_dict[section]:
self.config.toml_dict[section][key] = template[section][key]
else:
self.config.toml_dict[section] = template[section]
with open(CONFIG_PATH, "w+", encoding="utf-8") as fd:
toml.dump(self.config.toml_dict, fd)
load_config()
await inter.send(MessagesCZ.config_updated)
async def change_value(
self, inter: disnake.ApplicationCommandInteraction, key: str, value: str, append: bool
):
"""
Changes config attribute specified by `key` to `value`.
If `append` values are appended to current setting.
"""
if not hasattr(self.config, key) or key in self.config.config_static:
await inter.send(MessagesCZ.wrong_key)
return
try:
new_val: Any = shlex.split(value)
except Exception as e:
await inter.send(e)
return
key_toml = key
key_split = key.split("_", 1)
for section in self.config.toml_dict:
if key_split[0] == section:
key_toml = key_split[1]
if key_toml in self.config.toml_dict[section]:
attr = getattr(self.config, key)
if isinstance(attr, list):
if isinstance(attr[0], int):
for idx, item in enumerate(new_val):
try:
new_val[idx] = int(item)
except ValueError:
await inter.send(MessagesCZ.wrong_type)
return
if append:
new_val = attr + new_val
elif isinstance(attr, tuple) and append:
new_val = tuple(list(attr) + new_val)
elif isinstance(attr, str):
new_val = " ".join(new_val)
elif isinstance(attr, bool):
if new_val[0].lower() == "false":
new_val = False
else:
new_val = True
elif isinstance(attr, int):
try:
new_val = int(new_val[0])
except ValueError:
await inter.send(MessagesCZ.wrong_type)
return
self.config.toml_dict[section][key_toml] = new_val
break
else:
key_toml = key
else:
await inter.send(MessagesCZ.wrong_key)
return
setattr(self.config, key, new_val)
with open(CONFIG_PATH, "w+", encoding="utf-8") as fd:
toml.dump(self.config.toml_dict, fd)
await inter.send(MessagesCZ.config_updated)