-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbotHandler.py
568 lines (530 loc) · 32.2 KB
/
botHandler.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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#########################
# R8DIUM : Run8 Database for Integrated User Management
#
# Copyright (C) 2023, S. Joshua Stein, <[email protected]>
#
# This file is part of the R8DIUM software tool suite.
#
# R8DIUM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
#
# R8DIUM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with R8DIUM.
# If not, see <https://www.gnu.org/licenses/>.
##########################
import datetime
import discord
from discord.ext import commands, tasks # noqa
import asyncio # noqa
import dbAccess
import msgHandler
import pathlib
import psutil
import r8diumInclude
from r8diumInclude import (TOKEN, BAN_SCAN_TIME, SOFTWARE_VERSION, CH_ADMIN, CH_LOG, R8SERVER_ADDR, R8SERVER_PORT,
R8SERVER_NAME, R8SERVER_LOG, R8SERVER_PATH, R8SERVER_SECURITY_FNAME, R8SERVER_WORLD_FNAME,
R8SERVER_INDUSTRY_FNAME, R8SERVER_HUMP_FNAME, R8SERVER_TRAFFIC_FNAME, DB_FILENAME,
LOG_SCAN_TIME, INACT_DAYS, EXP_SCAN_TIME, UID_PURGE_TIME, BOT_STATUS, LOG_FILE, USER_DB)
import subprocess
discord_char_limit = 1900
hsf_mtime = {}
tmp_filename = 'user_list.txt' # File to hold long user list for sending to Discord (avoiding character limit)
def log_message(interaction) -> str:
log_msg = f'**{interaction.user.name} ({interaction.user.display_name})** executed: `{interaction.command.name} '
if 'options' in interaction.data:
for parm in interaction.data['options']:
log_msg += f'{parm["value"]} '
log_msg = log_msg[:-1]
log_msg += f'` in channel: *{interaction.channel}*'
msgHandler.write_log_file(log_msg) # Write the same message to our local log file
return log_msg
def run_discord_bot(ldb):
from discord import app_commands
from discord.ext import commands
client = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@client.event
async def on_ready():
print(f'Discord bot [{client.user}] is starting')
# Discord bot activity status
if BOT_STATUS:
await client.change_presence(activity=discord.Game(BOT_STATUS))
# Populate the dict with current host file modification timestamps
for filename in r8diumInclude.SECURITY_FILE:
hsf_mtime[filename] = pathlib.Path(filename).stat().st_mtime
msgHandler.write_log_file(f'------------------')
msgHandler.write_log_file(f'R8DIUM [{SOFTWARE_VERSION}] starting')
msgHandler.write_log_file(f'Discord bot [{client.user}] is now running')
try:
command_list = await client.tree.sync()
print(f'Registered {len(command_list)} command(s)')
msgHandler.write_log_file(f'Registered {len(command_list)} command(s)')
except Exception as e:
print(e)
print(f'Starting banned user periodic checks')
msgHandler.write_log_file(f'Starting banned user periodic checks')
scan_banned_users.start(ldb)
print(f'Starting log-in periodic checks')
msgHandler.write_log_file(f'Starting log-in periodic checks')
scan_logins.start(ldb)
if int(INACT_DAYS) > 0: # Not all server admins want to auto-expire users
print(f'Starting expired user checks')
msgHandler.write_log_file(f'Starting expired user checks')
expire_users.start(ldb)
if int(UID_PURGE_TIME) > 0: # Not all server admins want to purge UIDs from HostSecurity file
print(f'Starting UID purge daemon')
msgHandler.write_log_file(f'Starting UID purge daemon')
clean_uids.start(ldb)
dbAccess.send_statistics(ldb)
@client.event
async def on_member_remove(member):
if msgHandler.suspend_user(str(member.id), datetime.date.today(), 'Left discord server', ldb) > 0:
discord_name = dbAccess.get_element(str(member.id), dbAccess.discord_id, dbAccess.discord_name, ldb)
msg = f' R8DIUM BOT has set {discord_name} to INACTIVE due to leaving server'
channel_id = discord.utils.get(client.get_all_channels(), name=CH_ADMIN).id
admin_channel = client.get_channel(channel_id)
msgHandler.write_log_file(msg)
await admin_channel.send(msg)
if CH_LOG != 'none':
channel_id = discord.utils.get(client.get_all_channels(), name=CH_LOG).id
log_channel = client.get_channel(channel_id)
await log_channel.send(msg)
@tasks.loop(seconds=int(LOG_SCAN_TIME))
async def scan_logins(ldb):
for log_file in R8SERVER_LOG:
write_db = False
fp = open(log_file, 'r')
for line in fp.readlines():
if 'Name' in line and 'PW:' in line: # This is a log in status message
lft_line = line.split(',')[0] # Chunk up the line into useful parts
rt_line = line.split(',', 1)[1] # Very fragile due to the dependency on the log file format
raw_date = lft_line.split(' ')[
0] # This date shows up as YYYY-MM-DD which is different than how we store
date = datetime.datetime.strptime(raw_date, '%Y-%m-%d').strftime('%#m/%#d/%y')
time = lft_line.split(' ')[1]
name = rt_line.split('Name:')[1].split(' PW:')[0]
pw = rt_line.split('PW:')[1].split(' UID:')[0]
uid = rt_line.split('UID:')[1].split(' IP:')[0]
ip = rt_line.split('::ffff:')[1].split(']:')[0]
# print(f'{date} : {time} : {name} : {pw} : {uid} : {ip}')
last_login = dbAccess.get_element(pw, dbAccess.password, dbAccess.last_login, ldb)
if last_login == '':
last_login = '1/1/00'
# What to do if the password isn't found? Possible if the user changed pass in-between scans
# For now, just ignoring. Should eventually sync up
if last_login != -1:
log_date = datetime.datetime.strptime(date, '%m/%d/%y')
last_date = datetime.datetime.strptime(last_login, '%m/%d/%y')
if (log_date - last_date).days > 0:
dbAccess.set_element(pw, dbAccess.password, dbAccess.last_login, date, ldb)
dbAccess.set_element(pw, dbAccess.password, dbAccess.ip, ip, ldb)
dbAccess.set_element(pw, dbAccess.password, dbAccess.run8_name, name, ldb)
msg = f'Updating login info for ' \
f'{dbAccess.get_element(pw, dbAccess.password, dbAccess.discord_name, ldb)} from ' \
f'file {log_file}'
msgHandler.write_log_file(msg)
write_db = True
if write_db:
dbAccess.save_db(DB_FILENAME, ldb)
fp.close()
return
@tasks.loop(minutes=int(EXP_SCAN_TIME))
async def expire_users(ldb):
today = datetime.datetime.today()
today_str = datetime.datetime.strftime(today, '%m/%d/%y')
for line in ldb:
discord_id = line['discord_id']
last_active = dbAccess.get_element(discord_id, dbAccess.discord_id, dbAccess.last_login, ldb)
if last_active == '': # Handling a blank last_active by comparing to today's date
last_active = today_str
diff = (today - datetime.datetime.strptime(last_active, '%m/%d/%y')).days
if diff > int(INACT_DAYS) and \
dbAccess.get_element(discord_id, dbAccess.discord_id, dbAccess.active, ldb) != 'False':
discord_name = dbAccess.get_element(discord_id, dbAccess.discord_id, dbAccess.discord_name, ldb)
msg = f'Automated scan set user {discord_name} to INACTIVE; last login : {last_active}'
msgHandler.write_log_file(msg)
channel_id = discord.utils.get(client.get_all_channels(), name=CH_ADMIN).id
admin_channel = client.get_channel(channel_id)
await admin_channel.send(msg)
if CH_LOG != 'none':
channel_id = discord.utils.get(client.get_all_channels(), name=CH_LOG).id
log_channel = client.get_channel(channel_id)
await log_channel.send(msg)
msgHandler.expire_user(discord_id, today_str, ldb)
return
@tasks.loop(seconds=int(UID_PURGE_TIME))
async def clean_uids(local_db):
for filename in r8diumInclude.SECURITY_FILE:
current_mtime = pathlib.Path.stat(filename).st_mtime
if current_mtime != hsf_mtime[filename]:
print(f'clean_uid daemon: purging HostSecurity file(s) of UIDs')
msgHandler.write_log_file(f'clean_uid daemon: purging HostSecurity file(s) of UIDs')
dbAccess.write_security_file(local_db, purge_uids=True)
for key in hsf_mtime:
hsf_mtime[key] = pathlib.Path.stat(filename).st_mtime
break
@tasks.loop(seconds=int(BAN_SCAN_TIME))
async def scan_banned_users(local_db):
if type(local_db) is not list: # local_db must be empty - showing as NoneType
return
for record in local_db:
if record[dbAccess.banned] == 'True':
if not msgHandler.check_ban_status(record[dbAccess.sid], local_db):
msg = f'Automated scan **unbanned** {record[dbAccess.discord_name]} due to ' \
f'time served ({record[dbAccess.ban_duration]} days)'
msgHandler.write_log_file(msg)
channel_id = discord.utils.get(client.get_all_channels(), name=CH_ADMIN).id
admin_channel = client.get_channel(channel_id)
await admin_channel.send(msg)
if CH_LOG != 'none':
channel_id = discord.utils.get(client.get_all_channels(), name=CH_LOG).id
log_channel = client.get_channel(channel_id)
await log_channel.send(msg)
msgHandler.unban_user(record[dbAccess.discord_id], 'Automated check', local_db)
@client.tree.command(name='bot_commands', description=f'Show all commands available')
async def bot_commands(interaction: discord.Interaction):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = ''
command_list = await client.tree.fetch_commands()
for command in command_list:
response += f'**{command.name}** : *{command.description}*\n'
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='list_users', description=f'List all users in database')
async def list_users(interaction: discord.Interaction):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.list_users(ldb)
if len(response) > discord_char_limit:
tf = open(tmp_filename, 'w')
tf.write(response)
tf.close()
await interaction.response.send_message(file=discord.File(tmp_filename), ephemeral=True) # noqa
else:
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='read_notes',
description=f'Display all notes for user @id')
@app_commands.describe(member='@id')
async def read_notes(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = '* ' + msgHandler.show_notes(str(member.id), ldb).replace('|', '\n* ')
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='write_note',
description=f'write note about @id')
@app_commands.describe(member='@id',
note='Note to add to user data')
async def write_note(interaction: discord.Interaction, member: discord.Member, note: str):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.add_note(str(member.id), note, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='show_user',
description=f'Display all fields for user @id')
@app_commands.describe(member='@id')
async def show_user(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.show_user(str(member.id), ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='show_user_by_sid',
description=f'Display all fields for user server id <sid>')
@app_commands.describe(sid='server id number')
async def show_user_by_sid(interaction: discord.Interaction, sid: int):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.show_user_by_id(sid, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='add_user',
description=f'Add a new user <discord_id>')
@app_commands.describe(member='@id')
async def add_user(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
discord_name = await client.fetch_user(member.id)
response = msgHandler.add_user(str(member.id), discord_name, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='change_role',
description=f'Set role <role_str> to user @id')
@app_commands.describe(member='@id', role='role name')
async def change_role(interaction: discord.Interaction, member: discord.Member, role: str):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.add_role(str(member.id), role, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='del_user',
description=f'Delete user @id')
@app_commands.describe(member='@id')
async def del_user(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.delete_user(str(member.id), ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='ban_user',
description=f'ban user @id <duration(days)> <reason(string)>')
@app_commands.describe(member='@id',
duration='Length of ban in days',
reason='Reason for ban (short description)')
async def ban_user(interaction: discord.Interaction, member: discord.Member, duration: int, reason: str):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if dbAccess.get_element(str(member.id), dbAccess.discord_id, dbAccess.banned, ldb) != 'True':
response = msgHandler.ban_user(str(member.id), interaction.user.name, duration, reason, ldb)
# Write a message on the admin channel letting other admins know a user has been banned
admin_channel = discord.utils.get(interaction.guild.channels, name=CH_ADMIN)
await admin_channel.send(response)
else:
response = f'*{member.name}* **is already banned** - ignoring request'
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='unban_user',
description=f'unban user @id')
@app_commands.describe(member='@id')
async def unban_user(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if dbAccess.get_element(str(member.id), dbAccess.discord_id, dbAccess.banned, ldb) != 'False':
response = msgHandler.unban_user(str(member.id), interaction.user.name, ldb)
# Write a message to the admin channel letting other admins know a user has been un-banned
admin_channel = discord.utils.get(interaction.guild.channels, name=CH_ADMIN)
await admin_channel.send(response)
else:
response = f'*{member.name}* is **not currently banned** - ignoring request'
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='reactivate_user',
description=f'reactivate user @id')
@app_commands.describe(member='@id')
async def reactivate_user(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if dbAccess.get_element(str(member.id), dbAccess.discord_id, dbAccess.active, ldb) != 'True':
response = msgHandler.activate_user(str(member.id), interaction.user.name, ldb)
# Write a message to the admin channel letting other admins know a user has been un-banned
admin_channel = discord.utils.get(interaction.guild.channels, name=CH_ADMIN)
await admin_channel.send(response)
else:
response = f'*{member.name}* is **already active** - ignoring request'
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='generate_pass',
description=f'Generate a new password for user @id')
@app_commands.describe(member='@id')
async def generate_pass(interaction: discord.Interaction, member: discord.Member):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.new_pass(str(member.id), ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='arb_read',
description=f'read value of field <field> of user @id')
@app_commands.describe(member='@id',
field='Field name to show')
async def arb_read(interaction: discord.Interaction, member: discord.Member, field: str):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = f'{field} : {msgHandler.read_field(str(member.id), field, ldb)}'
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='arb_write',
description=f'write value <val> to field <field> of user @id')
@app_commands.describe(member='@id',
field='Field name to write to',
val='Value to write')
async def arb_write(interaction: discord.Interaction, member: discord.Member, field: str, val: str = ''):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.write_field(str(member.id), field, val, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='arb_write_by_sid',
description=f'write value <val> to field <field> of user with server id <sid>')
@app_commands.describe(sid='server id number',
field='Field name to write to',
val='Value to write')
async def arb_write_by_sid(interaction: discord.Interaction, sid: int, field: str, val: str = ''):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.write_field_by_sid(sid, field, val, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
# The following commands are to be opened up to all Discord users who have access to your server
@client.tree.command(name='show_password',
description=f'Display your Run8 server password in a message only you can see')
async def show_password(interaction: discord.Interaction):
user_id = str(interaction.user.id)
discord_name = await client.fetch_user(int(user_id))
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.show_pass(user_id, discord_name, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='refresh_pass',
description=f'Refresh your Run8 server password and display in a message only you can see')
async def refresh_pass(interaction: discord.Interaction):
user_id = str(interaction.user.id)
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
response = msgHandler.new_pass(user_id, ldb)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='server_info',
description=f'Show the Run 8 server address and port')
async def server_info(interaction: discord.Interaction):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
i = 0
response = ''
for server in R8SERVER_NAME:
if i > 0:
response += '----------------\n'
response += (f'Server info for : **{server}** \n'
f'* address: **{R8SERVER_ADDR[i]}**\n'
f'* port: **{R8SERVER_PORT[i]}**\n')
i += 1
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='restart_server', description=f'Kill Run8 server and restart')
@app_commands.describe(sname='Server name to restart')
async def restart_server(interaction: discord.Interaction, sname: str = ''):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if sname == '':
sname = R8SERVER_NAME[0]
# Find server parameters within server list
if sname not in R8SERVER_NAME:
response = f'Server name [{sname}] not known\n'
response += 'Use "/server_info" for a list of valid server names.'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
else:
spath = R8SERVER_PATH[R8SERVER_NAME.index(sname)]
# Attempt to find existing running server instance
response = f'No running server matching {sname} found.\n'
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
# Print process ID, Name, and Executable path
if proc.info['name'] == "Run-8 Train Simulator V3.exe":
if proc.info['exe'] == spath + '\Run-8 Train Simulator V3.exe':
process = psutil.Process(proc.info['pid'])
process.terminate()
response = f'Server Restart Initiated. \nServer {sname} (PID {proc.info["pid"]}) terminated.\n'
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
print(f'Exception in restart_server command - either server not running, or unable to terminate')
pass
# Attempt to run server
response += f'...\nServer {sname} starting up.\nNOTE: Wait at LEAST 5 minutes before enabling Auto DS (Otto)'
subprocess.run(spath + '\startServer.bat')
admin_channel = discord.utils.get(interaction.guild.channels, name=CH_ADMIN)
await admin_channel.send(response)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='kill_server', description=f'Kill Run8 server')
@app_commands.describe(sname='Server name to kill')
async def kill_server(interaction: discord.Interaction, sname: str = ''):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if sname == '':
sname = R8SERVER_NAME[0]
# Find server parameters within server list
if sname not in R8SERVER_NAME:
response = f'Server name [{sname}] not known\n'
response += 'Use "/server_info" for a list of valid server names.'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
else:
spath = R8SERVER_PATH[R8SERVER_NAME.index(sname)]
# Attempt to find existing running server instance
response = f'No running server matching {sname} found.\n'
for proc in psutil.process_iter(['pid', 'name', 'exe']):
try:
if proc.info['name'] == "Run-8 Train Simulator V3.exe":
if proc.info['exe'] == spath + '\Run-8 Train Simulator V3.exe':
process = psutil.Process(proc.info['pid'])
process.terminate()
response = f'Server Kill initiated.\nServer {sname} (PID {proc.info["pid"]}) terminated.\n'
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
print(f'Exception in kill_server command - either server not running, or unable to terminate')
pass
admin_channel = discord.utils.get(interaction.guild.channels, name=CH_ADMIN)
await admin_channel.send(response)
await interaction.response.send_message(response, ephemeral=True) # noqa
@client.tree.command(name='download_file', description=f'Download a configuration file from server')
@app_commands.describe(fname='The name of the file to send [hump, industry, traffic, world]',
sname='Server name')
async def download_file(interaction: discord.Interaction, fname: str, sname: str = ''):
print('here in the send file')
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if sname == '':
sname = R8SERVER_NAME[0]
# Find server parameters within server list
if sname not in R8SERVER_NAME:
response = f'Server name [{sname}] not known\n'
response += 'Use "/server_info" for a list of valid server names.'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
else:
if fname.lower() == 'hump':
spath = R8SERVER_HUMP_FNAME[R8SERVER_NAME.index(sname)]
elif fname.lower() == 'industry':
spath = R8SERVER_INDUSTRY_FNAME[R8SERVER_NAME.index(sname)]
elif fname.lower() == 'traffic':
spath = R8SERVER_TRAFFIC_FNAME[R8SERVER_NAME.index(sname)]
elif fname.lower() == 'world':
spath = R8SERVER_WORLD_FNAME[R8SERVER_NAME.index(sname)]
else:
response = f'Filename "{fname}" not found\n'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
if spath == '':
response = f'**Error**: {fname} file not eligible for download.\n'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
await interaction.response.send_message(file=discord.File(spath), ephemeral=True) # noqa
@client.tree.command(name='admin_file_download', description=f'Download admin files from server')
@app_commands.describe(fname='The name of the file to send [database, log, r8dium_log, security]',
sname='Server name')
async def admin_file_download(interaction: discord.Interaction, fname: str, sname: str = ''):
if CH_LOG != 'none':
log_channel = discord.utils.get(interaction.guild.channels, name=CH_LOG) # return channel id from name
await log_channel.send(log_message(interaction))
if sname == '':
sname = R8SERVER_NAME[0]
# Find server parameters within server list
if sname not in R8SERVER_NAME:
response = f'Server name [{sname}] not known\n'
response += 'Use "/server_info" for a list of valid server names.'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
else:
if fname.lower() == 'security':
spath = R8SERVER_SECURITY_FNAME[R8SERVER_NAME.index(sname)]
elif fname.lower() == 'log':
spath = R8SERVER_LOG[R8SERVER_NAME.index(sname)]
elif fname.lower() == 'r8dium_log':
spath = LOG_FILE + '.log'
elif fname.lower() == 'database':
spath = USER_DB + '.csv'
else:
response = f'Filename "{fname}" not found\n'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
if spath == '':
response = f'**Error**: {fname} file not eligible for download.\n'
await interaction.response.send_message(response, ephemeral=True) # noqa
return
await interaction.response.send_message(file=discord.File(spath), ephemeral=True) # noqa
client.run(TOKEN)