-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscord_bot.py
More file actions
151 lines (122 loc) · 4.61 KB
/
Copy pathdiscord_bot.py
File metadata and controls
151 lines (122 loc) · 4.61 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
import discord
from discord.ext import commands
import logging
from dotenv import load_dotenv
import os
import sys
import asyncio
from functools import wraps
import server_manager as sm # import your server functions
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
enable_shutdown_command = os.getenv('ENABLE_SHUTDOWN_COMMAND', 'False').lower() in ('true', '1', 'yes')
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
server_manager = sm.MinecraftServerManager()
async def update_status():
if server_manager.is_running:
await bot.change_presence(
status=discord.Status.online,
activity=discord.Game("Server running")
)
else:
await bot.change_presence(
status=discord.Status.idle,
activity=discord.Game("Server offline")
)
async def status_watcher():
await bot.wait_until_ready()
while not bot.is_closed():
await update_status()
await asyncio.sleep(300) # check every 5 minutes
def require_valid_environment(func):
@wraps(func)
async def wrapper(ctx, *args, **kwargs):
manager_role = discord.utils.get(ctx.guild.roles, name="Server-Manager")
bot_channel = discord.utils.get(ctx.guild.channels, name="bot-commands")
# If bot-commands channel exists, enforce it
if bot_channel is not None and ctx.channel.id != bot_channel.id:
await ctx.message.delete()
await ctx.send(f"⚠️ You can only use this command in {bot_channel.mention}.", delete_after=10)
return
if manager_role is not None and manager_role not in ctx.author.roles and not ctx.author.guild_permissions:
await ctx.send("⚠️ You do not have permission to use this command.", delete_after=10)
return
await func(ctx, *args, **kwargs)
return wrapper
@bot.event
async def on_ready():
bot.loop.create_task(status_watcher())
@bot.command()
@require_valid_environment
async def start(ctx):
if server_manager.is_running:
await ctx.send("⚠️ Server is already running!")
return
await ctx.send("🚀 Starting the Minecraft server...")
await server_manager.start()
await ctx.send("✅ Server started!")
await update_status()
@bot.command()
@require_valid_environment
async def stop(ctx):
if not server_manager.is_running:
await ctx.send("⚠️ Server is not running.")
return
if server_manager.online_players:
await ctx.send("⚠️ Players are still online!")
return
await ctx.send("🛑 Stopping the server...")
await server_manager.shutdown()
await ctx.send("✅ Server stopped!")
await update_status()
@bot.command()
@require_valid_environment
async def online(ctx):
if not server_manager.is_running:
await ctx.send("⚠️ Server is offline.")
return
online_players = server_manager.online_players
if online_players:
await ctx.send(f"✅ Online players: {', '.join(online_players)}")
else:
await ctx.send("❌ No players are currently online.")
@bot.command()
@require_valid_environment
async def shutdown(ctx):
if not enable_shutdown_command:
await ctx.send("⚠️ Shutdown command is disabled.")
return
if server_manager.is_running:
await stop(ctx)
while server_manager.is_running: # wait until server fully stops
await asyncio.sleep(1)
await ctx.send("🛑 Shutting down the server...")
os.system("shutdown /s")
await ctx.send("✅ Server is shutting down.")
@bot.command()
@require_valid_environment
async def cancel(ctx):
if not enable_shutdown_command:
await ctx.send("⚠️ Shutdown command is disabled.")
return
await ctx.send("🛑 Cancelling shutdown...")
os.system("shutdown /a")
if token is None:
print("Error: DISCORD_TOKEN environment variable not set.")
sys.exit(1)
@bot.command()
@require_valid_environment
async def cmd(ctx):
op_role = discord.utils.get(ctx.guild.roles, name="OP")
if op_role is not None and op_role not in ctx.author.roles and not ctx.author.guild_permissions:
await ctx.send("⚠️ You do not have permission to use this command.", delete_after=10)
return
await server_manager.send_command(ctx.message.content[len("!cmd "):])
if token is None:
print("Error: DISCORD_TOKEN environment variable not set.")
sys.exit(1)
handler = logging.FileHandler(filename=sm.setup_logging("discord_bot"), encoding='utf-8', mode='w')
bot.run(token, log_handler=handler, log_level=logging.DEBUG)