jhon_jhon121

make me a discord bot code that has the following commands " !addcargo @user @role(s) and it give the pinged roles to the pinged user but the user that uses the command has got to have a sertain role to execute this command and cannot give role to themselfs or higher than their role " " !remcargo @user @role(s) and it removes the selected roles from the selected user but the same permissions as the !addcargo " !strip @user and in removes all roles from a user but not a special role " !infold @user and it displays every detail about this user and details about what warnings the have or ban history " " !warn @user @reason and it gives a warning to the pinged user and it is documented on !infold " !unwarn @user @reason it removes the warning from the user " " !sban @user @reason and it gives a user a role and removes every single role they have " " !unsban @user @reason and it removes the ban and gives the user the roles they had before getting banned " and make sure each of these commands have a differant role who can execute these commands but make sure their is a admin role the can do all these camands and make sure there is a channel that this bot logs everything inside

Kodari AI
KodariOct 5 at 4:59 pm 1
RoleManagerBot
A Discord moderation bot with role management and warning systems. Features role assignment/removal commands (!addcargo, !remcargo) with permission hierarchy checks preventing self-assignment or granting roles above the executor's rank. Includes user info lookup (!infold) displaying warnings and ban history, warning system (!warn, !unwarn), soft-ban functionality (!sban, !unsban) that stores and restores previous roles, and full role stripping (!strip) that preserves special roles. Each command has distinct permission requirements with an admin override role. All actions logged to a dedicated logging channel.
  1. Build the prefix-command bot with per-command role checks, a shared admin-role bypass, and hierarchy protections.

  2. Add SQLite-backed warnings, moderation history, and saved roles for sban/unsban.

  3. Add configurable role/channel IDs, audit logging, and startup/dependency files.

Created the bot with all eight commands, per-command role permissions plus an admin-role bypass, hierarchy checks, command audit logging, and SQLite storage for warnings and sban role snapshots.

Before starting:

  • Replace the placeholder in .env with your bot token.

  • In config.json, replace the 0 values with the relevant Discord role and log-channel IDs. Give each command its own command_roles role ID; admin_role_id can use every command.

  • Enable Message Content Intent and Server Members Intent in the app’s Discord Developer Portal → Bot → Privileged Gateway Intents.

  • Give the bot Manage Roles permission and put its highest role above the roles it needs to manage.

!unwarn @user <warning ID or exact reason> removes a warning; its ID appears in !infold. !sban is a role-based ban that saves removable roles for !unsban to restore. !strip preserves the configured protected role.

jhon_jhon121

make a !cargoperms and a panel pops up and it allows me to put the role ID for each permission for each command and where the bot logs different commands.

Kodari AI
KodariOct 5 at 6:09 pm 1
  1. Add !cargoperms with an interactive configuration panel for command permission-role IDs and per-command log channels, then persist its settings in the existing config.

Added !cargoperms. Server administrators or members with the configured admin role can open the panel, choose a command, and set its required role ID and audit log channel ID. Use 0 for the default log channel. The admin bypass role is configurable in the same panel, and settings are saved to config.json.

jhon_jhon121

then for the !cargoperms make it so that i can edit the error messages for each error

Kodari AI
KodariOct 5 at 6:11 pm 1
  • Add a separate error-message selector and editor to !cargoperms.

  • Save custom messages in config.json, with blank input restoring the default.

  • Route command and panel validation errors through the saved messages, preserving useful placeholders.

Added error-message editing to !cargoperms. Choose an error from the new dropdown, click Edit error message, and submit your custom response. Leave the field blank to restore its default; changes save to config.json.

The panel covers permission, argument, lookup, hierarchy, role, warning, sban, and settings-validation errors. Placeholders such as {target}, {role}, {item}, {command}, and {signature} work where relevant.

jhon_jhon121

make the panel look like a popup panel on your screen not in the chat

Kodari AI
KodariOct 5 at 6:54 pm 1

Discord can’t open an actual floating panel from a ! message command. I’ll make !cargoperms send the panel privately by DM and add /cargoperms to open it as an ephemeral panel visible only to you.

