2sp2yy

i want you to make a discord bot where any channel is made from a specific category will automatically sync no matter if its new or the other channel has perms as long it is in that category it should SYNC

Kodari AI
KodariSep 2 at 3:26 am 1
CategoryPermSync
A Discord bot that automatically synchronizes permissions for all channels within a designated category. When a new channel is created in the category, it inherits the category's permission settings. If any channel's permissions are modified, the bot detects the change and reverts it to match the category's permissions, ensuring consistent access control across all channels in the category. Supports multiple categories and provides commands to add or remove categories from the sync list.
  1. Create a configurable Discord bot that synchronizes every existing and newly created channel under one category to that category’s permission overwrites.

  2. Add automatic handling for channels moved into the category and permission changes made on the category.

  3. Add a protected /sync_category recovery command plus environment-based setup documentation.

Created the Discord category permission sync bot.

  • Syncs existing channels on startup.

  • Automatically syncs newly created channels.

  • Re-syncs channels moved into the configured category.

  • Re-syncs channels if their permissions are manually changed.

  • Re-syncs all channels when the category permissions change.

  • Added /sync_category manual recovery command.

  • Uses .env for DISCORD_TOKEN and CATEGORY_ID.

  • Added requirements.txt, .env.example, .gitignore, and setup instructions in README.md.

2sp2yy

so how do i add this into my server and such

Kodari AI
KodariSep 2 at 3:32 am 1

To add and run the bot:

1. Create the Discord application

  1. Click New Application.

  2. Name it.

  3. Open the Bot tab and click Add Bot.

  4. Click Reset Token, then copy the token. Keep it private.

You do not need to enable privileged intents for this bot unless the code specifically asks for them.

2. Invite the bot to your server

In the Developer Portal:

  1. Open OAuth2 → URL Generator.

  2. Select these scopes:

    • bot

    • applications.commands

  3. Select these bot permissions:

    • View Channels

    • Manage Channels

    • Send Messages

  4. Copy the generated URL.

  5. Open the URL, select your server, and authorize the bot.

The bot needs Manage Channels to change channel permission overwrites.

3. Get the category ID

  1. In Discord, open User Settings → Advanced.

  2. Enable Developer Mode.

  3. Right-click the category you want synchronized.

  4. Click Copy Category ID.

4. Configure the bot

In the bot folder, copy:

Plain Text
.env.example

and rename the copy to:

Plain Text
.env

Open .env and enter:

Env
DISCORD_TOKEN=your_bot_token_here
CATEGORY_ID=your_category_id_here

For example:

Env
DISCORD_TOKEN=abc123...
CATEGORY_ID=123456789012345678

Do not share the token or upload .env.

5. Install and run it

Open a terminal in the bot folder and run:

Shell
pip install -r requirements.txt
python bot.py

On Windows, if python does not work, try:

Shell
py -m pip install -r requirements.txt
py bot.py

You should see a message indicating that the bot is logged in and ready.

6. How synchronization works

Once running, the bot will:

  • Synchronize existing channels inside the configured category.

  • Synchronize channels newly created in that category.

  • Synchronize channels moved into the category.

  • Reapply the category permissions if a channel’s permissions are changed.

  • Update all channels when the category permissions change.

  • Provide /sync_category as a manual recovery command.

The bot must remain running for automatic synchronization to work. Running it on your computer works while the terminal is open; for 24/7 operation, host it on a VPS or another always-on Python hosting service.

Also note that users with Discord’s Administrator permission can still bypass channel permission restrictions.

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 221
bot.py
import asyncio
import logging
import os

import discord
from discord import app_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("category-permission-sync")


def required_category_id() -> int:
    value = os.getenv("CATEGORY_ID", "").strip()
    if not value.isdigit():
        raise RuntimeError("CATEGORY_ID must be set to a Discord category ID")
    return int(value)


class SyncCommandTree(app_commands.CommandTree):
    async def on_error(
        self,
        interaction: discord.Interaction,
        error: app_commands.AppCommandError,
    ) -> None:
        logger.error("Application command failed: %s", error, exc_info=error)
        message = "The command could not be completed. Check the bot logs."
        try:
            if interaction.response.is_done():
                await interaction.followup.send(message, ephemeral=True)
            else:
                await interaction.response.send_message(message, ephemeral=True)
        except discord.HTTPException:
            logger.exception("Could not send the application command error message")


