Skip to content

Commit 4c45cbc

Browse files
committed
Refactor database access: Replace async_db with AsyncDatabase instance across multiple cogs and scripts for improved consistency and maintainability.
1 parent 4dc0b0e commit 4c45cbc

38 files changed

Lines changed: 605 additions & 572 deletions

botEvents/onReady.py

Lines changed: 134 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -1,134 +1,135 @@
1-
from bronxbot import *
2-
from cogInfo import CogLoader
3-
4-
@bot.event
5-
async def on_ready():
6-
"""Called when the bot is ready"""
7-
logging.info(f"Bot ready as {bot.user.name} ({bot.user.id})")
8-
9-
# Load all cogs using CogLoader
10-
try:
11-
logging.info("Loading cogs...")
12-
success_count, error_count = await CogLoader.load_all_cogs(bot)
13-
logging.info(f"Loaded {success_count} cogs with {error_count} errors")
14-
except Exception as e:
15-
logging.error(f"Error during cog loading: {e}")
16-
traceback.print_exc()
17-
18-
# Start the stats update loop after cogs are loaded
19-
if not hasattr(bot, 'update_stats'):
20-
logging.error("update_stats task not found")
21-
return
22-
if not bot.update_stats.is_running():
23-
bot.update_stats.start()
24-
logging.info("Started stats update loop")
25-
26-
# Start command usage tracker auto-save
27-
try:
28-
usage_tracker.start_auto_save()
29-
logging.info("Started command usage tracker auto-save")
30-
except Exception as e:
31-
logging.error(f"Failed to start command usage tracker: {e}")
32-
33-
# Initialize scalability manager
34-
try:
35-
bot.scalability_manager = await initialize_scalability(bot)
36-
logging.info("Scalability manager initialized successfully")
37-
except Exception as e:
38-
logging.warning(f"Scalability manager initialization failed: {e}")
39-
bot.scalability_manager = None
40-
41-
# Load additional cogs manually
42-
try:
43-
# Load TOS handler
44-
await bot.load_extension('utils.tos_handler')
45-
logging.info("TOS handler loaded successfully")
46-
47-
# Load Setup wizard
48-
await bot.load_extension('cogs.setup.SetupWizard')
49-
logging.info("Setup wizard loaded successfully")
50-
except Exception as e:
51-
logging.error(f"Failed to load additional cogs: {e}")
52-
53-
# Initialize database and clean up corrupted inventory data
54-
try:
55-
from utils.db import async_db
56-
await async_db.ensure_connected()
57-
logging.info("Database connection established")
58-
59-
# Run inventory cleanup on startup to remove corrupted data
60-
cleaned_count = await async_db.cleanup_corrupted_inventory()
61-
if cleaned_count > 0:
62-
logging.info(f"Cleaned up {cleaned_count} corrupted inventory items on startup")
63-
else:
64-
logging.info("No corrupted inventory items found during startup cleanup")
65-
except ImportError:
66-
logging.warning("Database module not available, skipping database initialization")
67-
except Exception as e:
68-
logging.error(f"Failed to initialize database or cleanup inventory: {e}")
69-
70-
guild_cache_start = time.time()
71-
# Build guild cache
72-
for guild in bot.guilds:
73-
await guild.chunk()
74-
bot.boot_metrics['guild_cache_time'] = time.time() - guild_cache_start
75-
76-
# Update presence
77-
await bot.change_presence(
78-
activity=discord.Activity(
79-
type=discord.ActivityType.playing,
80-
name=f"with {len(bot.guilds)} servers | .help"
81-
)
82-
)
83-
84-
if bot.restart_channel and bot.restart_message:
85-
try:
86-
channel = await bot.fetch_channel(bot.restart_channel)
87-
message = await channel.fetch_message(bot.restart_message)
88-
89-
bot.boot_metrics['total_boot_time'] = time.time() - bot.boot_metrics['start_time']
90-
bot.boot_metrics['ready_time'] = time.time() - bot.start_time
91-
bot.boot_metrics['total_cog_load_time'] = sum(bot.cog_load_times.values())
92-
93-
boot_info = (
94-
f"✅ Boot completed in `{bot.boot_metrics['total_boot_time']:.2f}s`\n\n"
95-
f"**Boot Metrics:**\n"
96-
f"• Config Load: `{bot.boot_metrics['config_load_time']:.2f}s`\n"
97-
f"• Guild Cache: `{bot.boot_metrics['guild_cache_time']:.2f}s`\n"
98-
f"• Total Cog Load: `{bot.boot_metrics['total_cog_load_time']:.2f}s`\n"
99-
f"• Ready Time: `{bot.boot_metrics['ready_time']:.2f}s`\n\n"
100-
f"**Individual Cog Load Times:**\n" +
101-
"\n".join([f"• `{cog.split('.')[-1]}: {time:.2f}s`"
102-
for cog, time in sorted(bot.cog_load_times.items())])
103-
)
104-
105-
embed = discord.Embed(
106-
description=boot_info,
107-
color=discord.Color.green()
108-
)
109-
await message.edit(embed=embed)
110-
except Exception as e:
111-
print(f"Failed to update restart message: {e}")
112-
113-
"""success, errors = await CogLoader.load_all_cogs(bot)
114-
status_msg = (
115-
f"[?] Logged in as {bot.user.name} (ID: {bot.user.id})\n"
116-
f"[!] Shards: {bot.shard_count}, Latency: {round(bot.latency * 1000, 2)}ms\n"
117-
f"[+] Cogs: {success} loaded, {errors} errors"
118-
)
119-
print(status_msg)"""
120-
121-
activity = discord.Activity(
122-
type=discord.ActivityType.playing,
123-
name=f"with {len(bot.guilds)} servers | .help"
124-
)
125-
await bot.change_presence(activity=activity)
126-
127-
# Start additional stats tracker
128-
if not additional_stats_update.is_running():
129-
additional_stats_update.start()
130-
logging.info("Started additional stats update loop")
131-
132-
if not reset_daily_stats.is_running():
133-
reset_daily_stats.start()
1+
from bronxbot import *
2+
from cogInfo import CogLoader
3+
4+
@bot.event
5+
async def on_ready():
6+
"""Called when the bot is ready"""
7+
logging.info(f"Bot ready as {bot.user.name} ({bot.user.id})")
8+
9+
# Load all cogs using CogLoader
10+
try:
11+
logging.info("Loading cogs...")
12+
success_count, error_count = await CogLoader.load_all_cogs(bot)
13+
logging.info(f"Loaded {success_count} cogs with {error_count} errors")
14+
except Exception as e:
15+
logging.error(f"Error during cog loading: {e}")
16+
traceback.print_exc()
17+
18+
# Start the stats update loop after cogs are loaded
19+
if not hasattr(bot, 'update_stats'):
20+
logging.error("update_stats task not found")
21+
return
22+
if not bot.update_stats.is_running():
23+
bot.update_stats.start()
24+
logging.info("Started stats update loop")
25+
26+
# Start command usage tracker auto-save
27+
try:
28+
usage_tracker.start_auto_save()
29+
logging.info("Started command usage tracker auto-save")
30+
except Exception as e:
31+
logging.error(f"Failed to start command usage tracker: {e}")
32+
33+
# Initialize scalability manager
34+
try:
35+
bot.scalability_manager = await initialize_scalability(bot)
36+
logging.info("Scalability manager initialized successfully")
37+
except Exception as e:
38+
logging.warning(f"Scalability manager initialization failed: {e}")
39+
bot.scalability_manager = None
40+
41+
# Load additional cogs manually
42+
try:
43+
# Load TOS handler
44+
await bot.load_extension('utils.tos_handler')
45+
logging.info("TOS handler loaded successfully")
46+
47+
# Load Setup wizard
48+
await bot.load_extension('cogs.setup.SetupWizard')
49+
logging.info("Setup wizard loaded successfully")
50+
except Exception as e:
51+
logging.error(f"Failed to load additional cogs: {e}")
52+
53+
# Initialize database and clean up corrupted inventory data
54+
try:
55+
from utils.db import AsyncDatabase
56+
db = AsyncDatabase.get_instance()
57+
await db.ensure_connected()
58+
logging.info("Database connection established")
59+
60+
# Run inventory cleanup on startup to remove corrupted data
61+
cleaned_count = await db.cleanup_corrupted_inventory()
62+
if cleaned_count > 0:
63+
logging.info(f"Cleaned up {cleaned_count} corrupted inventory items on startup")
64+
else:
65+
logging.info("No corrupted inventory items found during startup cleanup")
66+
except ImportError:
67+
logging.warning("Database module not available, skipping database initialization")
68+
except Exception as e:
69+
logging.error(f"Failed to initialize database or cleanup inventory: {e}")
70+
71+
guild_cache_start = time.time()
72+
# Build guild cache
73+
for guild in bot.guilds:
74+
await guild.chunk()
75+
bot.boot_metrics['guild_cache_time'] = time.time() - guild_cache_start
76+
77+
# Update presence
78+
await bot.change_presence(
79+
activity=discord.Activity(
80+
type=discord.ActivityType.playing,
81+
name=f"with {len(bot.guilds)} servers | .help"
82+
)
83+
)
84+
85+
if bot.restart_channel and bot.restart_message:
86+
try:
87+
channel = await bot.fetch_channel(bot.restart_channel)
88+
message = await channel.fetch_message(bot.restart_message)
89+
90+
bot.boot_metrics['total_boot_time'] = time.time() - bot.boot_metrics['start_time']
91+
bot.boot_metrics['ready_time'] = time.time() - bot.start_time
92+
bot.boot_metrics['total_cog_load_time'] = sum(bot.cog_load_times.values())
93+
94+
boot_info = (
95+
f"✅ Boot completed in `{bot.boot_metrics['total_boot_time']:.2f}s`\n\n"
96+
f"**Boot Metrics:**\n"
97+
f"• Config Load: `{bot.boot_metrics['config_load_time']:.2f}s`\n"
98+
f"• Guild Cache: `{bot.boot_metrics['guild_cache_time']:.2f}s`\n"
99+
f"• Total Cog Load: `{bot.boot_metrics['total_cog_load_time']:.2f}s`\n"
100+
f"• Ready Time: `{bot.boot_metrics['ready_time']:.2f}s`\n\n"
101+
f"**Individual Cog Load Times:**\n" +
102+
"\n".join([f"• `{cog.split('.')[-1]}: {time:.2f}s`"
103+
for cog, time in sorted(bot.cog_load_times.items())])
104+
)
105+
106+
embed = discord.Embed(
107+
description=boot_info,
108+
color=discord.Color.green()
109+
)
110+
await message.edit(embed=embed)
111+
except Exception as e:
112+
print(f"Failed to update restart message: {e}")
113+
114+
"""success, errors = await CogLoader.load_all_cogs(bot)
115+
status_msg = (
116+
f"[?] Logged in as {bot.user.name} (ID: {bot.user.id})\n"
117+
f"[!] Shards: {bot.shard_count}, Latency: {round(bot.latency * 1000, 2)}ms\n"
118+
f"[+] Cogs: {success} loaded, {errors} errors"
119+
)
120+
print(status_msg)"""
121+
122+
activity = discord.Activity(
123+
type=discord.ActivityType.playing,
124+
name=f"with {len(bot.guilds)} servers | .help"
125+
)
126+
await bot.change_presence(activity=activity)
127+
128+
# Start additional stats tracker
129+
if not additional_stats_update.is_running():
130+
additional_stats_update.start()
131+
logging.info("Started additional stats update loop")
132+
133+
if not reset_daily_stats.is_running():
134+
reset_daily_stats.start()
134135
logging.info("Started daily stats reset loop")

