vonn0ob.

Fix the moderation role make them can’t use $ban, $unban and $kick And fix the quarantine to they can’t access the channels and fix the user they can write reason why they rated them like that and fix the servicechannel log the feedback and the ticket staff that claimed the ticket and add the optional channel at /boostset

Kodari AI
KodariSep 13 at 11:52 pm 2
ModerationOverhaul
Overhauls the moderation system by restricting moderator roles from using $ban, $unban, and $kick commands. Implements quarantine functionality that prevents quarantined users from accessing specific channels. Adds a reason field for user ratings, enabling them to explain their feedback. Enhances the service channel to log all feedback and track which staff member claimed each ticket. Introduces an optional channel parameter to the /boostset command for flexible configuration.
  1. Build the discord.py bot foundation with persistent guild configuration and secure environment-based token loading.

  2. Add moderation-role restrictions for $ban, $unban, and $kick, plus quarantine role channel isolation.

  3. Add ticket creation, staff claiming, feedback ratings with written reasons, and service-channel logging.

  4. Add /boostset and boost notification delivery, with setup commands and usage documentation.

  1. Created the discord.py bot with .env token loading and persistent guild configuration.

  2. Added moderation-role blocking for $ban, $unban, and $kick.

  3. Added quarantine roles that deny channel access, with /quarantine and /unquarantine.

  4. Added ticket panels, staff claiming, feedback ratings with written reasons, and service-channel logging.

  5. Added optional boost notifications through /boostset.

  6. Added setup instructions in README.md.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 658
bot.py
import json
import logging
import os
from pathlib import Path
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("kodari")


class ConfigStore:
    def __init__(self, path: Path):
        self.path = path
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.data = {"guilds": {}}
        self._load()

    def _load(self):
        if not self.path.exists():
            self._save()
            return
        try:
            with self.path.open("r", encoding="utf-8") as file:
                loaded = json.load(file)
            if isinstance(loaded, dict) and isinstance(loaded.get("guilds"), dict):
                self.data = loaded
        except (OSError, json.JSONDecodeError):
            logger.exception("Could not load configuration; using an empty configuration")

    def _save(self):
        temporary_path = self.path.with_suffix(".tmp")
        with temporary_path.open("w", encoding="utf-8") as file:
            json.dump(self.data, file, indent=2, sort_keys=True)
        temporary_path.replace(self.path)

    def guild(self, guild_id: int) -> dict:
        guilds = self.data.setdefault("guilds", {})
        return guilds.setdefault(str(guild_id), {})

    def get(self, guild_id: int, key: str) -> Optional[int]:
        value = self.guild(guild_id).get(key)
        return int(value) if value is not None else None

    def set(self, guild_id: int, key: str, value: Optional[int]):
        settings = self.guild(guild_id)
        if value is None:
            settings.pop(key, None)
        else:
            settings[key] = int(value)
        self._save()


class KodariBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True
        intents.bans = True
        super().__init__(command_prefix="$", intents=intents, help_command=None)
        self.config = ConfigStore(Path("data/config.json"))

    async def setup_hook(self):
        self.add_view(TicketPanelView(self))
        self.add_view(TicketActionsView(self))
        for command in SLASH_COMMANDS:
            self.tree.add_command(command)
        await self.tree.sync()

    async def on_ready(self):
        logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
        for guild in self.guilds:
            await apply_quarantine_overwrites(self, guild)

    async def on_message(self, message: discord.Message):
        if not message.author.bot:
            await self.process_commands(message)

    async def on_guild_channel_create(self, channel: discord.abc.GuildChannel):
        await apply_quarantine_overwrites(self, channel.guild, channel=channel)

    async def on_member_update(self, before: discord.Member, after: discord.Member):
        quarantine_role_id = self.config.get(after.guild.id, "quarantine_role_id")
        if quarantine_role_id:
            had_role = any(role.id == quarantine_role_id for role in before.roles)
            has_role = any(role.id == quarantine_role_id for role in after.roles)
            if had_role != has_role:
                await apply_quarantine_overwrites(self, after.guild)

        if before.premium_since is None and after.premium_since is not None:
            channel_id = self.config.get(after.guild.id, "boost_channel_id")
            channel = after.guild.get_channel(channel_id) if channel_id else None
            if isinstance(channel, discord.TextChannel):
                await channel.send(
                    embed=discord.Embed(
                        title="New Server Boost",
                        description=f"{after.mention} boosted the server. Thank you!",
                        color=discord.Color.fuchsia(),
                    )
                )

    async def on_command_error(self, context: commands.Context, error: commands.CommandError):
        if isinstance(error, commands.CommandNotFound):
            return
        if isinstance(error, commands.CommandOnCooldown):
            await context.send(f"Try again in {error.retry_after:.1f} seconds.")
            return
        if isinstance(error, commands.MissingRequiredArgument):
            await context.send(f"Missing argument: `{error.param.name}`.")
            return
        if isinstance(error, commands.BadArgument):
            await context.send("That argument is not valid.")
            return
        if isinstance(error, commands.NoPrivateMessage):
            await context.send("This command can only be used in a server.")
            return
        if isinstance(error, commands.CheckFailure):
            await context.send("You cannot use that command.")
            return
        logger.exception("Unhandled command error", exc_info=error)
        await context.send("An unexpected error occurred while running that command.")

    async def log_service(self, guild: discord.Guild, embed: discord.Embed):
        channel_id = self.config.get(guild.id, "service_channel_id")
        channel = guild.get_channel(channel_id) if channel_id else None
        if isinstance(channel, discord.TextChannel):
            await channel.send(embed=embed)


bot = KodariBot()


def member_has_role(member: discord.Member, role_id: Optional[int]) -> bool:
    return role_id is not None and any(role.id == role_id for role in member.roles)


def is_guild_manager(member: discord.Member) -> bool:
    permissions = member.guild_permissions
    return permissions.administrator or permissions.manage_guild


def is_ticket_staff(member: discord.Member, guild: discord.Guild) -> bool:
    if member.guild_permissions.administrator or member.guild_permissions.manage_channels:
        return True
    return member_has_role(member, bot.config.get(guild.id, "moderation_role_id"))


def ticket_metadata(channel: discord.TextChannel) -> Optional[dict]:
    topic = channel.topic or ""
    if not topic.startswith("kodari-ticket|"):
        return None
    values = {}
    for item in topic.split("|")[1:]:
        if "=" in item:
            key, value = item.split("=", 1)
            values[key] = value
    return values


def serialize_ticket_metadata(metadata: dict) -> str:
    return "kodari-ticket|" + "|".join(f"{key}={value}" for key, value in metadata.items())


async def apply_quarantine_overwrites(
    client: KodariBot,
    guild: discord.Guild,
    channel: Optional[discord.abc.GuildChannel] = None,
):
    role_id = client.config.get(guild.id, "quarantine_role_id")
    role = guild.get_role(role_id) if role_id else None
    if role is None:
        return

    channels = [channel] if channel is not None else guild.channels
    quarantined = any(member_has_role(member, role.id) for member in guild.members)
    for guild_channel in channels:
        if not guild_channel or not hasattr(guild_channel, "set_permissions"):
            continue
        try:
            if quarantined:
                overwrite = guild_channel.overwrites_for(role)
                overwrite.view_channel = False
                overwrite.send_messages = False
                overwrite.read_message_history = False
                overwrite.connect = False
                overwrite.speak = False
                await guild_channel.set_permissions(
                    role,
                    overwrite=overwrite,
                    reason="Keep quarantined members out of server channels",