karkartif-coder

Jesteś doświadczonym programistą Discord botów i znasz Brawl Stars API (Supercell).

Twoim zadaniem jest zaprojektowanie i napisanie Discord bota, który w pełni zarządza klanem w grze Brawl Stars.

BOT MA:

  • integrować Discord z Brawl Stars (rejestracja graczy po tagu)
  • sprawdzać czy gracz należy do konkretnego klanu
  • przypisywać role Discord (Leader, Vice, Member, Inactive)
  • pobierać statystyki graczy z Brawl Stars API
  • zapisywać historię pucharów i aktywności
  • wykrywać nieaktywnych graczy (brak progresu X dni)
  • tworzyć rankingi tygodniowe i dzienne
  • obsługiwać cele klanowe (np. minimalny progres)
  • wysyłać automatyczne raporty na kanał Discord
  • posiadać komendy tylko dla liderów
  • działać automatycznie (zadania cykliczne)

WYMAGANIA TECHNICZNE:

  • język: Python
  • biblioteka: discord.py
  • baza danych: SQLite
  • użycie slash commands
  • czytelna struktura projektu
  • komentarze w kodzie
  • bezpieczne przechowywanie tokenów (.env)

NAJPIERW:

  1. Zaprojektuj architekturę bota
  2. Opisz strukturę bazy danych
  3. Wypisz wszystkie komendy
  4. Następnie napisz podstawowy działający kod (MVP)

Nie pisz skrótowo. Tłumacz decyzje techniczne krok po kroku.

Kodari AI
KodariJan 9 at 3:17 pm

Rozumiem zadanie. Stworzę kompletnego Discord bota do zarządzania klanem Brawl Stars z integracją API.

ANALIZA I PROJEKT

1. ARCHITEKTURA BOTA

Plain Text
BrawlStarsBot/
├── bot.py                 # Punkt wejścia, inicjalizacja
├── config.py             # Konfiguracja (ID ról, kanałów)
├── database/
│   └── db_manager.py     # Obsługa SQLite
├── cogs/
│   ├── registration.py   # Rejestracja graczy
│   ├── stats.py         # Statystyki i rankingi
│   ├── admin.py         # Komendy dla liderów
│   └── tasks.py         # Zadania automatyczne
├── utils/
│   ├── brawlstars_api.py # Wrapper dla BS API
│   ├── role_manager.py   # Zarządzanie rolami Discord
│   └── validators.py     # Walidacja tagów, danych
├── .env                  # Tokeny (GIT IGNORE!)
├── requirements.txt
└── schema.sql           # Schemat bazy danych

2. BAZA DANYCH (SQLite)

Tabela: players

  • discord_id (PRIMARY KEY) - ID użytkownika Discord

  • brawl_tag (UNIQUE) - Tag gracza Brawl Stars

  • current_trophies - Aktualne puchary

  • last_update - Ostatnia aktualizacja danych

  • joined_at - Data dołączenia do systemu

Tabela: trophy_history

  • id (PRIMARY KEY)

  • discord_id (FOREIGN KEY)

  • trophies - Liczba pucharów

  • recorded_at - Data zapisu

Tabela: activity_log

  • id (PRIMARY KEY)

  • discord_id (FOREIGN KEY)

  • progress - Zmiana pucharów

  • logged_at - Data aktywności

Tabela: clan_settings

  • key (PRIMARY KEY) - Nazwa ustawienia

  • value - Wartość (przechowuje: clan_tag, min_weekly_trophies, inactivity_days)

3. LISTA KOMEND

Publiczne:

  • /register <tag> - Rejestracja gracza

  • /stats [gracz] - Statystyki gracza

  • /ranking - Ranking klanowy

  • /progress - Twój progres tygodniowy

Tylko dla liderów:

  • /admin set_clan <tag> - Ustawienie klanu

  • /admin sync_roles - Synchronizacja ról

  • /admin check_inactive - Sprawdź nieaktywnych

  • /admin set_goal <puchary> - Ustaw cel tygodniowy

  • /admin report - Generuj raport

Automatyczne zadania:

  • Co 6h: Aktualizacja statystyk

  • Codziennie: Sprawdzanie aktywności

  • W niedzielę: Raport tygodniowy


BrawlStarsDiscordBot
Discord bot for comprehensive Brawl Stars clan management with Supercell API integration. Features player registration by tag, automatic role assignment based on clan hierarchy, trophy tracking with historical data, inactivity detection, weekly/daily rankings, clan goal management, and automated reporting. Includes leader-only commands and scheduled background tasks for stats updates and activity monitoring.

Teraz tworzę kompletny kod MVP:

Kodari can make mistakes. Review important code before using.
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()