Skip to content

Roles

A roles panel lets members give themselves roles. Each category of roles is a card of buttons, and a click adds the role or takes it away, under the rules of its category: one color at a time, at least one pronoun.

Deprecated, removed in 5.0.0

The roles pattern works through 4.x, and a panel class defined on it warns with a DeprecationWarning. A role panel changes the server rather than showing something, so it belongs in the bot: build one from a PersistentLayoutView whose buttons add or remove the role, with a DynamicPersistentButton to keep each button working after a restart.

Kael's roles show Red. Kael clicks Blue on the Color Roles card: the reply reads "Switched to Blue (removed Red)" and the roles now show Blue. Kael then clicks She/Her, the only pronoun role held, and the reply says at least one Pronoun Roles role must stay

import discord
from cascadeui import PersistentRolesLayoutView, RoleCategory


class ServerRoles(PersistentRolesLayoutView):
    title = "Server Roles"
    categories = [
        RoleCategory(
            name="Color Roles",
            roles={"Red": 101, "Blue": 102, "Green": 103, "Purple": 104},  # (1)!
            exclusive=True,  # (2)!
            color=discord.Color.red(),
        ),
        RoleCategory(
            name="Gaming Roles",
            icon="๐ŸŽฎ",
            roles={"Minecraft": 201, "Valorant": 202, "League": 203},
            color=discord.Color.dark_teal(),
        ),
        RoleCategory(
            name="Pronoun Roles",
            roles={"He/Him": 301, "She/Her": 302, "They/Them": 303, "Neopronoun": 304},
            exclusive=True,
            required=True,  # (3)!
            color=discord.Color.blurple(),
        ),
    ]


@bot.hybrid_command(description="Post the roles panel")
async def roles(ctx):
    view = ServerRoles(context=ctx, persistence_key=f"roles:{ctx.guild.id}")  # (4)!
    await view.send()
  1. Each button's label, and the id of the role it hands out.
  2. One role at a time: picking Blue takes Red away.
  3. At least one: the last pronoun role cannot be removed.
  4. One panel per server, which comes back after a restart (see A Panel That Survives a Restart).

The panel shows the title, then one card per category: its heading, a hint for its rules (โ—‰ for one at a time, โ—‰ * for exactly one), a divider, and a button per role. A click replies to the member alone, such as "Gave you Minecraft." or "Switched to Blue (removed Red).". The buttons do not show which roles a member holds: the panel is one message that everyone sees the same, and the reply says what changed.

A roles panel suits roles members choose for themselves: colors, pronouns, games, notification pings. The bot needs the Manage Roles permission, and its highest role must sit above every role the panel hands out. Otherwise Discord refuses the change and the member is told it failed.

Categories

RoleCategory describes one card:

Field Default What it does
name required The heading.
roles required {label: role_id} or (label, role_id) pairs, one button per role in that order, at most five: a card holds one row of buttons.
exclusive False At most one of the roles at a time.
required False At least one of the roles at all times.
color None The card's accent: a discord.Color or an int.
button_style None The buttons' style. None is grey (secondary). A link or premium style, which sends no click, raises ValueError.
icon None An emoji before the heading.
description None A line of text under the hint.
key None The part of the buttons' ids that names the category (see Button Ids).

The two flags make four kinds of category:

exclusive required A member holds
False False Any of the roles, or none.
True False One or none. Picking another swaps, and clicking the one held removes it.
False True Any number, but at least one. Removing the last is refused.
True True Exactly one. Picking another swaps, and clicking the one held is refused.

A swap adds the new role, then removes the old one, so when Discord refuses the new role the member keeps the old. A role may sit in two categories, and each applies its own rules to it.

A wrong field raises when the category is built, naming the category:

  • ValueError for an empty name or label, or one role id under two labels
  • TypeError for a role id that is not an int, a flag that is not a bool, or a description that is not text

A category of more than five roles raises ValueError when the panel class listing it is defined.

How a Click Works

