-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.py
282 lines (211 loc) · 8.01 KB
/
run.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
from argparse import ArgumentParser
from contextlib import closing
from json import loads
from os import chdir
from random import randint
from socket import socket, AF_INET, SOCK_STREAM
from string import ascii_lowercase, ascii_uppercase, digits
from subprocess import run
from sys import argv
def main():
parser = get_parser()
args = parser.parse_args()
user_config_list = handle_user_config(args.action)
if user_config_list is None:
print(
"config.json must exist in main directory (same as this script), and must be fully specified. See 'WidenBot Config' section of README.md"
)
return
if args.action == "start":
run_all_bots(user_config_list)
elif args.action == "stop":
stop_all_bots(user_config_list)
else:
# Validate provided label
labels = list()
for user_config in user_config_list:
labels.append(user_config["label"])
if args.label not in labels:
parser.print_help()
return
try:
run(
[
"docker",
"logs",
get_container_name(args.label, args.type),
"--follow",
]
)
except KeyboardInterrupt:
return
def get_parser():
parser = ArgumentParser(
prog="run.py",
description="Run script for WidenBot.",
epilog="Visit https://github.com/cgwhouse/widen-bot for setup instructions.",
)
parser.add_argument(
"action",
type=str,
choices=["start", "stop", "logs"],
help="The 'start' / 'stop' actions start or stop all WidenBots in config.json, and 'logs' shows specific client or server container logs in --follow mode.",
)
action_is_logs = "run.py logs" in " ".join(argv)
parser.add_argument(
"-l",
"--label",
required=action_is_logs,
type=str,
help="The WidenBot instance whose logs should be viewed.",
)
parser.add_argument(
"-t",
"--type",
required=action_is_logs,
type=str,
choices=["client", "server"],
help="Whether to view client or server logs.",
)
return parser
def handle_user_config(action):
try:
user_config_list = loads(get_file_contents("config.json"))
# Only need to validate label and isEnabled if stopping bots or viewing logs
if action != "start":
for user_config in user_config_list:
if user_config["label"] == "" or not user_config["label"].isalnum():
return None
if user_config["isEnabled"] == "":
return None
if not user_config["isEnabled"]:
print(
f"...Skipping {user_config['label']} because isEnabled is false"
)
continue
return user_config_list
# Start at 80 and increment by 1 for each bot in the array
current_port = 80
# Validate each config in the array
for user_config in user_config_list:
if user_config["label"] == "" or not user_config["label"].isalnum():
return None
if user_config["isEnabled"] == "":
return None
if not user_config["isEnabled"]:
print(f"...Skipping {user_config['label']} because isEnabled is false")
continue
if user_config["useSponsorBlock"] == "":
return None
if (
user_config["discord"]["serverID"] == ""
or user_config["discord"]["botToken"] == ""
):
return None
if (
user_config["spotify"]["clientID"] == ""
or user_config["spotify"]["clientSecret"] == ""
):
return None
# Generate new password for this run
alphanumerics = list(ascii_lowercase + ascii_uppercase + digits)
password = ""
for _ in range(15):
password += alphanumerics[randint(0, len(alphanumerics) - 1)]
user_config["password"] = password
# Make sure current_port is available, otherwise move on to next
while True:
with closing(socket(AF_INET, SOCK_STREAM)) as sock:
if sock.connect_ex(("127.0.0.1", current_port)) == 0:
current_port += 1
else:
print(
f"Found port {current_port} for WidenBot instance {user_config['label']}!"
)
break
user_config["clientPort"] = current_port
current_port += 1
return user_config_list
except (FileNotFoundError, KeyError, TypeError, ValueError):
return None
def run_all_bots(user_config_list):
print("Starting WidenBot...")
chdir("./src")
labels = list()
for user_config in user_config_list:
# Check enabled flag and skip
if not user_config["isEnabled"]:
continue
labels.append(user_config["label"])
# Lavalink application.yml
write_application_yml(
user_config["spotify"]["clientID"], user_config["spotify"]["clientSecret"]
)
# Docker .env file
write_env_file(user_config)
run(
[
"docker",
"compose",
"-p",
user_config["label"],
"up",
"--build",
"--force-recreate",
"--detach",
]
)
print(f"\nWidenBot instance(s) {', '.join(labels)} are now running!")
def stop_all_bots(user_config_list):
for user_config in user_config_list:
# Check enabled flag and skip
if not user_config["isEnabled"]:
continue
label = user_config["label"]
for type in ["client", "server"]:
run(
[
"docker",
"container",
"kill",
get_container_name(label, type),
]
)
print(f"WidenBot instance {label} has been stopped.")
def write_application_yml(client_id, client_secret):
spotify_client_id = "SPOTIFY_CLIENT_ID"
spotify_client_secret = "SPOTIFY_CLIENT_SECRET"
lavalink_config_raw = get_file_contents("application.template.yml")
lavalink_config_updated = lavalink_config_raw.replace(
spotify_client_id, client_id
).replace(spotify_client_secret, client_secret)
write_file_contents("application.yml", lavalink_config_updated)
def write_env_file(user_config):
env_file_contents = f"INSTANCE_LABEL={user_config['label']}\n"
env_file_contents += f"USE_SPONSORBLOCK={user_config['useSponsorBlock']}\n"
env_file_contents += f"DISCORD_SERVER_ID={user_config['discord']['serverID']}\n"
env_file_contents += f"DISCORD_BOT_TOKEN={user_config['discord']['botToken']}\n"
# If provided, inject requiredChannel too
# Set to initial dummy value to prevent Docker warning
required_channel = "none"
if (
"requiredChannel" in user_config["discord"]
and user_config["discord"]["requiredChannel"] is not None
):
required_channel = user_config["discord"]["requiredChannel"]
env_file_contents += f"REQUIRED_CHANNEL={required_channel}\n"
# Internally managed env vars, users don't mess with these directly
env_file_contents += f"CLIENT_PORT={user_config['clientPort']}\n"
env_file_contents += f"LAVALINK_PASSWORD={user_config['password']}\n"
write_file_contents(".env", env_file_contents)
def get_file_contents(path):
with open(path, "r") as f:
raw = f.read()
return raw
def write_file_contents(path, contents):
with open(path, "w") as f:
f.write(contents)
def get_container_name(label, type):
return f"{label}-widenbot-{type}"
if __name__ == "__main__":
main()