/cargoperms now opens the settings panel as a private ephemeral response; !cargoperms sends it by DM instead of posting it in the server channel. Discord doesn’t support opening a true floating popup directly from a prefix command.

jhon_jhon121

make the panel pop up on my screen instead of it in chat

Kodari AI
KodariOct 5 at 6:59 pm 1
  • Make /cargoperms open a native Discord modal immediately, rather than a message-style panel.

  • Let the popup edit command roles/log channels or a selected error message, saving changes to config.json.

  • Have !cargoperms direct users to the slash command, since prefix commands can’t open Discord popups.

/cargoperms now opens a native Discord popup immediately. Enter admin or a command name to edit its permission role and log channel; enter error:<key> to edit an error message. Leave fields blank to keep existing settings, or leave the error message blank to reset it.

!cargoperms now points users to /cargoperms, because Discord prefix commands can’t open popups.

Kodari can make mistakes. Review important code before using.
Files
bot.py
config.json
requirements.txt
Code
3 867
bot.py
import json
import logging
import os
import sqlite3
from datetime import datetime, timezone
from pathlib import Path

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


BASE_DIR = Path(__file__).resolve().parent
DATABASE_PATH = BASE_DIR / "moderation.sqlite3"
CONFIG_PATH = BASE_DIR / "config.json"

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


def load_config():
    with CONFIG_PATH.open(encoding="utf-8") as config_file:
        config = json.load(config_file)
    config["admin_role_id"] = int(config.get("admin_role_id", 0))
    config["log_channel_id"] = int(config.get("log_channel_id", 0))
    config["protected_role_id"] = int(config.get("protected_role_id", 0))
    config["sban_role_id"] = int(config.get("sban_role_id", 0))
    config["command_roles"] = {
        name: int(role_id) for name, role_id in config.get("command_roles", {}).items()
    }
    config["command_log_channels"] = {
        name: int(channel_id) for name, channel_id in config.get("command_log_channels", {}).items()
    }
    config["error_messages"] = {
        str(key): str(message) for key, message in config.get("error_messages", {}).items()
    }
    return config


CONFIG = load_config()

ERROR_MESSAGE_DEFAULTS = {
    "permission_denied": ("Permission denied", "You do not have the required role to use this command."),
    "guild_only": ("Server only", "This command can only be used in a server."),
    "missing_argument": ("Missing argument", "Missing argument. Usage: `!{command} {signature}`"),
    "member_or_role_not_found": ("Member or role not found", "I could not find that member or role. Mention them or use their ID."),
    "unknown_command": ("Unknown command", "I don't recognize that command."),
    "unexpected": ("Unexpected command error", "The command failed unexpectedly. Check the bot logs or ask an administrator."),
    "panel_owner": ("Panel used by another user", "Only the person who opened this panel can use it."),
    "invalid_role_id": ("Invalid role ID", "Role ID must be a number (use `0` to disable it)."),
    "role_not_found": ("Role does not exist", "That role ID does not identify a configurable server role."),
    "invalid_log_channel": ("Invalid log channel", "Use `0` for the default channel or enter the ID of a text channel in this server."),
    "config_save_failed": ("Could not save settings", "Could not save the settings to config.json."),
    "self_target": ("Self-targeting", "You cannot use this command on yourself."),
    "missing_roles": ("No roles selected", "Mention at least one role to add or remove."),
    "target_hierarchy": ("Target role hierarchy", "You can only moderate members whose highest role is below yours."),
    "bot_hierarchy": ("Bot role hierarchy", "The bot's highest role must be above {item}."),
    "bot_role_missing": ("Bot role hierarchy unavailable", "The bot could not verify its server role hierarchy."),
    "role_not_below_actor": ("Role above your rank", "You cannot manage {role}; it is not below your highest role."),
    "reserved_role": ("Reserved role", "{role} is reserved and cannot be changed with this command."),
    "target_lacks_role": ("Target does not have role", "{target} does not have {role}."),
    "warning_not_found": ("Warning not found", "No active warning matched that ID or exact reason."),
    "warning_ambiguous": ("Warning reason is ambiguous", "More than one warning has that reason; use its ID from !infold instead."),
    "sban_role_not_configured": ("sban role not configured", "Configure a valid sban_role_id in config.json first."),
    "invalid_sban_role": ("Invalid sban role", "The configured sban role must be a normal, assignable server role."),
    "existing_sban": ("Existing sban snapshot", "This member already has an active sban role snapshot."),
    "missing_snapshot": ("No saved role snapshot", "No saved role snapshot was found for this member."),
}


