Potpot Potpot

Create a Discord bot with an owner-only Admin Panel. Only whitelisted users can assign themselves higher roles; everyone else is denied. Add "security say (message)": delete the user's message and repost it as the bot. Block inappropriate, hateful, sexual, or dangerous content and punish violations with a warning or timeout. Log actions.

Kodari AI
KodariSep 8 at 7:21 am 1
AdminGuardBot
A Discord bot providing an owner-only admin panel. Whitelisted users can self-assign elevated roles while others are denied. Includes a "security say" command that deletes the user's message and reposts it as the bot. Content filtering blocks hateful, sexual, dangerous, or inappropriate messages, issuing warnings or timeouts for violations. All actions are logged for accountability and moderation oversight.
  1. Core bot: create configuration, persistent whitelist/warning storage, moderation, and action logging.

  2. Owner Admin Panel: add whitelist management and restrict role self-assignment to whitelisted users and configured roles.

  3. Security moderation: add security say, message deletion/reposting, content filtering, warnings, timeouts, and command error handling.

  4. Setup: add dependency, environment template, ignore rules, and deployment instructions.

  1. Created a Discord bot with owner-only /admin panel controls for managing the self-role whitelist.

  2. Added /selfrole, restricted to whitelisted users and configured roles above the member’s current roles.

  3. Added !security say <message> with command-message deletion, bot reposting, mention prevention, and permission checks.

  4. Added moderation for inappropriate, hateful, sexual, and dangerous content with warnings, repeated-violation timeouts, and moderation logs.

  5. Added persistent JSON storage, environment configuration, dependency files, ignore rules, and setup documentation.

Potpot Potpot

Deploy

Kodari AI
KodariSep 8 at 7:23 am 1

Deployment requires a hosting target and Discord credentials. Choose one:

  1. Railway

  2. Render

  3. VPS using Docker

  4. Another provider

Set these as private environment variables on the host:

Env
DISCORD_TOKEN=your_bot_token
OWNER_ID=your_discord_user_id
MOD_LOG_CHANNEL_ID=your_log_channel_id
SELF_ASSIGNABLE_ROLE_IDS=role_id_1,role_id_2

Do not send the bot token here. The bot also needs its Discord application intents enabled and the required permissions from README.md.

Potpot Potpot

DISCORD_TOKEN=<redacted> OWNER_ID=1424365656509382696 MOD_LOG_CHANNEL_ID=your_log_channel_id SELF_ASSIGNABLE_ROLE_IDS=role_id_1,role_id_2

Kodari AI
KodariSep 8 at 7:25 am 1

That bot token is exposed and must be rotated immediately. I won’t use or store it.

  1. Open the Discord Developer Portal → Your Application → Bot.

  2. Click Reset Token, then copy the new token privately.

  3. Do not paste the replacement token here.

  4. Choose a deployment target: Railway, Render, VPS/Docker, or another provider.

  5. Replace the placeholders with actual Discord IDs:

    • MOD_LOG_CHANNEL_ID

    • SELF_ASSIGNABLE_ROLE_IDS

Use these as private host environment variables:

Env
DISCORD_TOKEN=<new_rotated_token>
OWNER_ID=1424365656509382696
MOD_LOG_CHANNEL_ID=<channel_id>
SELF_ASSIGNABLE_ROLE_IDS=<role_id_1>,<role_id_2>

I need the hosting provider and the real channel/role IDs before deployment can proceed.

Potpot Potpot

Don't add mod log channel ID, and Self assign role ids, uhm just find the role, like detect what's the bots highest role

Kodari AI
KodariSep 8 at 7:28 am 1
  1. Remove MOD_LOG_CHANNEL_ID and SELF_ASSIGNABLE_ROLE_IDS from configuration and setup docs.

  2. Make moderation/admin logs automatically use the guild’s configured bot log destination when available, without requiring an environment ID.

  3. Build the self-role menu from roles below the bot’s highest role, while retaining whitelist and hierarchy checks.

Updated:

  • Removed MOD_LOG_CHANNEL_ID and SELF_ASSIGNABLE_ROLE_IDS from .env.example and configuration.

  • /selfrole now automatically detects unmanaged roles below the bot’s highest role.

  • Whitelisted users can only select roles higher than their current highest role.

  • The bot still refuses managed roles, its own role level, and roles it cannot manage.

  • Logs are sent to the first available channel named mod-logs, moderation-logs, bot-logs, or logs.

  • If no matching log channel exists, actions are written to the bot console.

  • Fixed the self-role callback after removing the explicit role allowlist.

Your environment now only needs:

Env
DISCORD_TOKEN=<new_rotated_token>
OWNER_ID=1424365656509382696

The token previously posted in chat must still be regenerated in the Discord Developer Portal.

Potpot Potpot

Use the previous token,

Kodari AI
KodariSep 8 at 7:29 am 1

I can’t use the previous token because it was exposed in chat and should be considered compromised. Reset it in Discord Developer Portal → Application → Bot → Reset Token, then configure the replacement privately on your hosting provider.

