-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
457 lines (379 loc) · 16 KB
/
Copy pathbot.py
File metadata and controls
457 lines (379 loc) · 16 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
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
"""
bot.py
Version: 1.3.0
This module contains the main logic for the Minecraft Discord bot. It sets
up the bot, defines command handlers for various bot functionalities,
and manages interactions with the Minecraft server. The bot supports commands
such as starting/stopping the server, managing snapshots, and verifying users.
Usage:
- Run this module to start the bot and listen for commands in Discord.
- The bot uses the command prefix `$` to interact with users.
Key Commands:
- `start`: Starts the Minecraft server.
- `stop`: Stops the Minecraft server.
- `snapshots`: Manage world snapshots (list, create, delete, restore, download).
- `verify`: Links a Discord account to a Minecraft account.
- `ping`: Measures the bot's latency.
Database:
- The bot uses an SQLite database to manage user verification and snapshot
information.
Configuration:
- The bot's configuration is loaded from a `config.cfg` file, which should
contain the necessary settings (e.g., bot token, RCON credentials).
Notes:
- Ensure that the Minecraft server is running before executing commands
that interact with it.
- The bot requires specific roles and permissions to execute certain commands.
"""
# Standard Library Imports
import asyncio
import logging
import configparser
import sqlite3
import subprocess
# Third-party imports
import aiohttp
import discord
import mcrcon
from discord.ext import commands
# First-party imports
import bot_modules
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s] [%(levelname)-8s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
BOT_VERSION = "1.3.0"
conn = sqlite3.connect('minecraft_manager.db')
c = conn.cursor()
config = configparser.ConfigParser()
config.read('config.cfg')
TOKEN = config.get('PythonConfig', 'TOKEN')
REQUIRED_ROLE = config.get('PythonConfig', 'required_role')
BOT_OWNER_ID = int(config.get('PythonConfig', 'bot_owner_id'))
PORT = config.get("PythonConfig", "port")
RCON_HOST = config.get('PythonConfig', 'rcon_host')
RCON_PORT = int(config.get('PythonConfig', 'rcon_port'))
RCON_PASSWORD = config.get('PythonConfig', 'rcon_password')
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
bot.server_running = False
@bot.command(name='start')
async def start(ctx):
discord_id = ctx.author.id
if ctx.author.id == BOT_OWNER_ID:
pass
elif bot_modules.has_required_role(ctx):
pass
else:
is_op, error_message = bot_modules.has_operator(discord_id)
if not is_op:
embed = discord.Embed(
title=':x: Missing Permissions',
description=f'{error_message}',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
bot.server_running = await bot_modules.start_server(ctx, bot)
@bot.command(name='stop')
async def stop_command(ctx):
discord_id = ctx.author.id
if ctx.author.id == BOT_OWNER_ID:
pass
else:
# Check if the user is a Minecraft operator
is_op, error_message = bot_modules.has_operator(discord_id)
if not is_op:
embed = discord.Embed(
title=':x: Missing Permissions',
description=f'{error_message}',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
if not bot.server_running:
embed = discord.Embed(
title=':x: Server Offline!',
description='The Minecraft server is not running.',
color=discord.Color.red())
await ctx.send(embed=embed)
return
try:
with mcrcon.MCRcon(RCON_HOST, RCON_PASSWORD, port=RCON_PORT) as rcon:
rcon.command('stop')
embed = discord.Embed(
title=":hourglass: Server Stopping...",
description='Sent the `stop` command to the Minecraft server.',
color=discord.Color.blue())
stop = await ctx.send(embed=embed)
except mcrcon.MCRconException:
embed = discord.Embed(
title=':x: Server Error!',
description='Failed to send the `stop` command to the Minecraft server.',
color=discord.Color.red())
await ctx.send(embed=embed)
return
# Checking if server actually went offline
for attempt in range(5):
logging.debug("Checking server state... Attempt %d/5", attempt + 1)
bot.server_running = bot_modules.check_server_running(host='localhost', port=PORT)
if not bot.server_running:
logging.info("Server stopped successfully")
embed = discord.Embed(
title=":stop_button: Server Stopped",
description='Server stopped successfully',
color=discord.Color.green())
await stop.edit(embed=embed)
try:
# Terminate Ngrok process
result = subprocess.call('taskkill /im ngrok.exe /f', shell=True)
if result == 0:
logging.info("Ngrok terminated successfully.")
else:
logging.error("Failed to terminate Ngrok process. Error code: %d", result)
except Exception as e:
logging.error("Error terminating Ngrok process: %s", e)
break
await asyncio.sleep(2)
if bot.server_running:
logging.error("Failed to stop the Minecraft server")
embed = discord.Embed(
title=':x: Server Error!',
description='Server failed to stop',
color=discord.Color.red())
await stop.edit(embed=embed)
@bot.command(name='shutdown')
async def shutdown_bot(ctx):
if ctx.author.id == BOT_OWNER_ID:
embed = discord.Embed(
title=':stop_button: Bot Shutting Down',
description='Shutting down the bot...',
color=discord.Color.blue())
await ctx.send(embed=embed)
await bot.close()
else:
embed = discord.Embed(
title=":x: Missing Permissions",
description="Only the Minecraft Server Owner can issue this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
@bot.command(name='update')
async def update_bot(ctx):
if ctx.author.id == BOT_OWNER_ID:
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.github.com/repos/yuri010/minecraft-manager/releases/latest") as response:
data = await response.json()
latest_version = data.get("tag_name", "Unknown")
if latest_version < BOT_VERSION:
embed = discord.Embed(
title=':x: You are in the future!',
description=f'Current version ({BOT_VERSION})\
is newer than the latest public build ({latest_version})!\n\
Update aborted.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
if latest_version > BOT_VERSION:
embed = discord.Embed(
title=':arrows_counterclockwise: Update Available!',
description=f'A new version ({latest_version} over {BOT_VERSION}) is available!\n\
Automatic update is unavailable in this version though.\n\
Please update manually from the repository available\
[here](https://github.com/yuri010/minecraft-manager)',
color=discord.Color.yellow()
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title=':white_check_mark: Up-to-date!',
description=f'The bot is already up to date (Version {BOT_VERSION}).',
color=discord.Color.green()
)
await ctx.send(embed=embed)
else:
embed = discord.Embed(
title="❌ Missing Permissions",
description="Only the Minecraft Server Owner can issue this command.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
@bot.command(name='console')
async def console_command(ctx, *, command):
discord_id = ctx.author.id
# Permissions check
if ctx.author.id != BOT_OWNER_ID:
# Check if the user is a Minecraft operator
is_op, error_message = bot_modules.has_operator(discord_id)
if not is_op:
embed = discord.Embed(
title=':x: Missing Permissions',
description=f'{error_message}',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
# Check if the server is running
if not bot.server_running:
embed = discord.Embed(
title=':x: Server Offline!',
description='The Minecraft server is not running.',
color=discord.Color.red())
await ctx.send(embed=embed)
return
try:
# Set up an RCON connection with a timeout
with mcrcon.MCRcon(RCON_HOST, RCON_PASSWORD, port=RCON_PORT, timeout=5) as rcon:
response = rcon.command(command)
embed = discord.Embed(
title='Minecraft Console',
description=f'Command: {command}',
color=discord.Color.green())
embed.add_field(name='Output', value=response)
await ctx.send(embed=embed)
except mcrcon.MCRconException as e:
# Handle RCON-specific errors
embed = discord.Embed(
title='Minecraft Console',
description=f'Command: {command}',
color=discord.Color.red())
embed.add_field(name='Error', value=str(e))
await ctx.send(embed=embed)
except TimeoutError:
# Handle timeout errors
embed = discord.Embed(
title='❌ Timed Out',
description=':x: Failed to connect to the server within the timeout period.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
@console_command.error
async def console_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="❌ Missing Argument",
description="Please provide a command to execute.",
color=discord.Color.red()
)
await ctx.send(embed=embed)
@bot.command(name='status')
async def status_command(ctx):
# Initial message while checking server status
loading_embed = discord.Embed(
title=':hourglass: Checking Status',
description='Checking server status, please wait...',
color=discord.Color.blue()
)
status_message = await ctx.send(embed=loading_embed)
embed_color = discord.Color.red()
public_ip = await bot_modules.get_public_ip() if bot.server_running else None
host, port = None, None
if bot.server_running:
embed_color = discord.Color.green()
try:
# Parse public_ip and set host/port
if isinstance(public_ip, str):
public_ip = public_ip.replace('tcp://', '')
if ':' in public_ip:
host, port = public_ip.split(':')[:2]
else:
host, port = public_ip, '25565' # Default port
# Only proceed if host and port are valid
if host and port and not bot_modules.check_server_running(host, int(port)):
embed_color = discord.Color.red()
except Exception as e:
logging.error("Error while checking server status: %d", e)
# Construct final embed
embed = discord.Embed(title='Server Status', color=embed_color)
embed.add_field(name='Status', value='Running' if bot.server_running else 'Stopped', inline=False)
# Update IP field based on validity
embed.add_field(name='IP', value=public_ip if public_ip else 'N/A', inline=False)
# Check ping if server is running and IP/port are available
if bot.server_running and host and port:
try:
latency = bot_modules.check_server_latency(host, int(port))
if latency is not None:
embed.add_field(name='Ping', value=f'Latency: {latency} ms', inline=False)
else:
embed.add_field(name='Ping', value='Failed to ping server: Port is closed', inline=False)
except Exception as e:
embed.add_field(name='Ping', value=f'Failed to ping server: {str(e)}', inline=False)
# Edit original message with the final status
await status_message.edit(embed=embed)
@bot.command(name='snapshots')
async def snapshots_command(ctx, action=None, *args):
discord_id = ctx.author.id
if action == 'list' or action is None: # When 'list' or no arguments are given, simply list the snapshots
await bot_modules.list_snapshots(ctx)
return
if action == 'create':
# Check if the user is the bot owner first
if discord_id != BOT_OWNER_ID:
# If not the owner, check if they are an operator
is_op, error_message = bot_modules.has_operator(discord_id)
if not is_op:
embed = discord.Embed(
title=':x: Missing Permissions',
description=f'{error_message}',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
await bot_modules.create_snapshot(ctx, bot, *args)
return
# Check if user is owner before executing descructive commands
if action in ['delete', 'restore'] and discord_id != BOT_OWNER_ID:
embed = discord.Embed(
title=':x: Missing Permissions',
description='You do not have permission to use this command.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
# Ensure snapshot name is provided for 'delete', 'restore', and 'download'
if action in ['delete', 'restore', 'download']:
if not args: # If no snapshot name is provided
embed = discord.Embed(
title=':x: Missing Arguments',
description=f'You must provide a snapshot name for the `{action}` command.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
return
# Process the commands if snapshot name is provided
if action == 'delete':
await bot_modules.delete_snapshot(ctx, bot, ' '.join(args))
elif action == 'restore':
await bot_modules.restore_snapshot(ctx, bot, ' '.join(args))
elif action == 'download':
await bot_modules.download_snapshot(ctx, ' '.join(args))
else:
embed = discord.Embed(
title=':x: Unknown Argument',
description=f'Unknown action `{action}`.',
color=discord.Color.red()
)
await ctx.send(embed=embed)
@bot.command(name='info')
async def info_command(ctx, action=None):
if action == 'snapshots':
await bot_modules.info_snapshots(ctx, bot)
else:
await bot_modules.info(ctx, bot)
@bot.command(name='verify')
async def verify_command(ctx):
await bot_modules.verify(ctx, bot)
@bot.command(name='ping')
async def ping_command(ctx):
await bot_modules.ping(ctx)
@bot.event
async def on_ready():
logging.info("Bot is ready. Logged in as %s", bot.user.name)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,
name="over a Minecraft Server"))
if __name__ == "__main__":
bot.run(TOKEN)