Each role button carries its category and role in its id, such as roles:color_roles:102. A click finds both from the id, so the panel keeps nothing for each member.

A click reads the member's roles from the click and applies the category's rules to them. A member's clicks in one category take turns: a click that had to wait reads the member's roles from Discord first, so a quick Red then Blue on the colors ends with Blue alone. A second click on the same role while the first is still being applied is dropped, so a double-click changes the role once. Clicks by other members, and in other categories, do not wait.

The reply goes to the member alone. A click that cannot change anything says why: "Role panels only work in a server." in a direct message, and role_error_message when the role is gone from the server, when the category no longer lists it (a button left from an older post), or when Discord refuses the change. A button whose category no longer exists at all answers "This role panel is out of date. An admin needs to re-post it."

Text and Replies

Attribute Default What it does
title "Server Roles" The heading above the cards. None shows none.
subtitle None A line under the title, shown as written: "-# Pick what fits" shows as small text.
hint_normal None The hint on a category with neither flag.
hint_exclusive "โ—‰" The hint on an exclusive category.
hint_required "*" The hint on a required category.
hint_exclusive_required "โ—‰ *" The hint on a category with both.

A hint is a line of text under the heading, any string or emoji, and None leaves it out. title, subtitle, and the hints take a str or None, and anything else raises TypeError when the class is defined.

The replies are templates, filled with str.format:

Attribute Default Sent
assigned_message "Gave you **{role}**." After a role is added.
removed_message "Removed **{role}**." After a role is removed.
swap_message "Switched to **{role}** (removed {removed})." After a swap. {removed} lists the roles taken away, in bold.
required_message "You must keep at least one **{category}** role." When removing the last role of a required category.
role_error_message "Could not update roles: {error}" When the change fails.

{role} and {category} work in the first four, and {error} in the last. A template is checked when the class is defined: a misspelled placeholder ({roel}) or an unbalanced brace raises ValueError naming the attribute and the placeholders it takes.

class CustomRoles(PersistentRolesLayoutView):
    categories = [...]

    title = "๐ŸŽจ Pick Your Roles"
    subtitle = "-# Click a button to add or remove the role."
    hint_exclusive = "๐ŸŽฏ pick one"
    hint_required = "โš ๏ธ required"
    assigned_message = "โœ… Added **{role}**."
    removed_message = "โž– Removed **{role}**."

A role click has no panel instance to read, so the hints, the five *_message templates, and categories are read from the class: set them in the class body, where set_class_attribute() refuses them. title and subtitle can be set on one panel.

The Card

A Color Roles card with each part labeled by what draws it: the accent color from color, the heading from format_category_title, the hint from format_category_hint, the description line, the divider, and the buttons, whose label, emoji, and style come from format_button_label, format_button_emoji, and format_button_style

Five hooks draw a card's parts, so an override replaces only the part it changes:

Hook Draws Default
format_category_title(category) The heading. ### name, with the icon before the name when set.
format_category_hint(category) The hint. The hint_* attribute for the category's flags. None leaves it out.
format_button_label(role_name, role_id, category) A button's label. The role's label.
format_button_emoji(role_name, role_id, category) A button's emoji. None.
format_button_style(role_name, role_id, category) A button's style. The category's button_style, else grey.

build_category_card(category) puts the parts together into one card. Override it for a card of another shape.

class ColorRoles(PersistentRolesLayoutView):
    categories = [...]

    @classmethod
    def format_button_emoji(cls, role_name, role_id, category):
        return {"Red": "๐ŸŸฅ", "Blue": "๐ŸŸฆ", "Green": "๐ŸŸฉ"}.get(role_name)

The hooks are classmethods, since the card is built on the class. Written as a plain method, one raises TypeError when the class is defined, while the class keeps the default build_category_card(). They run as the panel is built, so they are plain defs: an async def one is refused when the class is defined.

A label of "" or None with an emoji shows the emoji alone, for a row of icons. A button with neither raises ValueError when its card is built, naming the role and category.