Your environment only needs:

Env
DISCORD_TOKEN=<new_token>
OWNER_ID=1424365656509382696

Do not paste the new token here.

Potpot Potpot

Where do I paste it

Kodari AI
KodariSep 8 at 7:30 am 1

For local use, create a file named .env in the bot’s project root—the same folder as bot.py:

Env
DISCORD_TOKEN=your_new_rotated_token
OWNER_ID=1424365656509382696

Replace only your_new_rotated_token; don’t include quotes. Keep .env private and never commit it.

If deploying to a hosting provider, paste the same values into its Environment Variables / Secrets section instead:

  • Name: DISCORD_TOKEN
    Value: your newly reset token

  • Name: OWNER_ID
    Value: 1424365656509382696

Do not paste the token into bot.py, README.md, or this chat.

Potpot Potpot

Deploy

Kodari AI
KodariSep 8 at 7:31 am 1

I can’t deploy without a hosting provider and access to that provider. Choose one:

  1. Railway — easiest

  2. Render

  3. VPS/Docker

For Railway:

  1. Push the bot project to a private GitHub repository.

  2. Create a Railway project and select Deploy from GitHub.

  3. Add these private variables under Variables:

Env
DISCORD_TOKEN=<newly reset token>
OWNER_ID=1424365656509382696
  1. Set the start command to:

Shell
python bot.py
  1. Deploy and check the logs for the bot’s on_ready message.

The previously posted token must be reset first; do not add it to GitHub or paste the replacement here.

Potpot Potpot

Just do it yourself

Kodari AI
KodariSep 8 at 7:32 am 1

I can’t deploy it myself because I don’t have access to your Discord account, hosting account, or a deployment credential—and the previous token is compromised.

To deploy safely:

  1. Reset the token in Discord Developer Portal → Application → Bot → Reset Token.

  2. Choose a host such as Railway, Render, or a VPS.

  3. Add these private environment variables:

Env
DISCORD_TOKEN=<new-token>
OWNER_ID=1424365656509382696
  1. Set the start command to:

Shell
python bot.py

Never send the replacement token in chat.

Potpot Potpot

Don't host it, just deploy the commands

Kodari AI
KodariSep 8 at 7:32 am 1

The commands are already configured to deploy automatically in bot.py via self.tree.sync() when the bot starts.

To deploy them without hosting:

Shell
python bot.py

Leave it running until the log shows:

Plain Text
Synced N application commands

Then stop it with Ctrl+C. Global slash commands may take up to an hour to appear. I can’t perform the Discord API sync myself because the only token provided was exposed and must be reset first.

Potpot Potpot

Deploy now

Kodari AI
KodariSep 8 at 7:33 am 1

I can’t deploy the commands from here: I don’t have authenticated access to your Discord account, and the token you provided is compromised.

Do this locally from the bot folder after resetting the token:

Shell
python bot.py

Wait for:

Plain Text
Synced N application commands

Then stop it with Ctrl+C. Add the new token only to your private .env:

Env
DISCORD_TOKEN=<newly-reset-token>
OWNER_ID=1424365656509382696

Do not reuse the previous token.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.py
logging_utils.py
moderation.py
README.md
requirements.txt
storage.py
Code
8 594
bot.py
from __future__ import annotations

import logging
import re
import discord
from discord import app_commands
from discord.ext import commands

from config import Settings
from logging_utils import log_action
from moderation import ModerationService
from storage import JsonStore


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("kodari-bot")


class WhitelistModal(discord.ui.Modal):
    user_id = discord.ui.TextInput(
        label="User ID or mention",
        placeholder="123456789012345678",
        min_length=2,
        max_length=30,
    )

    def __init__(self, store: JsonStore, adding: bool) -> None:
        super().__init__(title="Add whitelist user" if adding else "Remove whitelist user")
        self.store = store
        self.adding = adding

    async def on_submit(self, interaction: discord.Interaction) -> None:
        if interaction.user.id != interaction.client.settings.owner_id:
            await interaction.response.send_message("Only the bot owner can manage the whitelist.", ephemeral=True)
            return

        match = re.fullmatch(r"<@!?([0-9]+)>|([0-9]+)", str(self.user_id.value).strip())
        if match is None:
            await interaction.response.send_message("Enter a valid user ID or mention.", ephemeral=True)
            return

        user_id = int(match.group(1) or match.group(2))
        changed = self.store.add_to_whitelist(user_id) if self.adding else self.store.remove_from_whitelist(user_id)
        action = "added to" if self.adding else "removed from"
        result = f"`{user_id}` was {action} the whitelist." if changed else f"`{user_id}` was already in the requested state."
        await interaction.response.send_message(result, ephemeral=True)
        await log_action(
            interaction.client,
            interaction.guild,
            "Whitelist updated",
            f"Owner: {interaction.user} (`{interaction.user.id}`)\nUser: `{user_id}`\nAction: {action}",
            discord.Color.blurple(),
        )


