import discord from discord import app_commands from discord.ext import commands import config import data CATEGORY_CHOICES = [app_commands.Choice(name="All panels", value="all")] + [ app_commands.Choice(name=c["title"], value=c["key"]) for c in data.CATEGORIES ] def make_groups(cat): """Split a category into dropdown groups of at most 25 roles each.""" names = cat["roles"] if len(names) <= 25: return [(cat["key"], names, cat["placeholder"])] chunks = [names[i : i + 25] for i in range(0, len(names), 25)] return [ (f"{cat['key']}:{i}", chunk, f"{cat['placeholder']}: {chunk[0]} to {chunk[-1]}") for i, chunk in enumerate(chunks) ] class GroupSelect(discord.ui.Select): def __init__(self, key, role_names, placeholder, multi, required): super().__init__( custom_id=f"roles:{key}", placeholder=placeholder, min_values=1 if required else 0, max_values=len(role_names) if multi else 1, options=[discord.SelectOption(label=n, value=n) for n in role_names], ) self.role_names = role_names async def callback(self, interaction: discord.Interaction): await interaction.response.defer() member = interaction.user by_name = {r.name: r for r in interaction.guild.roles} missing = [n for n in self.role_names if n not in by_name] if missing: await interaction.followup.send( "Some roles don't exist yet. An admin needs to run /setup_roles.", ephemeral=True, ) return chosen = set(self.values) current = {r.name for r in member.roles} to_add = [by_name[n] for n in chosen if n not in current] to_remove = [ by_name[n] for n in self.role_names if n not in chosen and n in current ] try: if to_add: await member.add_roles(*to_add, reason="Self-assigned via panel") if to_remove: await member.remove_roles(*to_remove, reason="Self-assigned via panel") except discord.Forbidden: await interaction.followup.send( "I couldn't change your roles. An admin needs to move my role " "above these roles in Server Settings -> Roles.", ephemeral=True, ) def build_view(cat): view = discord.ui.View(timeout=None) for key, names, placeholder in make_groups(cat): view.add_item( GroupSelect(key, names, placeholder, cat["multi"], cat["required"]) ) return view class Roles(commands.Cog): def __init__(self, bot): self.bot = bot async def cog_load(self): for cat in data.CATEGORIES: self.bot.add_view(build_view(cat)) @app_commands.command( name="setup_roles", description="Create any roles that don't exist yet" ) @app_commands.guilds(config.GUILD) @app_commands.default_permissions(manage_roles=True) @app_commands.guild_only() async def setup_roles(self, interaction: discord.Interaction): await interaction.response.defer(ephemeral=True) guild = interaction.guild existing = {r.name for r in guild.roles} created = [] try: for cat in data.CATEGORIES: for name in cat["roles"]: if name in existing: continue kwargs = {} if cat["color"] is not None: kwargs["colour"] = discord.Colour(cat["color"]) await guild.create_role( name=name, reason="Alabama Progress setup", **kwargs ) existing.add(name) created.append(name) except discord.Forbidden: await interaction.followup.send( "I'm missing the Manage Roles permission.", ephemeral=True ) return if created: msg = f"Created {len(created)} roles: " + ", ".join(created) else: msg = "All roles already exist. Nothing to do." await interaction.followup.send(msg[:1900], ephemeral=True) @app_commands.command( name="post_panels", description="Post the role dropdown panels in this channel" ) @app_commands.guilds(config.GUILD) @app_commands.describe(category="Which panel to post (default: all)") @app_commands.choices(category=CATEGORY_CHOICES) @app_commands.default_permissions(manage_roles=True) @app_commands.guild_only() async def post_panels( self, interaction: discord.Interaction, category: str = "all" ): await interaction.response.defer(ephemeral=True) existing = {r.name for r in interaction.guild.roles} cats = [c for c in data.CATEGORIES if category in ("all", c["key"])] missing = [n for c in cats for n in c["roles"] if n not in existing] if missing: await interaction.followup.send( f"{len(missing)} roles don't exist yet. Run /setup_roles first.", ephemeral=True, ) return for cat in cats: await interaction.channel.send(content=cat["text"], view=build_view(cat)) await interaction.followup.send(f"Posted {len(cats)} panel(s).", ephemeral=True) async def setup(bot): await bot.add_cog(Roles(bot))