def configured_error(key, **values):
    default = ERROR_MESSAGE_DEFAULTS[key][1]
    template = CONFIG["error_messages"].get(key, default)
    try:
        return template.format(**values)
    except (IndexError, KeyError, ValueError):
        return template


def connect_database():
    connection = sqlite3.connect(DATABASE_PATH)
    connection.row_factory = sqlite3.Row
    return connection


def initialize_database():
    with connect_database() as connection:
        connection.executescript(
            """
            CREATE TABLE IF NOT EXISTS warnings (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                moderator_id INTEGER NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS moderation_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                moderator_id INTEGER NOT NULL,
                action TEXT NOT NULL,
                reason TEXT NOT NULL,
                created_at TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS role_snapshots (
                guild_id INTEGER NOT NULL,
                user_id INTEGER NOT NULL,
                role_ids TEXT NOT NULL,
                PRIMARY KEY (guild_id, user_id)
            );
            """
        )


def timestamp():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def add_history(guild_id, user_id, moderator_id, action, reason):
    with connect_database() as connection:
        connection.execute(
            "INSERT INTO moderation_history (guild_id, user_id, moderator_id, action, reason, created_at) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (guild_id, user_id, moderator_id, action, reason, timestamp()),
        )


def add_warning(guild_id, user_id, moderator_id, reason):
    with connect_database() as connection:
        cursor = connection.execute(
            "INSERT INTO warnings (guild_id, user_id, moderator_id, reason, created_at) "
            "VALUES (?, ?, ?, ?, ?)",
            (guild_id, user_id, moderator_id, reason, timestamp()),
        )
        return cursor.lastrowid


def get_warnings(guild_id, user_id):
    with connect_database() as connection:
        return connection.execute(
            "SELECT * FROM warnings WHERE guild_id = ? AND user_id = ? ORDER BY id DESC",
            (guild_id, user_id),
        ).fetchall()


def remove_warning(guild_id, user_id, moderator_id, warning_ref):
    warnings = get_warnings(guild_id, user_id)
    if warning_ref.isdecimal():
        matches = [warning for warning in warnings if warning["id"] == int(warning_ref)]
    else:
        matches = [
            warning for warning in warnings
            if warning["reason"].casefold() == warning_ref.casefold()
        ]
    if len(matches) != 1:
        return "missing" if not matches else "ambiguous"

    warning = matches[0]
    with connect_database() as connection:
        connection.execute("DELETE FROM warnings WHERE id = ?", (warning["id"],))
    add_history(guild_id, user_id, moderator_id, "unwarn", warning["reason"])
    return warning["id"]


def get_history(guild_id, user_id):
    with connect_database() as connection:
        return connection.execute(
            "SELECT * FROM moderation_history WHERE guild_id = ? AND user_id = ? "
            "ORDER BY id DESC",
            (guild_id, user_id),
        ).fetchall()


def get_role_snapshot(guild_id, user_id):
    with connect_database() as connection:
        row = connection.execute(
            "SELECT role_ids FROM role_snapshots WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        ).fetchone()
    return json.loads(row["role_ids"]) if row else None


def save_role_snapshot(guild_id, user_id, role_ids):
    with connect_database() as connection:
        connection.execute(
            "INSERT INTO role_snapshots (guild_id, user_id, role_ids) VALUES (?, ?, ?)",
            (guild_id, user_id, json.dumps(role_ids)),
        )


def delete_role_snapshot(guild_id, user_id):
    with connect_database() as connection:
        connection.execute(
            "DELETE FROM role_snapshots WHERE guild_id = ? AND user_id = ?",
            (guild_id, user_id),
        )