modified: app.py

This commit is contained in:
SimolZimol
2025-10-26 01:35:24 +02:00
parent 3abe6bd10d
commit 5b91b8ebd3

192
app.py
View File

@@ -4,7 +4,7 @@ import os
import asyncio import asyncio
import logging import logging
from dotenv import load_dotenv from dotenv import load_dotenv
import asyncpg import aiomysql
import json import json
from datetime import datetime from datetime import datetime
from typing import Optional, List, Dict from typing import Optional, List, Dict
@@ -25,9 +25,51 @@ DB_PASSWORD = os.getenv('DB_PASSWORD')
# Build DATABASE_URL from individual components if not provided # Build DATABASE_URL from individual components if not provided
if not DATABASE_URL and all([DB_HOST, DB_NAME, DB_USER, DB_PASSWORD]): if not DATABASE_URL and all([DB_HOST, DB_NAME, DB_USER, DB_PASSWORD]):
DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}" DATABASE_URL = f"mysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
print(f"📝 Built DATABASE_URL from individual environment variables") print(f"📝 Built DATABASE_URL from individual environment variables")
# Parse MySQL connection details from DATABASE_URL
def parse_database_url(url):
"""Parse MySQL connection URL into components"""
if not url:
return None
# Remove mysql:// prefix
if url.startswith('mysql://'):
url = url[8:]
# Split user:pass@host:port/db
if '@' in url:
auth, host_db = url.split('@', 1)
if ':' in auth:
user, password = auth.split(':', 1)
else:
user, password = auth, ''
else:
return None
if '/' in host_db:
host_port, database = host_db.split('/', 1)
else:
return None
if ':' in host_port:
host, port = host_port.split(':', 1)
try:
port = int(port)
except ValueError:
port = 3306
else:
host, port = host_port, 3306
return {
'host': host,
'port': port,
'user': user,
'password': password,
'db': database
}
# Global database connection pool # Global database connection pool
db_pool = None db_pool = None
@@ -90,49 +132,68 @@ async def init_database():
"""Initialize database connection and create tables""" """Initialize database connection and create tables"""
global db_pool global db_pool
try: try:
db_pool = await asyncpg.create_pool(DATABASE_URL) # Parse DATABASE_URL for MySQL connection
db_config = parse_database_url(DATABASE_URL)
if not db_config:
raise ValueError("Invalid DATABASE_URL format")
print(f"🔌 Connecting to MySQL: {db_config['host']}:{db_config['port']}/{db_config['db']}")
# Create MySQL connection pool
db_pool = await aiomysql.create_pool(
host=db_config['host'],
port=db_config['port'],
user=db_config['user'],
password=db_config['password'],
db=db_config['db'],
charset='utf8mb4',
autocommit=True,
maxsize=10
)
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
# Create players table async with conn.cursor() as cursor:
await conn.execute(''' # Create players table (MySQL syntax)
await cursor.execute('''
CREATE TABLE IF NOT EXISTS players ( CREATE TABLE IF NOT EXISTS players (
id SERIAL PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
discord_id BIGINT UNIQUE NOT NULL, discord_id BIGINT UNIQUE NOT NULL,
username VARCHAR(255) NOT NULL, username VARCHAR(255) NOT NULL,
standard_elo INTEGER DEFAULT 800, standard_elo INT DEFAULT 800,
competitive_elo INTEGER DEFAULT 800, competitive_elo INT DEFAULT 800,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) )
''') ''')
# Create games table # Create games table (MySQL syntax)
await conn.execute(''' await cursor.execute('''
CREATE TABLE IF NOT EXISTS games ( CREATE TABLE IF NOT EXISTS games (
id SERIAL PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
game_name VARCHAR(255) NOT NULL, game_name VARCHAR(255) NOT NULL,
game_type VARCHAR(50) NOT NULL, game_type VARCHAR(50) NOT NULL,
status VARCHAR(50) DEFAULT 'setup', status VARCHAR(50) DEFAULT 'setup',
players JSONB NOT NULL DEFAULT '[]', players JSON NOT NULL,
winner_team VARCHAR(255), winner_team VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
finished_at TIMESTAMP finished_at TIMESTAMP NULL
) )
''') ''')
# Create game_results table for detailed match history # Create game_results table (MySQL syntax)
await conn.execute(''' await cursor.execute('''
CREATE TABLE IF NOT EXISTS game_results ( CREATE TABLE IF NOT EXISTS game_results (
id SERIAL PRIMARY KEY, id INT AUTO_INCREMENT PRIMARY KEY,
game_id INTEGER REFERENCES games(id), game_id INT,
discord_id BIGINT NOT NULL, discord_id BIGINT NOT NULL,
team_name VARCHAR(255) NOT NULL, team_name VARCHAR(255) NOT NULL,
t_level INTEGER NOT NULL, t_level INT NOT NULL,
old_elo INTEGER NOT NULL, old_elo INT NOT NULL,
new_elo INTEGER NOT NULL, new_elo INT NOT NULL,
elo_change INTEGER NOT NULL, elo_change INT NOT NULL,
won BOOLEAN NOT NULL, won BOOLEAN NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (game_id) REFERENCES games(id)
) )
''') ''')
@@ -140,29 +201,34 @@ async def init_database():
except Exception as e: except Exception as e:
print(f"❌ Database initialization failed: {e}") print(f"❌ Database initialization failed: {e}")
import traceback
traceback.print_exc()
async def get_or_create_player(discord_id: int, username: str) -> Dict: async def get_or_create_player(discord_id: int, username: str) -> Dict:
"""Get or create a player in the database""" """Get or create a player in the database"""
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
# Try to get existing player # Try to get existing player
player = await conn.fetchrow( await cursor.execute(
"SELECT * FROM players WHERE discord_id = $1", discord_id "SELECT * FROM players WHERE discord_id = %s", (discord_id,)
) )
player = await cursor.fetchone()
if not player: if not player:
# Create new player # Create new player
await conn.execute( await cursor.execute(
"INSERT INTO players (discord_id, username) VALUES ($1, $2)", "INSERT INTO players (discord_id, username) VALUES (%s, %s)",
discord_id, username (discord_id, username)
) )
player = await conn.fetchrow( await cursor.execute(
"SELECT * FROM players WHERE discord_id = $1", discord_id "SELECT * FROM players WHERE discord_id = %s", (discord_id,)
) )
player = await cursor.fetchone()
else: else:
# Update username if changed # Update username if changed
await conn.execute( await cursor.execute(
"UPDATE players SET username = $1, updated_at = CURRENT_TIMESTAMP WHERE discord_id = $2", "UPDATE players SET username = %s, updated_at = CURRENT_TIMESTAMP WHERE discord_id = %s",
username, discord_id (username, discord_id)
) )
return dict(player) return dict(player)
@@ -240,20 +306,22 @@ async def hoi4create(ctx, game_type: str, game_name: str):
try: try:
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
# Check if game name already exists and is active # Check if game name already exists and is active
existing_game = await conn.fetchrow( await cursor.execute(
"SELECT * FROM games WHERE game_name = $1 AND status = 'setup'", "SELECT * FROM games WHERE game_name = %s AND status = 'setup'",
game_name (game_name,)
) )
existing_game = await cursor.fetchone()
if existing_game: if existing_game:
await ctx.send(f"❌ A game with name '{game_name}' is already in setup phase!") await ctx.send(f"❌ A game with name '{game_name}' is already in setup phase!")
return return
# Create new game # Create new game
await conn.execute( await cursor.execute(
"INSERT INTO games (game_name, game_type, status) VALUES ($1, $2, 'setup')", "INSERT INTO games (game_name, game_type, status, players) VALUES (%s, %s, 'setup', %s)",
game_name, game_type.lower() (game_name, game_type.lower(), '[]')
) )
embed = discord.Embed( embed = discord.Embed(
@@ -280,11 +348,13 @@ async def hoi4setup(ctx, game_name: str, user: discord.Member, team_name: str, t
try: try:
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
# Get the game # Get the game
game = await conn.fetchrow( await cursor.execute(
"SELECT * FROM games WHERE game_name = $1 AND status = 'setup'", "SELECT * FROM games WHERE game_name = %s AND status = 'setup'",
game_name (game_name,)
) )
game = await cursor.fetchone()
if not game: if not game:
await ctx.send(f"❌ No game found with name '{game_name}' in setup phase!") await ctx.send(f"❌ No game found with name '{game_name}' in setup phase!")
@@ -313,9 +383,9 @@ async def hoi4setup(ctx, game_name: str, user: discord.Member, team_name: str, t
players.append(player_data) players.append(player_data)
# Update game # Update game
await conn.execute( await cursor.execute(
"UPDATE games SET players = $1 WHERE id = $2", "UPDATE games SET players = %s WHERE id = %s",
json.dumps(players), game['id'] (json.dumps(players), game['id'])
) )
embed = discord.Embed( embed = discord.Embed(
@@ -339,11 +409,13 @@ async def hoi4end(ctx, game_name: str, winner_team: str):
"""End a game and calculate ELO changes""" """End a game and calculate ELO changes"""
try: try:
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cursor:
# Get the game # Get the game
game = await conn.fetchrow( await cursor.execute(
"SELECT * FROM games WHERE game_name = $1 AND status = 'setup'", "SELECT * FROM games WHERE game_name = %s AND status = 'setup'",
game_name (game_name,)
) )
game = await cursor.fetchone()
if not game: if not game:
await ctx.send(f"❌ No active game found with name '{game_name}'!") await ctx.send(f"❌ No active game found with name '{game_name}'!")
@@ -416,25 +488,25 @@ async def hoi4end(ctx, game_name: str, winner_team: str):
for change in elo_changes: for change in elo_changes:
# Update player ELO # Update player ELO
elo_field = f"{game['game_type']}_elo" elo_field = f"{game['game_type']}_elo"
await conn.execute( await cursor.execute(
f"UPDATE players SET {elo_field} = $1, updated_at = CURRENT_TIMESTAMP WHERE discord_id = $2", f"UPDATE players SET {elo_field} = %s, updated_at = CURRENT_TIMESTAMP WHERE discord_id = %s",
change['new_elo'], change['discord_id'] (change['new_elo'], change['discord_id'])
) )
# Save game result # Save game result
await conn.execute( await cursor.execute(
"""INSERT INTO game_results """INSERT INTO game_results
(game_id, discord_id, team_name, t_level, old_elo, new_elo, elo_change, won) (game_id, discord_id, team_name, t_level, old_elo, new_elo, elo_change, won)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)""", VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
game['id'], change['discord_id'], change['team_name'], (game['id'], change['discord_id'], change['team_name'],
change['t_level'], change['old_elo'], change['new_elo'], change['t_level'], change['old_elo'], change['new_elo'],
change['elo_change'], change['won'] change['elo_change'], change['won'])
) )
# Mark game as finished # Mark game as finished
await conn.execute( await cursor.execute(
"UPDATE games SET status = 'finished', winner_team = $1, finished_at = CURRENT_TIMESTAMP WHERE id = $2", "UPDATE games SET status = 'finished', winner_team = %s, finished_at = CURRENT_TIMESTAMP WHERE id = %s",
winner_team, game['id'] (winner_team, game['id'])
) )
# Create result embed # Create result embed
@@ -501,9 +573,11 @@ async def hoi4games(ctx):
"""Show all active games""" """Show all active games"""
try: try:
async with db_pool.acquire() as conn: async with db_pool.acquire() as conn:
games = await conn.fetch( async with conn.cursor(aiomysql.DictCursor) as cursor:
await cursor.execute(
"SELECT * FROM games WHERE status = 'setup' ORDER BY created_at DESC" "SELECT * FROM games WHERE status = 'setup' ORDER BY created_at DESC"
) )
games = await cursor.fetchall()
if not games: if not games:
await ctx.send("📝 No active games found. Use `/hoi4create` to create a new game!") await ctx.send("📝 No active games found. Use `/hoi4create` to create a new game!")