Files
database
utils
.gitignore
config.py
requirements.txt
schema.sql
Code
7 410
database/db_manager.py
import aiosqlite
import os
from datetime import datetime, timedelta
from typing import Optional, List, Dict, Any
class DatabaseManager:
def __init__(self, db_path: str):
self.db_path = db_path
async def initialize(self):
if not os.path.exists(self.db_path):
async with aiosqlite.connect(self.db_path) as db:
with open('schema.sql', 'r') as f:
await db.executescript(f.read())
await db.commit()
async def register_player(self, discord_id: int, brawl_tag: str, player_name: str,
trophies: int, clan_role: str) -> bool:
try:
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
INSERT INTO players (discord_id, brawl_tag, player_name, current_trophies,
highest_trophies, clan_role)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(discord_id) DO UPDATE SET
brawl_tag = excluded.brawl_tag,
player_name = excluded.player_name,
current_trophies = excluded.current_trophies,
clan_role = excluded.clan_role,
last_update = CURRENT_TIMESTAMP
''', (discord_id, brawl_tag, player_name, trophies, trophies, clan_role))
await db.execute('''
INSERT INTO trophy_history (discord_id, trophies)
VALUES (?, ?)
''', (discord_id, trophies))
await db.commit()
return True
except Exception as e:
print(f"Database error in register_player: {e}")
return False
async def get_player(self, discord_id: int) -> Optional[Dict[str, Any]]:
async with aiosqlite.connect(self.db_path) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
'SELECT * FROM players WHERE discord_id = ?', (discord_id,)
) as cursor:
row = await cursor.fetchone()
return dict(row) if row else None
async def get_player_by_tag(self, brawl_tag: str) -> Optional[Dict[str, Any]]:
async with aiosqlite.connect(self.db_path) as db:
db.row_factory = aiosqlite.Row
async with db.execute(
'SELECT * FROM players WHERE brawl_tag = ?', (brawl_tag,)
) as cursor:
row = await cursor.fetchone()
return dict(row) if row else None
async def update_player_trophies(self, discord_id: int, new_trophies: int, clan_role: str):
async with aiosqlite.connect(self.db_path) as db:
player = await self.get_player(discord_id)
if not player:
return
old_trophies = player['current_trophies']
progress = new_trophies - old_trophies
await db.execute('''
UPDATE players
SET current_trophies = ?,
highest_trophies = MAX(highest_trophies, ?),
clan_role = ?,
last_update = CURRENT_TIMESTAMP
WHERE discord_id = ?
''', (new_trophies, new_trophies, clan_role, discord_id))
await db.execute('''
INSERT INTO trophy_history (discord_id, trophies)
VALUES (?, ?)
''', (discord_id, new_trophies))
if progress != 0:
await db.execute('''
INSERT INTO activity_log (discord_id, trophies_before, trophies_after, progress)
VALUES (?, ?, ?, ?)
''', (discord_id, old_trophies, new_trophies, progress))
await db.commit()
async def get_all_players(self) -> List[Dict[str, Any]]:
async with aiosqlite.connect(self.db_path) as db:
db.row_factory = aiosqlite.Row
async with db.execute('SELECT * FROM players ORDER BY current_trophies DESC') as cursor:
rows = await cursor.fetchall()
return [dict(row) for row in rows]
async def get_weekly_progress(self, days: int = 7) -> List[Dict[str, Any]]:
async with aiosqlite.connect(self.db_path) as db:
db.row_factory = aiosqlite.Row
cutoff = datetime.now() - timedelta(days=days)
async with db.execute('''
SELECT
p.discord_id,
p.player_name,
p.current_trophies,
COALESCE(SUM(al.progress), 0) as weekly_progress
FROM players p
LEFT JOIN activity_log al ON p.discord_id = al.discord_id
AND al.logged_at > ?
GROUP BY p.discord_id
ORDER BY weekly_progress DESC
''', (cutoff,)) as cursor:
rows = await cursor.fetchall()
return [dict(row) for row in rows]
async def get_inactive_players(self, days: int) -> List[Dict[str, Any]]:
async with aiosqlite.connect(self.db_path) as db:
db.row_factory = aiosqlite.Row
cutoff = datetime.now() - timedelta(days=days)
async with db.execute('''
SELECT
p.*,
MAX(al.logged_at) as last_activity
FROM players p
LEFT JOIN activity_log al ON p.discord_id = al.discord_id
GROUP BY p.discord_id
HAVING last_activity IS NULL OR last_activity < ?
ORDER BY last_activity ASC
''', (cutoff,)) as cursor:
rows = await cursor.fetchall()
return [dict(row) for row in rows]
async def get_setting(self, key: str) -> Optional[str]:
async with aiosqlite.connect(self.db_path) as db:
async with db.execute(
'SELECT value FROM clan_settings WHERE key = ?', (key,)
) as cursor:
row = await cursor.fetchone()
return row[0] if row else None
async def set_setting(self, key: str, value: str):
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
INSERT INTO clan_settings (key, value)
VALUES (?, ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value
''', (key, value))
await db.commit()
async def cleanup_old_history(self, days: int = 90):
async with aiosqlite.connect(self.db_path) as db:
cutoff = datetime.now() - timedelta(days=days)
await db.execute(
'DELETE FROM trophy_history WHERE recorded_at < ?', (cutoff,)
)
await db.execute(
'DELETE FROM activity_log WHERE logged_at < ?', (cutoff,)
)
await db.commit()