Repository navigation
Expand file tree
/
Copy pathrun_bot.py
More file actions
365 lines (297 loc) · 15.6 KB
/
Copy pathrun_bot.py
File metadata and controls
365 lines (297 loc) · 15.6 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#!/usr/bin/python3
__version__ = '9.0.3'
__date__ = '02/11/2023'
__license__ = 'GPL 3'
__author__ = 'github.com/0n1udra'
__discord__ = 'https://discord.gg/s58XgzhE3U' # Join for bot help (if i'm online :)
import os
import sys
import platform
import subprocess
from bot_files.config import config
from bot_files.utils import lprint, utils, file_utils, proc_utils
class Run_Bot:
def __init__(self):
self.watch_interval = 1 # for log runtime arg. watch -n X tail bot_log.txt
self.dev_mode = ''
if 'dev' in sys.argv:
self.dev_mode = 'dev'
# Use Windows config file.
if platform.system() == 'Windows' and self.dev_mode:
config._win_mode = True
# Asks for some basic configs if no config file found.
if not config.update_from_file() or config.get_config('init') is False:
lprint("INFO: Initializing config.")
self.config_prompts() # This will call config.update_all_configs which will creates user_config.json if not exist.
else: lprint("INFO: Loaded user_config.json.")
# Start bot in a tmux or screen session or else in line.
self.bot_session = ''
if config.get_config('bot_use_tmux'):
self.bot_session = 'tmux'
elif config.get_config('bot_use_screen'):
self.bot_session = 'screen'
self.tmux_name = config.get_config('bot_tmux_name')
self.tmux = f"{self.tmux_name}:{config.get_config('bot_tmux_pane')}"
self.screen_name = config.get_config('bot_screen_name')
self.parse_runtime_args()
def parse_runtime_args(self):
# The order of the if statements is important.
# Hides banner
if 'hidebanner' not in sys.argv:
if config.get_config('use_pyenv'):
if sys.prefix == sys.base_prefix:
self.show_banner()
else: self.show_banner()
# Use custom token and configs.
if self.dev_mode:
# In dev mode, you can set a different token here if needed
lprint("INFO: Using dev mode.")
# Setup needed folders: servers, server_backups, world_backups
if 'makefolders' in sys.argv:
if config.get_config('use_sftp'):
lprint("INFO: Folder setup not needed for SFTP configuration")
else:
file_utils.setup_directories()
return
if 'startbot' in sys.argv:
self.start_bot()
# Start Discord bot task directly.
if '_startbot' in sys.argv:
self._start_bot()
# Background process method (using nohup)
if 'stopbot' in sys.argv:
proc_utils.kill_slime_proc()
if 'statusbot' in sys.argv:
proc_utils.status_slime_proc()
# Show live view of bot log using watch and tail command.
if 'log' in sys.argv:
self.show_log()
# TODO add attach args for server tmux and screen.
if 'attachbot' in sys.argv:
self.attach_bot()
if 'attachserver' in sys.argv:
self.attach_server()
# Show help page.
if 'help' in sys.argv:
self.script_help()
def config_prompts(self) -> None:
"""if 'init' variable in configs is False, asks user to setup basic configs."""
# Creates flatten dict to make it easier to find items to use as defaults
def get_input(config_promptss):
new_configs = {}
for variable, prompt in config_promptss.items():
parts = prompt.split(':')
if len(parts) > 1:
prompt = parts[1].strip()
config_key = parts[0]
negate_config = '!' in config_key
# Specified config must be false for current prompt to show
if negate_config and new_configs.get(config_key.split('!')[1]):
continue
# Show prompt only if specified config is true.
elif not negate_config and not new_configs.get(config_key):
continue
default_value = config.get_config(variable)
input_type = type(default_value)
config_input = input(
f"{prompt} [{default_value}]: ").strip() or default_value # Uses default value if enter nothing.
if input_type is bool:
if str(config_input).lower() in ['y', 'yes'] or config_input is True:
new_configs[variable] = True
if str(config_input).lower() in ['n', 'no']:
new_configs[variable] = False
else:
try:
new_configs[variable] = input_type(
config_input) if input_type else config_input # Converts to needed type.
except:
new_configs[variable] = default_value
print("Using default:", default_value)
return new_configs
# Some questions can be skipped, like how pyenv_python_path prompt will only show if user says yes to use_pyenv.
# Add the config with colon, and get_input() will split the prompt and check the prior received inputs. Order of prompts is important.
# A ! means skip prompt if specified config was answered. E.g. !bot_use_screen will be skipped if bot_use_tmux is True.
bot_config_promptss = {
'use_pyenv': "Use Python env (y/n)",
'pyenv_python_path': 'use_pyenv: Path to python3 executable (e.g. .../venv/slime/bin/python3)',
'bot_token': "Discord bot token (get from https://discord.com/developers/applications)",
'command_prefix': "Discord command prefix",
'use_sftp': "Use SFTP for remote server management (y/n)",
'sftp_host': 'use_sftp: SFTP server hostname/IP',
'sftp_username': 'use_sftp: SFTP username',
'sftp_password': 'use_sftp: SFTP password (leave empty if using key auth)',
'remote_server_path': 'use_sftp: Remote server base path (e.g. /home/minecraft/servers)',
'bot_use_tmux': "Run bot using Tmux (y/n)",
'bot_tmux_name': "bot_use_tmux: Tmux session name for bot",
'bot_use_screen': "!bot_use_tmux: Run bot using Screen (y/n)",
'bot_screen_name': 'bot_use_screen: Screen session name for bot',
}
server_config_promptss = { # Optionally setup server
'server_name': 'Server name',
'server_description': 'Server description',
'server_address': 'Server domain/IP',
'server_port': 'Server port',
'server_use_rcon': 'Use RCON (y/n)',
'rcon_pass': 'server_use_rcon: RCON password',
'rcon_port': 'server_use_rcon: RCON Port',
'server_use_tmux': "Run server using Tmux (y/n)",
'server_tmux_name': "server_use_tmux: Tmux session name for server",
'server_use_screen': "!server_use_tmux: Run server using Screen (y/n)",
'server_screen_name': 'server_use_screen: Screen session name for server',
'server_use_subprocess': "!server_use_tmux: Run server subprocess (y/n)",
}
print("----- Config Setup -----\nPress enter to use default.")
configs = get_input(bot_config_promptss)
# Asks to continue to server configs
ask_input = input(f"\nContinue to server config (y/n) [False]: ").strip().lower()
if ask_input in ['y', 'yes']:
new_server_config = get_input(server_config_promptss)
config.new_server_configs(new_server_config['server_name'], new_server_config)
# Initialize configs (no longer need mc_path parameter)
config.bot_configs.update(configs)
config.set_config('init', True)
config.update_all_configs() # Updates paths configs, and writes to file.
def start_bot(self) -> None:
"""Uses different methods of launching Discord bot depending on config"""
if 'tmux' in self.bot_session:
if not self.start_bot_tmux():
return
elif 'screen' in self.bot_session:
if not self.start_bot_screen():
return
else: self._start_bot()
def _start_bot(self, launch=None) -> None:
"""Starts Discord bot. This is a separate function incase you want to run the bot inline."""
# If using virtual environment
if config.get_config('use_pyenv'):
# Runs run_bot.py _startbot if not already in venv.
if sys.prefix == sys.base_prefix:
subprocess.run([config.get_config('pyenv_python_path'), f"{config.get_config('bot_source_path')}/run_bot.py", "_startbot"])
sys.exit()
TOKEN = config.get_config('bot_token')
if not TOKEN:
lprint("ERROR: Discord bot token not configured. Please set 'bot_token' in your configuration.")
sys.exit()
lprint("INFO: Using configured Discord Token")
from bot_files.bot import bot
bot.run(TOKEN, reconnect=True)
def start_bot_tmux(self) -> bool:
"""Start bot in tmux session."""
if utils.start_tmux_session(self.tmux_name) is False:
return False
if os.system(f"tmux send-keys -t {self.tmux} 'cd {config.get_config('bot_source_path')}' ENTER"):
lprint(f"ERROR: Changing directory {config.get_config('bot_source_path')}")
return False
if os.system(f"tmux send-keys -t {self.tmux} '{config.get_config('bot_launch_command')} {self.dev_mode}' ENTER"):
lprint("ERROR: Could not start bot in tmux.")
return False
else: lprint("INFO: Started Discord bot.")
return True
def start_bot_screen(self) -> bool:
"""Start bot in screen session."""
if os.system(f"screen -dmS '{self.screen_name}' {config.get_config('bot_launch_command')}"):
lprint(f"ERROR: Could not start server with screen: {self.screen_name}")
return False
lprint(f"INFO: Started bot in screen session: {self.screen_name}")
return True
def attach_bot(self) -> None:
"""Attaches to tmux/screen session containing bot."""
if 'tmux' in self.bot_session:
if os.system(f"tmux a -t {self.tmux_name}"):
lprint(f"ERROR: Unable to attach to tmux session: {self.tmux_name}")
elif 'screen' in self.bot_session:
if os.system(f"screen -r {self.screen_name}"):
lprint(f"ERROR: Unable to attach to screen session {self.screen_name}")
def attach_server(self) -> None:
"""Attaches to tmux/screen session containing server."""
if config.get_config('server_use_tmux'):
if os.system(f"tmux a -t {config.get_config('server_tmux_name')}"):
lprint(f"ERROR: Unable to attach to tmux session: {self.tmux_name}")
elif config.get_config('server_use_screen'):
if os.system(f"screen -r {config.get_config('server_screen_name')}"):
lprint(f"ERROR: Unable to attach to screen session {self.screen_name}")
def show_log(self) -> None:
"""Use watch + tail command on bot log."""
os.system(f"watch -n {self.watch_interval} tail {config.get_config('bot_log_filepath')}")
def script_help(self) -> None:
"""Shows help page for run_bot.py"""
help = """
python3 run_bot.py setup download startboth -- Create required folders, downloads latest server.jar, and start server and bot with Tmux.
python3 run_bot.py tmuxstart startboth tmuxattach -- Start Tmux session, start server and bot, then attaches to Tmux session.
help - Shows this help page.
makefolders - Create necessary folders. Starts Tmux session in detached mode with 2 panes.
startbot - Creates tmux or screen session and launches Discord bot.
stopbot - Stops Discord bot.
attachbot - Attaches to session containing bot (tmux or screen).
attachserver - Attaches to session containing server (tmux or screen).
log - Show bot log using 'watch -n X tail .../bot_log.txt' command. To get out of it, use ctrl + c.
Use standalone, showlog will not work properly if used with other arguments.
NOTE: The corresponding functions will run in the order you pass arguments in.
For example, 'python3 run_bot.py startbot tmuxattach tmuxstart' won't work because the script will try to start the server and bot in a Tmux session that doesn't exist.
Instead run 'python3 tmuxstart startboth tmuxattach', start Tmux session then start server and bot, then attach to Tmux session.
"""
print(help)
def show_banner(self) -> None:
"""Shows banner containing some bot config."""
# Hides sensitive info from output.
nono = config.get_config('show_sensitive_info') # what? got a problem with the naming? it works.
no = '**********' # 2bad. change it!
vars_msg = f"""
NOTE: More config info in README.md or read comments in config.py file in bot_files.
Bot:
Version {__version__} - {__date__}
Python Env {config.get_config('pyenv_python_path') if config.get_config('use_pyenv') else 'None'}
Config File: {config.get_config('user_config_filepath')}
Bot Log {config.get_config('bot_log_filepath')}
Tmux {config.get_config('bot_use_tmux')}
Screen {config.get_config('bot_use_screen')}
Windows Mode {config.get_config('windows_compatibility')}
Discord:
Discord Token {config.get_config('bot_token_filepath')}
Command Prefix {config.get_config('command_prefix')}
Case Insensitive {config.get_config('case_insensitive')}
Channel ID {config.get_config('channel_id') if nono else no}
Show Custom Status {config.get_config('check_before_command')} - {config.get_config('custom_status_interval')}min
Disabled Commands {', '.join(config.get_config('disabled_commands'))}
"""
if config.get_config('bot_use_tmux'): vars_msg += f"""
Bot Tmux:
Name and pane {self.tmux}
"""
if config.get_config('bot_use_screen'): vars_msg += f"""
Bot Screen:
Session Name {config.get_config('bot_screen_name')}
"""
vars_msg += f"""
Server:
File Access {config.get_config('server_files_access')}
Autosave {config.get_config('enable_autosave')} - {config.get_config('autosave_interval')}min
Server URL {config.get_config('server_address') if nono else no}
Server Port {config.get_config('server_port') if nono else no}
RCON {config.get_config('server_use_rcon')}
Tmux {config.get_config('server_use_tmux')}
Screen {config.get_config('server_use_screen')}
Subprocess {config.get_config('server_use_subprocess')}
"""
if config.get_config('server_use_tmux'): vars_msg += f"""
Server Tmux:
Name and pane {config.get_config('server_tmux_name')}:{config.get_config('server_tmux_pane')}
"""
if config.get_config('server_use_screen'): vars_msg += f"""
Server Screen:
Session Name {config.get_config('server_screen_name')}
"""
if config.get_config('server_use_rcon'): vars_msg += f"""
Server RCON:
Pass {config.get_config('rcon_pass') if nono else no}
Port {config.get_config('rcon_port') if nono else no}
"""
if config.get_config('use_sftp'): vars_msg += f"""
SFTP Configuration:
Host {config.get_config('sftp_host')}
Username {config.get_config('sftp_username')}
Remote Path {config.get_config('remote_server_path')}
"""
print(vars_msg)
if __name__ == '__main__':
slime = Run_Bot()