-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.py
More file actions
293 lines (258 loc) · 10.8 KB
/
Main.py
File metadata and controls
293 lines (258 loc) · 10.8 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
"""
Start HazeBot (Bot Only)
Runs only the Discord bot without the API server
"""
import logging
# Setup logging first
logging.basicConfig(
level=logging.INFO,
format="[{asctime}] 🛈 INFO │ {message}",
datefmt="%H:%M:%S",
style="{",
)
logging.getLogger("discord").handlers.clear()
logging.getLogger("discord").propagate = False
logging.getLogger("discord").setLevel(logging.ERROR) # Suppress discord.py warnings
# Set root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.WARNING)
root_logger.handlers.clear()
# Now imports
import asyncio
import difflib
import pathlib
import discord
from discord.ext import commands
from dotenv import load_dotenv
import Config
from Config import (
BOT_TOKEN,
DATA_DIR,
GUILD_ID,
PROD_MODE,
SLASH_COMMANDS,
BotName,
CommandPrefix,
FuzzyMatchingThreshold,
Intents,
MessageCooldown,
get_guild_id,
)
from Utils.ConfigLoader import load_config_from_file
from Utils.EmbedUtils import set_pink_footer
from Utils.Env import LoadEnv
from Utils.Logger import Logger
# Load environment
load_dotenv()
Token = BOT_TOKEN
EnvDict = LoadEnv()
# Load saved configuration overrides before starting the bot
print("🔄 Loading configuration from file...")
load_config_from_file()
print(f"🔍 After load: RL_RANK_CHECK_INTERVAL_HOURS = {Config.RL_RANK_CHECK_INTERVAL_HOURS}")
loaded_count = sum(1 for v in EnvDict.values() if v is not None)
Logger.info(f"🌍 Environment variables loaded: {loaded_count}/{len(list(EnvDict.keys()))}")
class HazeWorldBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=CommandPrefix, intents=Intents)
self.remove_command("help")
self.UserCooldowns = {} # For message cooldowns
async def setup_hook(self) -> None:
Logger.info("🚀 Starting Cog loading sequence...")
loaded_cogs = []
# Skip AnalyticsManager and APIServer when running without API
# (Both require API modules and are only useful when API is running)
Logger.info(" └─ ⏭️ Skipped: AnalyticsManager (requires API - use start_with_api.py)")
Logger.info(" └─ ⏭️ Skipped: APIServer (requires API - use start_with_api.py)")
# Load CogManager second (to manage cogs)
try:
await self.load_extension("Cogs.CogManager")
loaded_cogs.append("CogManager")
Logger.info(" └─ ✅ Loaded: CogManager")
except Exception as e:
Logger.error(f" └─ ❌ Failed to load CogManager: {e}")
return
# Load DiscordLogging third
try:
await self.load_extension("Cogs.DiscordLogging")
loaded_cogs.append("DiscordLogging")
Logger.info(" └─ ✅ Loaded: DiscordLogging")
except Exception as e:
Logger.error(f" └─ ❌ Failed to load DiscordLogging: {e}")
# Get disabled cogs
cog_manager = self.get_cog("CogManager")
disabled_cogs = cog_manager.get_disabled_cogs() if cog_manager else []
# Load other cogs
for cog in pathlib.Path("Cogs").glob("*.py"):
if cog.name.startswith("_") or cog.stem in [
"AnalyticsManager",
"APIServer",
"CogManager",
"DiscordLogging",
]:
continue
if cog.stem in disabled_cogs:
Logger.info(f" └─ ⏸️ Skipped (disabled): {cog.stem}")
continue
try:
await self.load_extension(f"Cogs.{cog.stem}")
loaded_cogs.append(cog.stem)
Logger.info(f" └─ ✅ Loaded: {cog.stem}")
except Exception as e:
Logger.error(f" └─ ❌ Failed to load {cog.stem}: {e}")
if loaded_cogs:
Logger.info(f"🧩 All Cogs loaded: {', '.join(loaded_cogs)}")
else:
Logger.warning("⚠️ No Cogs loaded!")
Logger.info("🎯 Cog loading sequence complete.")
# List commands
slash_commands = SLASH_COMMANDS
Logger.info("📋 Available ! commands:")
for cog_name, cog in self.cogs.items():
for cmd in cog.get_commands():
if not cmd.hidden:
slash_available = cmd.name in slash_commands
Logger.info(f" └─ ! {cmd.name} (Cog: {cog_name}) {'(/ available)' if slash_available else ''}")
# Sync commands
self.tree.clear_commands(guild=None)
guild = discord.Object(id=get_guild_id())
self.tree.copy_global_to(guild=guild)
synced = await self.tree.sync(guild=guild)
Logger.info(f"Synced commands: {[cmd.name for cmd in synced]}")
Logger.info(f"🔗 Synced {len(synced)} guild slash commands.")
Logger.info(f"🤖 HazeWorldBot starting in {'PRODUCTION' if PROD_MODE else 'TEST'} mode")
Logger.info(f"📊 Using Guild ID: {GUILD_ID}")
Logger.info(f"📁 Using Data Directory: {DATA_DIR}")
async def on_ready(self) -> None:
Logger.info(f"{BotName} is online as {self.user}!")
async def on_command_completion(self, ctx: commands.Context) -> None:
try:
await ctx.message.delete()
except Exception:
pass
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError) -> None:
"""Handle command errors with detailed responses."""
if isinstance(error, commands.CommandNotFound):
# Fuzzy matching for unknown commands
cmd_name = ctx.message.content.split()[0][len(CommandPrefix) :]
all_cmds = [cmd.name for cog in self.cogs.values() for cmd in cog.get_commands() if not cmd.hidden]
matches = difflib.get_close_matches(cmd_name, all_cmds, n=1, cutoff=FuzzyMatchingThreshold)
if matches:
embed = discord.Embed(
title="❓ Command not found",
description=f"Did you mean `!{matches[0]}`?",
color=discord.Color.orange(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(10)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
else:
embed = discord.Embed(
title="❓ Command not found",
description="Use `!help` for a list of commands.",
color=discord.Color.red(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(10)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="🚫 Missing Permissions",
description="You don't have the required permissions to use this command.",
color=discord.Color.red(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(5)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
elif isinstance(error, commands.BadArgument):
embed = discord.Embed(
title="⚠️ Bad Argument",
description="Invalid argument provided. Check the command usage.",
color=discord.Color.yellow(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(5)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
elif isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title="⏳ Command on Cooldown",
description=f"This command is on cooldown. Try again in {error.retry_after:.1f} seconds.",
color=discord.Color.blue(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(5)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
else:
Logger.error(f"Unhandled command error: {error}")
embed = discord.Embed(
title="💥 An error occurred",
description="Something went wrong. Please try again later.",
color=discord.Color.red(),
)
set_pink_footer(embed, bot=self.user)
embed_message = await ctx.send(embed=embed)
await asyncio.sleep(5)
try:
await embed_message.delete()
await ctx.message.delete()
except Exception:
pass
async def on_message(self, message: discord.Message) -> None:
"""Handle messages with cooldowns."""
if message.author.bot:
return
now = message.created_at.timestamp()
is_admin_command = message.content.startswith("!") and any(
cmd in message.content.lower() for cmd in ["load", "unload", "reload", "listcogs"]
)
if not is_admin_command:
if message.author.id in self.UserCooldowns:
if now - self.UserCooldowns[message.author.id] < MessageCooldown:
return
self.UserCooldowns[message.author.id] = now
await self.process_commands(message)
async def on_message_edit(self, before: discord.Message, after: discord.Message) -> None:
"""Log message edits."""
if before.author.bot or before.content == after.content:
return
Logger.info(f"✏️ Message edited by {before.author} in {before.channel}: '{before.content}' -> '{after.content}'")
async def on_message_delete(self, message: discord.Message) -> None:
"""Log message deletions."""
if message.author.bot:
return
Logger.info(f"🗑️ Message deleted by {message.author} in {message.channel}: '{message.content}'")
def main():
"""Main entry point"""
bot = HazeWorldBot()
Logger.info("🤖 Starting Discord bot (Bot only mode - no API server)...")
try:
bot.run(Token)
except KeyboardInterrupt:
Logger.info("🛑 Keyboard interrupt received, shutting down...")
if __name__ == "__main__":
main()