bronxbot.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,10 @@ async def close(self):
131131

132132
# Close database connections (only if db module exists)
133133
try:
134-
from utils.db import async_db
135-
if hasattr(async_db, '_client') and async_db._client:
136-
async_db._client.close()
134+
from utils.db import AsyncDatabase
135+
db = AsyncDatabase.get_instance()
136+
if hasattr(db, '_client') and db._client:
137+
db._client.close()
137138
logging.info("Closed database connections")
138139
except ImportError:
139140
logging.debug("Database module not available, skipping cleanup")

cogs/Moderation.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@
77
import datetime
88
import asyncio
99
from cogs.logging.logger import CogLogger
10-
from utils.db import db
10+
from utils.db import AsyncDatabase
1111
from utils.error_handler import ErrorHandler
1212

13+
# Initialize database instance
14+
db = AsyncDatabase.get_instance()
15+
1316
# this is super wip
1417
class Moderation(commands.Cog, ErrorHandler):
1518
def __init__(self, bot):

cogs/Reminders.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
import re
55
from typing import Optional, List, Dict, Any
66
import asyncio
7-
from utils.db import async_db as db
7+
from utils.db import AsyncDatabase
8+
db = AsyncDatabase.get_instance()
89
from utils.error_handler import ErrorHandler
910
from cogs.logging.logger import CogLogger
1011