A message holds 40 components. The title and subtitle take one each, and a card of five roles nine (the card, its heading, its divider, its button row, and five buttons), plus one for a hint and one for a description. Four such cards fit beside the title. A panel that does not fit raises ValueError when it is built, naming the category that does not fit, so split the categories between two panel classes.

After a Click

Five hooks send the replies, and an override can do more: log the change, post to another channel, reply with an embed.

Hook Runs
on_role_assigned(interaction, member, role, category) After a role is added.
on_role_removed(interaction, member, role, category) After a role is removed.
on_role_swap(interaction, member, role_added, roles_removed, category) After a swap.
on_role_required_block(interaction, member, role, category) When removing the last role of a required category is refused.
on_role_error(interaction, error) When the change cannot be made. error is a Discord or connection error, or a message.
from cascadeui import PersistentRolesLayoutView


class AuditedRoles(PersistentRolesLayoutView):
    categories = [...]

    @classmethod
    async def on_role_assigned(cls, interaction, member, role, category):
        await super().on_role_assigned(interaction, member, role, category)
        audit = interaction.guild.get_channel(AUDIT_CHANNEL_ID)
        if audit:
            await audit.send(f"{member} took {role.name}")

These hooks are classmethods too: a click reaches the button, not a panel, so they read cls and answer the interaction directly. Written as a plain method, one raises TypeError when the class is defined. Each may be a plain def or async def. A reply of your own goes through respond_safe(interaction, ...) (from cascadeui import respond_safe), which sends a followup when the click was already acknowledged.

on_role_error hears only a change that could not be made. An error raised by another hook, after the role changed, propagates instead, so the member is not told a change failed that went through.

A click runs the hooks and replies of the class of the live panel it came from, so a subclass's overrides answer its own panel. With no live panel on the message, the class that declares the category answers.

Button Ids and Renames

The category name Color Roles becomes the slug color_roles, which becomes the middle of the button id roles:color_roles:102. Renamed to Colours, the slug and the id change and the posted buttons stop matching. With key="colors", the id stays roles:colors:102 under either name

A button's id is roles:{slug}:{role_id}. The slug is the category's key when it has one, and otherwise made from its name: ASCII letters lowercased and digits kept, every other run of characters turned into _, the ends trimmed, so "Color Roles" gives color_roles and "Games!" gives games. A name with no ASCII letter or digit (Cyrillic, CJK, an emoji alone) takes a slug made from a digest of the name, the same in every process.

Slugs must be unique across every roles panel in the process, and within one panel. Names that give the same slug ("Colors" and "colors", or "Cafรฉ" and "Cafรจ", both caf) raise ValueError when the class is defined, not when a member clicks. Give each a key, or tell the names apart ("ServerA Colors", "ServerB Colors").

Renaming a category without a key changes its buttons' ids. A persistent panel restored after the restart is drawn again with the new ids. Any other panel already posted answers that it is out of date until it is posted again. A key keeps the ids when the name changes, and lets two names that give the same slug share a panel:

RoleCategory(name="Colours", key="colors", roles={"Red": 111})

A key holds lowercase letters, digits, _, and -. A category whose button ids would run past Discord's 100 characters raises ValueError when it is built, naming how long a key may be.

A Panel That Survives a Restart

PersistentRolesLayoutView is a panel posted once and kept. It takes a persistence_key= and differs from RolesLayoutView in two defaults:

Attribute RolesLayoutView PersistentRolesLayoutView
exit_policy "delete" "disable": closing it leaves it on screen, disabled.
timeout 180 seconds None: it never times out.

Both let everyone click (owner_only = False). A RolesLayoutView times out 180 seconds after its last click or edit, and its buttons are disabled.

For the panel to work after a restart, install PersistenceMiddleware(bot=...) (see Panels That Survive Restarts). Its restore registers the role buttons with the bot, so their clicks route again, and draws each panel again from the current categories: a new role or a new label shows without posting the panel again. Each restore costs one edit per panel.