class AdminPanelView(discord.ui.View):
    def __init__(self, settings: Settings, store: JsonStore) -> None:
        super().__init__(timeout=300)
        self.settings = settings
        self.store = store

    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id != self.settings.owner_id:
            await interaction.response.send_message("This Admin Panel is owner-only.", ephemeral=True)
            return False
        return True

    @discord.ui.button(label="Add whitelist user", style=discord.ButtonStyle.success)
    async def add_user(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.send_modal(WhitelistModal(self.store, adding=True))

    @discord.ui.button(label="Remove whitelist user", style=discord.ButtonStyle.danger)
    async def remove_user(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.send_modal(WhitelistModal(self.store, adding=False))

    @discord.ui.button(label="List whitelist", style=discord.ButtonStyle.secondary)
    async def list_users(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        users = self.store.whitelist()
        text = "\n".join(f"• <@{user_id}> (`{user_id}`)" for user_id in users) or "The whitelist is empty."
        await interaction.response.send_message(text, ephemeral=True)


class SelfRoleSelect(discord.ui.Select):
    def __init__(self, settings: Settings, store: JsonStore, roles: list[discord.Role]) -> None:
        self.settings = settings
        self.store = store
        options = [
            discord.SelectOption(label=role.name[:100], value=str(role.id), description="Assign this role to yourself")
            for role in roles[:25]
        ]
        super().__init__(placeholder="Choose a role", min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction) -> None:
        if interaction.guild is None or not self.store.is_whitelisted(interaction.user.id):
            await interaction.response.send_message("You are not whitelisted for self-assigned roles.", ephemeral=True)
            return

        role_id = int(self.values[0])
        role = interaction.guild.get_role(role_id)
        member = interaction.guild.get_member(interaction.user.id)
        bot_member = interaction.guild.me
        if role is None or member is None or bot_member is None:
            await interaction.response.send_message("That role is unavailable in this server.", ephemeral=True)
            return
        if role.is_default() or role.managed or role >= bot_member.top_role:
            await interaction.response.send_message("The bot cannot safely assign that role.", ephemeral=True)
            return
        if role in member.roles:
            await interaction.response.send_message("You already have that role.", ephemeral=True)
            return
        if role.position <= member.top_role.position:
            await interaction.response.send_message("You can only assign a role higher than your current roles.", ephemeral=True)
            return

        try:
            await member.add_roles(role, reason="Whitelisted self-role assignment")
        except discord.DiscordException:
            await interaction.response.send_message("I could not assign that role.", ephemeral=True)
            return

        await interaction.response.send_message(f"Assigned **{role.name}** to you.", ephemeral=True)
        await log_action(
            interaction.client,
            interaction.guild,
            "Self-role assigned",
            f"User: {member} (`{member.id}`)\nRole: {role.name} (`{role.id}`)",
            discord.Color.green(),
        )


class SelfRoleView(discord.ui.View):
    def __init__(self, settings: Settings, store: JsonStore, roles: list[discord.Role]) -> None:
        super().__init__(timeout=120)
        self.add_item(SelfRoleSelect(settings, store, roles))


class KodariBot(commands.Bot):
    def __init__(self, settings: Settings) -> None:
        intents = discord.Intents.default()
        intents.message_content = True
        intents.members = True
        super().__init__(command_prefix=settings.command_prefix, intents=intents, help_command=None)
        self.settings = settings
        self.store = JsonStore(settings.data_file)
        self.moderation = ModerationService(
            self,
            self.store,
            settings.warning_timeout_seconds,
        )

    async def setup_hook(self) -> None:
        try:
            synced = await self.tree.sync()
            logger.info("Synced %d application commands", len(synced))
        except discord.DiscordException:
            logger.exception("Could not sync application commands")

    async def on_ready(self) -> None:
        logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")

    async def on_message(self, message: discord.Message) -> None:
        if message.author.bot:
            return
        if await self.moderation.handle_message(message):
            return
        await self.process_commands(message)

    async def on_command_error(self, context: commands.Context, error: commands.CommandError) -> None:
        if isinstance(error, commands.CommandNotFound):
            return
        if isinstance(error, commands.MissingRequiredArgument):
            await context.send(f"Missing argument: `{error.param.name}`.", delete_after=6)
            return
        if isinstance(error, commands.CheckFailure):
            await context.send("You do not have permission to use that command.", delete_after=6)
            return
        logger.exception("Command error", exc_info=error)
        await context.send("That command failed. Check the bot logs for details.", delete_after=6)


def register_commands(bot: KodariBot) -> None:
    @bot.group(name="security", invoke_without_command=True)
    async def security(context: commands.Context) -> None:
        if context.invoked_subcommand is None:
            await context.send(f"Use `{bot.settings.command_prefix}security say <message>`.", delete_after=8)

    @security.command(name="say")
    @commands.guild_only()
    @commands.has_permissions(manage_messages=True)
    async def security_say(context: commands.Context, *, message: str) -> None:
        if len(message) > 2000:
            await context.send("The reposted message must be 2,000 characters or fewer.", delete_after=6)
            return

        try:
            await context.message.delete()
        except discord.DiscordException: