jacckk0423
๐Ÿ“Ž 1 file 2,354 chars
๐Ÿ“„
pasted-code-1792935082116.txt
txt 47 lines
โ–ถ
Create a Discord staff management bot for an ERLC (Emergency Response: Liberty County) roleplay community called [SERVER NAME]. Use slash commands only.

COMMANDS:

1. /promote
Options: user (User), old_rank (Role), new_rank (Role), reason (String)
- Only members with the Manage Roles permission (or the role [HIGH COMMAND ROLE]) can use it.
- Remove the old rank role and give the new rank role.
- Ping the promoted user above the embed.
- Post an embed in the promotions channel with:
  - Author line: "Signed, [username of the person who ran the command]" with their avatar
  - Title: "๐ŸŽ‰ [SERVER NAME] - Promotion"
  - Description: "The [SERVER NAME] Senior High Ranking members have decided to promote you. Congratulations on your new rank!"
  - Fields in the description: "๐Ÿ‘ค Promoted Staff" (user mention), "โœจ New Rank" (old rank โ†’ new rank), "๐Ÿ“‹ Reason" (as a quote)
  - A large banner image at the bottom
  - Footer: "Promotion for [username]" with a timestamp
  - Blue color

2. /demote
Same options and layout as /promote, but red, titled "Demotion", with a message about the demotion. Remove the higher rank and give the lower rank.

3. /infract
Options: user (User), type (Choice: Warning, Strike, Suspension, Termination), reason (String), appealable (Choice: Yes/No)
- Post a red embed in the infractions channel and DM the user the same information.
- Save every infraction to a database with a unique case ID, date, staff member, and reason.

4. /infractions
Option: user (User). Shows a user's full infraction history.

5. /session
Subcommands: start, vote, end.
- /session vote posts an embed with a Join/Interested button that counts votes.
- /session start posts a "Session Started" embed with the host, server name, and server code.
- /session end posts a "Session Ended" embed and logs who hosted it.

6. /profile
Option: user (User). Shows rank, promotions, infractions, and sessions hosted.

SETTINGS:
- A /setup command to set the promotions channel, infractions channel, sessions channel, and staff log channel.
- A permission system so only specific roles can use each command.
- Clear error messages if the bot lacks permission or the role is above its own.
- Log every action in a staff-logs channel.

STYLE:
- Clean, professional embeds with consistent colors and emojis.
- Slash commands with autocomplete where possible.
Kodari AI
KodariOct 25 at 1:39 pm 1
StaffManagementBot
A Discord staff management bot for ERLC roleplay communities using slash commands. Features include promotion/demotion commands with embed notifications, an infraction system with database storage and unique case IDs, session management with voting buttons, and user profiles showing rank history. Includes a setup command for channel configuration, role-based permission system, and comprehensive staff logging. Professional embeds with consistent colors, emojis, and autocomplete support.
  1. Build a slash-command-only discord.py bot with role changes, infractions, sessions, profiles, and staff logging.

  2. Add SQLite persistence, configurable channels/command roles, and persistent session-vote buttons.

  3. Add dependency and .env templates with no privileged intents enabled.

Created the ERLC staff bot with slash commands for promotions, demotions, infractions and history, sessions, profiles, and administrator setup. It stores records in SQLite and restores session-vote buttons after restarts.

Set DISCORD_TOKEN, SERVER_NAME, SERVER_CODE, and HIGH_COMMAND_ROLE_ID in .env, then use /setup channel to configure channels and /setup permission to restrict commands to roles. The bot uses no privileged intents.

jacckk0423

add that if i promote,demot,infract,session so they got dm

Kodari AI
KodariOct 25 at 1:55 pm 1
  • DM the promoted or demoted member the rank-change embed.

  • Keep infraction DMs and notify the session host and opted-in voters when sessions start/end; DM the poll creator a copy of the vote.

  • Handle closed DMs without interrupting the command and report delivery in the command response.

Promotions and demotions now DM the affected member, and infractions continue to DM them. Session vote creators get a DM copy of the poll; session hosts and members who voted interest get DMs when a session starts or ends. The bot reports how many session DMs were delivered; privacy settings may prevent some DMs.

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

import aiosqlite
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("erlc_staff_bot")

DATABASE_PATH = os.getenv("DATABASE_PATH", "bot.db")
SERVER_NAME = os.getenv("SERVER_NAME", "ERLC Roleplay")
SERVER_CODE = os.getenv("SERVER_CODE", "Not configured")
PROMOTION_BANNER_URL = os.getenv("PROMOTION_BANNER_URL", "")
HIGH_COMMAND_ROLE_ID = int(os.getenv("HIGH_COMMAND_ROLE_ID", "0") or "0")
BLUE = discord.Color.blue()
RED = discord.Color.red()
GREEN = discord.Color.green()