class CategoryPermissionSyncBot(discord.Client):
    def __init__(self, category_id: int) -> None:
        intents = discord.Intents.none()
        intents.guilds = True
        super().__init__(intents=intents)
        self.category_id = category_id
        self.tree = SyncCommandTree(self)
        self._sync_lock = asyncio.Lock()

    @staticmethod
    def channel_category_id(channel: discord.abc.GuildChannel) -> int | None:
        return getattr(channel, "category_id", None)

    async def setup_hook(self) -> None:
        @app_commands.command(
            name="sync_category",
            description="Synchronize all channels in the configured category",
        )
        async def sync_category_command(interaction: discord.Interaction) -> None:
            if interaction.guild is None:
                await interaction.response.send_message(
                    "This command can only be used in a server.", ephemeral=True
                )
                return

            permissions = getattr(interaction.user, "guild_permissions", None)
            if permissions is None or not permissions.manage_channels:
                await interaction.response.send_message(
                    "You need the Manage Channels permission to use this command.",
                    ephemeral=True,
                )
                return

            await interaction.response.defer(ephemeral=True)
            category = interaction.guild.get_channel(self.category_id)
            if not isinstance(category, discord.CategoryChannel):
                await interaction.followup.send(
                    "The configured category was not found in this server.",
                    ephemeral=True,
                )
                return

            synced = await self.sync_category(category)
            await interaction.followup.send(
                f"Synchronized {synced} channel(s) in **{category.name}**.",
                ephemeral=True,
            )

        self.tree.add_command(sync_category_command)
        try:
            await self.tree.sync()
            logger.info("Registered application commands")
        except discord.HTTPException:
            logger.exception("Could not register application commands")

    async def on_ready(self) -> None:
        await self.sync_all_guilds()
        logger.info("Logged in as %s", self.user)

    async def on_guild_channel_create(
        self, channel: discord.abc.GuildChannel
    ) -> None:
        await self.sync_channel_if_configured(channel)

    async def on_guild_channel_update(
        self,
        before: discord.abc.GuildChannel,
        after: discord.abc.GuildChannel,
    ) -> None:
        if after.id == self.category_id and isinstance(after, discord.CategoryChannel):
            await self.sync_category(after)
            return

        was_configured = self.channel_category_id(before) == self.category_id
        is_configured = self.channel_category_id(after) == self.category_id
        if was_configured or is_configured:
            await self.sync_channel_if_configured(after)

    async def sync_all_guilds(self) -> None:
        for guild in self.guilds:
            category = guild.get_channel(self.category_id)
            if isinstance(category, discord.CategoryChannel):
                await self.sync_category(category)
            else:
                logger.warning(
                    "Configured category %s was not found in guild %s",
                    self.category_id,
                    guild.name,
                )

    async def sync_channel_if_configured(
        self, channel: discord.abc.GuildChannel
    ) -> bool:
        if self.channel_category_id(channel) != self.category_id:
            return False

        async with self._sync_lock:
            return await self.sync_channel(channel)

    async def sync_category(self, category: discord.CategoryChannel) -> int:
        if category.id != self.category_id:
            return 0

        async with self._sync_lock:
            synced = 0
            for channel in list(category.channels):
                if await self.sync_channel(channel):
                    synced += 1
            return synced

    async def sync_channel(self, channel: discord.abc.GuildChannel) -> bool:
        if self.channel_category_id(channel) != self.category_id:
            return False
        if channel.permissions_synced:
            return False

        try:
            await channel.edit(
                sync_permissions=True,
                reason="Synchronize permissions with configured category",
            )
            logger.info("Synchronized permissions for #%s", channel.name)
            return True
        except discord.Forbidden:
            logger.error(
                "Missing Manage Channels permission for #%s in %s",
                channel.name,
                channel.guild.name,
            )
        except discord.HTTPException:
            logger.exception("Could not synchronize permissions for #%s", channel.name)
        return False


def main() -> None:
    token = os.getenv("DISCORD_TOKEN", "").strip()
    if not token:
        raise RuntimeError("DISCORD_TOKEN must be set in the environment or .env")

    bot = CategoryPermissionSyncBot(required_category_id())
    bot.run(token, log_handler=None)


if __name__ == "__main__":
    main()