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