async def initialize_database():
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.executescript(
            """
            CREATE TABLE IF NOT EXISTS settings (
                guild_id INTEGER NOT NULL,
                key TEXT NOT NULL,
                value TEXT NOT NULL,
                PRIMARY KEY (guild_id, key)
            );
            CREATE TABLE IF NOT EXISTS infractions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                staff_id INTEGER NOT NULL,
                type TEXT NOT NULL,
                reason TEXT NOT NULL,
                appealable TEXT NOT NULL,
                created_at TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS promotions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                staff_id INTEGER NOT NULL,
                action TEXT NOT NULL,
                old_role_id INTEGER NOT NULL,
                new_role_id INTEGER NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS sessions (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                host_id INTEGER NOT NULL,
                kind TEXT NOT NULL,
                status TEXT NOT NULL,
                channel_id INTEGER NOT NULL,
                message_id INTEGER,
                started_at TEXT NOT NULL,
                ended_at TEXT
            );
            CREATE TABLE IF NOT EXISTS session_votes (
                session_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                PRIMARY KEY (session_id, user_id)
            );
            """
        )
        await db.commit()


async def get_setting(guild_id: int, key: str):
    async with aiosqlite.connect(DATABASE_PATH) as db:
        async with db.execute(
            "SELECT value FROM settings WHERE guild_id = ? AND key = ?",
            (guild_id, key),
        ) as cursor:
            row = await cursor.fetchone()
    return row[0] if row else None


async def set_setting(guild_id: int, key: str, value: str):
    async with aiosqlite.connect(DATABASE_PATH) as db:
        await db.execute(
            "INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?) "
            "ON CONFLICT(guild_id, key) DO UPDATE SET value = excluded.value",
            (guild_id, key, value),
        )
        await db.commit()


async def configured_text_channel(guild: discord.Guild, key: str):
    channel_id = await get_setting(guild.id, f"channel:{key}")
    if not channel_id:
        return None
    channel = bot.get_channel(int(channel_id))
    if channel is None:
        try:
            channel = await bot.fetch_channel(int(channel_id))
        except (discord.NotFound, discord.Forbidden, discord.HTTPException):
            return None
    return channel if isinstance(channel, discord.TextChannel) else None


async def log_action(guild: discord.Guild, title: str, description: str, color=BLUE):
    channel = await configured_text_channel(guild, "staff_logs")
    if channel is None:
        return
    try:
        await channel.send(embed=discord.Embed(title=title, description=description, color=color))
    except discord.HTTPException:
        logger.exception("Unable to post an action to the staff log channel")


def has_role(member: discord.Member, role_id: int):
    return bool(role_id and any(role.id == role_id for role in member.roles))


async def require_permission(interaction: discord.Interaction, command_key: str):
    member = interaction.user
    if not isinstance(member, discord.Member):
        await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
        return False

    configured_role_id = await get_setting(interaction.guild_id, f"permission:{command_key}")
    if configured_role_id and not has_role(member, int(configured_role_id)):
        await interaction.response.send_message(
            f"You need the configured role for `/{command_key.replace('_', ' ')}` to use this command.",
            ephemeral=True,
        )
        return False

    high_command = has_role(member, HIGH_COMMAND_ROLE_ID)
    if command_key in ("promote", "demote"):
        allowed = member.guild_permissions.manage_roles or high_command
    elif command_key in ("infract", "infractions"):
        allowed = member.guild_permissions.manage_messages or high_command
    elif command_key in ("session_start", "session_end"):
        allowed = member.guild_permissions.manage_guild or high_command
    else:
        allowed = True

    if not allowed:
        if command_key in ("promote", "demote"):
            message = "You need Manage Roles or the configured High Command role to use this command."
        elif command_key in ("infract", "infractions"):
            message = "You need Manage Messages or the configured High Command role to use this command."
        else:
            message = "You need Manage Server or the configured High Command role to use this command."
        await interaction.response.send_message(message, ephemeral=True)
        return False
    return True


async def get_member(guild: discord.Guild, user: discord.User):
    member = guild.get_member(user.id)
    if member is not None:
        return member
    try:
        return await guild.fetch_member(user.id)
    except (discord.NotFound, discord.Forbidden, discord.HTTPException):
        return None


async def send_dm(user: discord.abc.User, embed: discord.Embed):
    try:
        await user.send(embed=embed)
        return True
    except (discord.Forbidden, discord.HTTPException):
        return False


async def notify_session_audience(guild_id: int, embed: discord.Embed, additional_user_ids=()):
    async with aiosqlite.connect(DATABASE_PATH) as db:
        async with db.execute(
            "SELECT DISTINCT sv.user_id FROM session_votes sv "
            "JOIN sessions s ON s.id = sv.session_id "
            "WHERE s.guild_id = ? AND s.kind = 'vote' AND s.status = 'open'",
            (guild_id,),
        ) as cursor:
            user_ids = {row[0] for row in await cursor.fetchall()}

    user_ids.update(additional_user_ids)
    delivered = 0
    for user_id in user_ids:
        user = bot.get_user(user_id)
        if user is None:
            try:
                user = await bot.fetch_user(user_id)
            except (discord.NotFound, discord.Forbidden, discord.HTTPException):
                continue
        if await send_dm(user, embed):
            delivered += 1