sinz.6

make me a discord infraction bot to infract staff members

Kodari AI
KodariAug 25 at 2:56 am 1
StaffInfractionBot
A Discord moderation bot that tracks infractions for staff members. It allows authorized admins to issue warnings, kicks, and bans to staff, logs each infraction with timestamps and reasons, and maintains a persistent infraction history per user. Includes commands to view a staff member's record, appeal infractions, and generate summary reports. Uses discord.py with SQLite storage for durable record-keeping and role-based permission checks to restrict usage to server leadership.
  • Create a secure discord.py slash-command bot for staff-only infractions.

  • Add SQLite persistence, audit-channel logging, target DMs, history lookup, and pardoning.

  • Add environment-based configuration, dependency metadata, and setup documentation.

Created a complete Discord staff infraction bot with:

  • /infract for warnings, strikes, final warnings, and suspensions

  • /infractions for viewing active or resolved cases

  • /pardon for resolving infractions

  • SQLite persistence

  • Staff and moderator role restrictions

  • Role hierarchy protection

  • Optional audit-channel logging

  • Private responses and staff-member DM notifications

  • Environment-based token/configuration

  • Setup documentation and dependency files

Run it with:

Shell
cp .env.example .env
python -m pip install -r requirements.txt
python bot.py
Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 457
bot.py
import logging
import os
import sqlite3
from datetime import datetime, timezone
from typing import Optional

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


load_dotenv()

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


def parse_id_set(value: str) -> set[int]:
    result = set()
    for item in value.split(","):
        item = item.strip()
        if not item:
            continue
        try:
            result.add(int(item))
        except ValueError:
            logger.warning("Ignoring invalid Discord ID in configuration: %s", item)
    return result


STAFF_ROLE_IDS = parse_id_set(os.getenv("STAFF_ROLE_IDS", ""))
MODERATOR_ROLE_IDS = parse_id_set(os.getenv("MODERATOR_ROLE_IDS", ""))
AUDIT_CHANNEL_ID = int(os.getenv("AUDIT_CHANNEL_ID", "0") or "0")
DB_PATH = os.getenv("DB_PATH", "infractions.db")
SYNC_GUILD_ID = int(os.getenv("SYNC_GUILD_ID", "0") or "0")


class InfractionError(Exception):
    pass


class InfractionStore:
    def __init__(self, path: str):
        self.connection = sqlite3.connect(path)
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA journal_mode=WAL")
        self.connection.execute(
            """
            CREATE TABLE IF NOT EXISTS infractions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                target_id INTEGER NOT NULL,
                actor_id INTEGER NOT NULL,
                kind TEXT NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL,
                active INTEGER NOT NULL DEFAULT 1,
                resolved_at TEXT,
                resolved_by INTEGER,
                resolution_reason TEXT
            )
            """
        )
        self.connection.execute(
            "CREATE INDEX IF NOT EXISTS idx_infractions_target ON infractions(guild_id, target_id)"
        )
        self.connection.commit()

    def add(
        self,
        guild_id: int,
        target_id: int,
        actor_id: int,
        kind: str,
        reason: str,
    ) -> int:
        cursor = self.connection.execute(
            """
            INSERT INTO infractions
                (guild_id, target_id, actor_id, kind, reason, created_at)
            VALUES (?, ?, ?, ?, ?, ?)
            """,
            (
                guild_id,
                target_id,
                actor_id,
                kind,
                reason,
                datetime.now(timezone.utc).isoformat(),
            ),
        )
        self.connection.commit()
        return int(cursor.lastrowid)

    def list_for_target(
        self, guild_id: int, target_id: int, include_resolved: bool
    ) -> list[sqlite3.Row]:
        query = (
            "SELECT * FROM infractions WHERE guild_id = ? AND target_id = ? "
            + ("ORDER BY id DESC LIMIT 25" if include_resolved else "AND active = 1 ORDER BY id DESC LIMIT 25")
        )
        return list(self.connection.execute(query, (guild_id, target_id)).fetchall())

    def get(self, guild_id: int, infraction_id: int) -> Optional[sqlite3.Row]:
        return self.connection.execute(
            "SELECT * FROM infractions WHERE guild_id = ? AND id = ?",
            (guild_id, infraction_id),
        ).fetchone()

    def resolve(
        self,
        guild_id: int,
        infraction_id: int,
        actor_id: int,
        reason: str,
    ) -> bool:
        cursor = self.connection.execute(
            """
            UPDATE infractions
            SET active = 0, resolved_at = ?, resolved_by = ?, resolution_reason = ?
            WHERE guild_id = ? AND id = ? AND active = 1
            """,
            (
                datetime.now(timezone.utc).isoformat(),
                actor_id,
                reason,
                guild_id,
                infraction_id,
            ),
        )
        self.connection.commit()
        return cursor.rowcount == 1

    def close(self) -> None:
        self.connection.close()


def clean_reason(reason: str) -> str:
    reason = " ".join(reason.split())
    if len(reason) < 3:
        raise InfractionError("The reason must be at least 3 characters long.")
    return reason


def ensure_guild(interaction: discord.Interaction) -> discord.Guild:
    if interaction.guild is None:
        raise InfractionError("This command can only be used inside a server.")
    return interaction.guild


def can_manage_infractions(member: discord.Member) -> bool:
    permissions = member.guild_permissions
    return (
        permissions.administrator
        or permissions.manage_guild
        or any(role.id in MODERATOR_ROLE_IDS for role in member.roles)
    )


def validate_target(
    guild: discord.Guild, actor: discord.Member, target: discord.Member
) -> None:
    if target.bot:
        raise InfractionError("Bots cannot receive staff infractions.")
    if target.id == actor.id:
        raise InfractionError("You cannot infract yourself.")
    if target.id == guild.owner_id:
        raise InfractionError("The server owner cannot receive an infraction.")

    if STAFF_ROLE_IDS:
        is_staff = any(role.id in STAFF_ROLE_IDS for role in target.roles)
    else:
        permissions = target.guild_permissions
        is_staff = (
            permissions.administrator
            or permissions.manage_guild
            or permissions.moderate_members
        )
    if not is_staff:
        raise InfractionError("The selected member is not recognized as staff.")

    elevated_actor = actor.guild_permissions.administrator or actor.id == guild.owner_id
    if not elevated_actor and actor.top_role <= target.top_role:
        raise InfractionError(
            "You can only infract staff members with a lower role than yours."
        )


async def send_result(
    interaction: discord.Interaction,
    content: str,
    *,
    embed: Optional[discord.Embed] = None,
    ephemeral: bool = True,
) -> None:
    if interaction.response.is_done():