Skip to content

Your First Panel

Build a counter: a panel with a number and a button that adds one to it. It takes about thirty lines, and every view you write later has the same shape.

A counter panel whose count goes up from 0 to 3 as its +1 button is clicked

Before You Start

You need:

  • Python 3.10 or newer, with discord.py 2.7 or newer
  • CascadeUI, installed with pip install pycascadeui (Installation lists the optional extras)
  • A bot token, and a server where you can test the bot

Draw the Panel

A view is the Python object behind a panel. Subclass StatefulLayoutView, the view class for Discord's component layout, where the message is made entirely of components:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card


class CounterView(StatefulLayoutView):
    instance_limit = 1  # (1)!

    def __init__(self, **kwargs):
        super().__init__(**kwargs)  # (2)!
        self.count = 0
        self.build_ui()  # (3)!

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"Count: **{self.count}**"))
        self.add_item(
            discord.ui.ActionRow(
                StatefulButton(
                    label="+1",
                    style=discord.ButtonStyle.primary,
                    callback=self.increment,
                    allow_double_click=True,  # (4)!
                )
            )
        )
  1. One counter per person in each server. What CascadeUI Did for You explains what happens to the old one.
  2. Pass the keywords on: they carry the command that opened the panel.
  3. Draws the first panel. Without this line, send() would call build_ui() itself, since the view has nothing to show yet.
  4. Counts every click, even two sent in quick succession. Without it, a person's second click on the button is dropped when it arrives before the first click has shown them anything (here, the new count). See Double Clicks.

build_ui() draws the panel from the view's data. It removes the old components and adds new ones, so you can call it again whenever the data changes:

  • card() makes a box of text. The text takes Discord's markdown.
  • StatefulButton is a button that runs the method you pass as callback.
  • Buttons sit in an ActionRow, as they do in discord.py.

Make the Button Count

Add the callback to the class:

class CounterView(StatefulLayoutView):
    # ... instance_limit, __init__, and build_ui, as above

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        self.build_ui()
        await self.refresh()

The callback receives the click's interaction. It changes the data, redraws the panel, and calls refresh(), which sends the new panel to Discord.

There is no interaction.response call. Discord expects an answer to every click within 3 seconds, and refresh() is that answer: it edits the message and answers the click in one request. Responding to Clicks covers callbacks that need to say something.

Send It From a Command

Build the view with the command's interaction or ctx, so it knows who opened it and where to reply, then call send():

@bot.tree.command(description="Open a counter")
async def counter(interaction: discord.Interaction):
    await CounterView(interaction=interaction).send()
from discord.ext import commands


@bot.hybrid_command(description="Open a counter")
async def counter(ctx: commands.Context):
    await CounterView(context=ctx).send()

Typed as !counter, a prefix command needs the message content intent: set intents.message_content = True and switch the intent on in the Discord Developer Portal.

The Whole File

import discord
from discord.ext import commands

from cascadeui import StatefulButton, StatefulLayoutView, card

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())


class CounterView(StatefulLayoutView):
    instance_limit = 1

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.count = 0
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"Count: **{self.count}**"))
        self.add_item(
            discord.ui.ActionRow(
                StatefulButton(
                    label="+1",
                    style=discord.ButtonStyle.primary,
                    callback=self.increment,
                    allow_double_click=True,
                )
            )
        )

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        self.build_ui()
        await self.refresh()


@bot.tree.command(description="Open a counter")
async def counter(interaction: discord.Interaction):
    await CounterView(interaction=interaction).send()


@bot.event
async def setup_hook():
    await bot.tree.sync()  # registers /counter with Discord


bot.run("YOUR_BOT_TOKEN")

Try It

  1. Run the file and type /counter in your server. The panel appears with a count of 0:

    The counter as /counter sends it, with a count of 0

  2. Click +1. The count goes up by one.

  3. Ask someone else to click. They see "You cannot interact with this.", and the count stays where it was:

    The reply only the other person sees: You cannot interact with this.

  4. Type /counter again. The first panel's message is deleted and a new counter starts at 0.

  5. Leave the panel alone for three minutes. Its button turns grey and stops responding:

    The counter after three minutes without a click, its button disabled

What CascadeUI Did for You

Each step above ran behavior you did not write:

  • Every click was answered in time. refresh() answered the clicks, and a callback too slow for that would have had its click acknowledged before the 3 seconds ran out. See Responding to Clicks.
  • Only you could click. A view takes clicks only from the person who opened it, unless you change owner_only or set allowed_users. See Who Can Click.
  • You kept one counter. instance_limit = 1 allows one live counter per person in each server. A new one replaces the old one and deletes its message. See How Many Can Exist.
  • The idle panel closed. After 180 seconds without a click (discord.py's default timeout), the view closed and left its button disabled, so the message no longer offers a click that would do nothing. See Timeout.

Next

Adding Shared State moves the count into CascadeUI's store, where other panels can read it. If you have built views with discord.py before, Coming from discord.py maps what you know onto CascadeUI.