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),
)