d01m

make me a discord bot that registers players to teams, and team owners and managers can send offers to free agents to accept or decline to join the team

Kodari AI
KodariNov 15 at 7:14 pm 1
TeamRecruitBot
A Discord bot for managing team rosters and recruitment. Players register themselves, then team owners and managers can send join offers to free agents. Free agents receive a DM with accept/decline buttons, and the bot updates team rosters and player statuses accordingly. Includes role-based permissions for team management, offer tracking, and roster display commands.

I’ll create a guild-scoped Discord bot with persistent SQLite registrations, team management, and offer inbox/accept/decline commands.

Created a Discord bot with guild-specific SQLite storage. Players can register as free agents, and team owners can appoint managers, send offers, remove players, or disband their team. Players can view, accept, or decline offers with slash commands.

Use /register to join the free-agent list, /team create to create a team, /offer send to make an offer, and /offer inbox to review offers. The bot also provides /team info, /team roster, /team leave, and manager-management commands.

Replace the placeholder in .env with your bot token before starting it. The bot uses slash commands and does not require privileged intents.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 562
bot.py
import logging
import os
import sqlite3
from datetime import datetime, timezone

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("team_bot")
load_dotenv()


class TeamDatabase:
    def __init__(self, path: str = "teams.sqlite3") -> None:
        self.connection = sqlite3.connect(path)
        self.connection.row_factory = sqlite3.Row

    def initialize(self) -> None:
        self.connection.executescript(
            """
            PRAGMA foreign_keys = ON;
            CREATE TABLE IF NOT EXISTS teams (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                name TEXT COLLATE NOCASE NOT NULL,
                owner_id INTEGER NOT NULL,
                created_at TEXT NOT NULL,
                UNIQUE (guild_id, name)
            );
            CREATE TABLE IF NOT EXISTS players (
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                team_id INTEGER REFERENCES teams(id) ON DELETE SET NULL,
                registered_at TEXT NOT NULL,
                PRIMARY KEY (guild_id, user_id)
            );
            CREATE TABLE IF NOT EXISTS managers (
                team_id INTEGER NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
                user_id INTEGER NOT NULL,
                PRIMARY KEY (team_id, user_id)
            );
            CREATE TABLE IF NOT EXISTS offers (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                team_id INTEGER NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
                guild_id INTEGER NOT NULL,
                player_id INTEGER NOT NULL,
                sender_id INTEGER NOT NULL,
                status TEXT NOT NULL DEFAULT 'pending',
                created_at TEXT NOT NULL
            );
            CREATE UNIQUE INDEX IF NOT EXISTS one_pending_offer_per_team_player
            ON offers(team_id, player_id) WHERE status = 'pending';
            """
        )
        self.connection.commit()

    @staticmethod
    def now() -> str:
        return datetime.now(timezone.utc).isoformat()

    def register_player(self, guild_id: int, user_id: int) -> str:
        current = self.connection.execute(
            "SELECT team_id FROM players WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ).fetchone()
        if current:
            return "member" if current["team_id"] is not None else "registered"
        self.connection.execute(
            "INSERT INTO players (guild_id, user_id, registered_at) VALUES (?, ?, ?)",
            (guild_id, user_id, self.now()),
        )
        self.connection.commit()
        return "created"

    def unregister_player(self, guild_id: int, user_id: int) -> str:
        player = self.connection.execute(
            "SELECT team_id FROM players WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ).fetchone()
        if not player:
            return "missing"
        if player["team_id"] is not None:
            return "member"
        self.connection.execute(
            "UPDATE offers SET status = 'cancelled' WHERE guild_id = ? AND player_id = ? AND status = 'pending'",
            (guild_id, user_id),
        )
        self.connection.execute(
            "DELETE FROM players WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        )
        self.connection.commit()
        return "removed"

    def create_team(self, guild_id: int, name: str, owner_id: int) -> int | None:
        try:
            cursor = self.connection.execute(
                "INSERT INTO teams (guild_id, name, owner_id, created_at) VALUES (?, ?, ?, ?)",
                (guild_id, name, owner_id, self.now()),
            )
            self.connection.commit()
            return cursor.lastrowid
        except sqlite3.IntegrityError:
            return None

    def get_team(self, guild_id: int, name: str) -> sqlite3.Row | None:
        return self.connection.execute(
            "SELECT * FROM teams WHERE guild_id = ? AND name = ? COLLATE NOCASE",
            (guild_id, name),
        ).fetchone()

    def team_role(self, team_id: int, user_id: int) -> str | None:
        team = self.connection.execute(
            "SELECT owner_id FROM teams WHERE id = ?", (team_id,)
        ).fetchone()
        if not team:
            return None
        if team["owner_id"] == user_id:
            return "owner"
        manager = self.connection.execute(
            "SELECT 1 FROM managers WHERE team_id = ? AND user_id = ?",
            (team_id, user_id),
        ).fetchone()
        return "manager" if manager else None

    def add_manager(self, team_id: int, user_id: int) -> bool:
        try:
            self.connection.execute(
                "INSERT INTO managers (team_id, user_id) VALUES (?, ?)",
                (team_id, user_id),
            )
            self.connection.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def remove_manager(self, team_id: int, user_id: int) -> bool:
        cursor = self.connection.execute(
            "DELETE FROM managers WHERE team_id = ? AND user_id = ?",
            (team_id, user_id),
        )
        self.connection.commit()
        return cursor.rowcount > 0

    def team_roster(self, team_id: int) -> list[int]:
        rows = self.connection.execute(
            "SELECT user_id FROM players WHERE team_id = ? ORDER BY user_id", (team_id,)
        ).fetchall()
        return [row["user_id"] for row in rows]

    def managers_for_team(self, team_id: int) -> list[int]:
        rows = self.connection.execute(
            "SELECT user_id FROM managers WHERE team_id = ? ORDER BY user_id", (team_id,)
        ).fetchall()
        return [row["user_id"] for row in rows]

    def leave_team(self, guild_id: int, user_id: int) -> bool:
        player = self.connection.execute(
            "SELECT team_id FROM players WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ).fetchone()
        if not player or player["team_id"] is None:
            return False
        self.connection.execute(
            "UPDATE players SET team_id = NULL WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        )
        self.connection.execute(
            "UPDATE offers SET status = 'cancelled' WHERE guild_id = ? AND player_id = ? AND status = 'pending'",
            (guild_id, user_id),
        )
        self.connection.commit()
        return True

    def remove_player_from_team(self, guild_id: int, team_id: int, user_id: int) -> bool:
        cursor = self.connection.execute(
            "UPDATE players SET team_id = NULL WHERE guild_id = ? AND user_id = ? AND team_id = ?",
            (guild_id, user_id, team_id),
        )
        if cursor.rowcount:
            self.connection.execute(
                "UPDATE offers SET status = 'cancelled' WHERE guild_id = ? AND player_id = ? AND status = 'pending'",
                (guild_id, user_id),
            )
        self.connection.commit()
        return cursor.rowcount > 0

    def disband_team(self, team_id: int) -> None:
        self.connection.execute(
            "UPDATE offers SET status = 'cancelled' WHERE team_id = ? AND status = 'pending'",
            (team_id,),
        )
        self.connection.execute("DELETE FROM teams WHERE id = ?", (team_id,))