cogs/ServerSettings.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import discord
22
from discord.ext import commands
3-
from utils.db import db
3+
from utils.db import AsyncDatabase
44
from cogs.logging.logger import CogLogger
55
from utils.error_handler import ErrorHandler
66

7+
# Initialize database instance
8+
db = AsyncDatabase.get_instance()
9+
710
logger = CogLogger('ServerSettings')
811

912
# DEPRECATED: This file has been replaced by the modular settings system

cogs/admin/Admin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import discord
22
from discord.ext import commands
33
from cogs.logging.logger import CogLogger
4-
from utils.db import async_db as db
4+
from utils.db import AsyncDatabase
5+
db = AsyncDatabase.get_instance()
56
import discord
67
import json
78
import datetime

cogs/admin/Performance.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
import datetime
66
import psutil
77
import asyncio
8-
from utils.db import async_db
8+
from utils.db import AsyncDatabase
9+
db = AsyncDatabase.get_instance()
910
from utils.command_tracker import usage_tracker
1011
from cogs.logging.logger import CogLogger
1112

@@ -63,7 +64,7 @@ async def health_check(self, ctx):
6364

6465
# Database health
6566
try:
66-
db_health = await async_db.health_check()
67+
db_health = await db.health_check()
6768

6869
status_emoji = "✅" if db_health["connection"] else "❌"
6970
status_color = discord.Color.green() if db_health["connection"] else discord.Color.red()
@@ -167,7 +168,7 @@ async def optimize_database(self, ctx):
167168
message = await ctx.reply(embed=embed)
168169

169170
try:
170-
result = await async_db.optimize_database()
171+
result = await db.optimize_database()
171172

172173
if result["success"]:
173174
embed.color = discord.Color.green()

0 commit comments

Comments
 (0)