How Many Can Exist¶
A view class can limit how many of itself are open at once: one settings panel per person, one leaderboard per server. This page covers the limit, what happens to the older panel or the new one when the limit is reached, and how players count toward it.
Limiting Open Panels¶
from cascadeui import StatefulLayoutView
class SettingsView(StatefulLayoutView):
instance_limit = 1 # (1)!
- One per person in each server. Opening a second closes the first and deletes its message.
A view counts from its send() until it closes, through exit(), a timeout, or the deletion of its message.
Without a limit, a bot keeps its own record of who has a panel open and has to clear it on every close. The
library keeps that record. Three class attributes decide the rest:
instance_limit: how many may be open at once.None, the default, sets no limit.instance_scope: who the count is for.instance_policy: what happens at the limit."replace", the default, closes an older panel, and"reject"refuses the new one.
Each class counts its own panels, so a subclass counts apart from the class it extends. A screen reached by
push() counts as the panel it was pushed from (see Screens Reached by push()).
Who the Count Is For¶
instance_scope |
One count per | For example |
|---|---|---|
"user_guild" (default) |
person, in each server | a settings panel per person in each server |
"user" |
person, in every server | a profile panel per person anywhere |
"guild" |
server | one shared scoreboard per server |
"global" |
the whole bot | one status board |
A DM has no server. Under "user_guild", a person's DMs count as one more place, so they get one panel there as
they do in each server. "guild" has nothing to count in a DM, so its limit does not apply there and the library
logs a warning once for the class. A command whose panel only makes sense in a server takes
@commands.guild_only(), which also keeps its slash command out of DMs.
When the Limit Is Reached¶
"replace" closes the person's oldest panels to make room, then sends the new one. replace_policy sets
what the old message becomes:
"delete"(default) deletes it."disable"leaves it in place, closed: a V2 panel keeps its content with its controls disabled, and a V1 panel keeps its embed and loses its buttons.
Replace closes only panels the same person owns. When the count is full of panels someone else owns, as under
"guild" or "global", or of games the person is playing in, the new send is refused, as under "reject".
"reject" refuses the new panel. Nothing is posted, send() returns None, and the person who ran the
command is told, in a reply only they see:
| Scope | instance_limit = 1 |
instance_limit = 3 |
|---|---|---|
| per person | You already have one of these open. Close it first. | You can only have 3 of these open at once. |
"guild" |
One of these is already open in this server. | This server can only have 3 of these open at once. |
"global" |
One of these is already open. | Only 3 of these can be open at once. |
Panels With Players¶
Replace leaves a panel alone while it holds someone else: a participant, or an attached child view another person owns. The new send is refused instead, so a host who starts a second game does not end the one their opponent is still playing. Child views the person owns themselves do not count.
protect_attached = False lets replace close such a panel, and replaced_message tells its players, in the old
panel's channel, before it closes:
class GameView(StatefulLayoutView):
instance_limit = 1
protect_attached = False
replaced_message = "This game was cancelled: the host started a new one." # (1)!
- Posted only when the old game has participants.
None, the default, posts nothing.
For a notice of your own, override on_replaced(). It runs on the old view while it is still whole, before it
closes:
class GameView(StatefulLayoutView):
instance_limit = 1
protect_attached = False
async def on_replaced(self):
if self.participants and self.message:
players = " ".join(f"<@{uid}>" for uid in sorted(self.participants))
await self.message.channel.send(f"{players} the host started a new game.")
An on_replaced() that raises is logged, and the new panel is sent anyway. One that requires arguments is
refused when its class is defined, since the library calls it with none.
Changing the Refusal¶
instance_limit_message replaces the words. on_instance_limit() replaces the reply:
class ReportView(StatefulLayoutView):
instance_limit = 1
instance_policy = "reject"
async def on_instance_limit(self, error):
await self.respond(
self.interaction,
f"You can run {error.limit} report at a time. Close the open one first.",
ephemeral=True,
)
on_instance_limit() also runs when register_participant() refuses a player who is
already in another panel of the class. When that player is not the person the reply goes to, as when a send with
auto_register_participants = True checks each listed player on the sender's interaction, the default reply names
the player (@Bea is already taking part in one of these.), with mentions off. It receives an InstanceLimitError:
| Attribute | Type | Meaning |
|---|---|---|
view_type |
str |
The refused view's class name |
limit |
int |
The instance_limit |
blocked_user_id |
int | None |
The player refused by register_participant(), or None for a refused send |
scope |
str | None |
The instance_scope the limit counted under, or None for a player |
default_message |
str |
The default reply, worded for the scope and the limit |
Checking Before Building the View¶
send() applies the limit. To find out before building a view whose __init__ is costly, such as one that
reads a database, ask the class:
import discord
from discord import app_commands
@app_commands.command()
async def game(self, interaction: discord.Interaction):
if not GameView.check_instance_available(
user_id=interaction.user.id,
guild_id=interaction.guild_id,
):
await interaction.response.send_message("You already have an active game.", ephemeral=True)
return
view = GameView(interaction=interaction)
await view.send()
It counts owners and participants, so a player in someone else's game counts against their own limit. It
returns True when the class sets no limit, or when an id the scope needs is missing.
Screens Reached by push()¶
A screen reached by push() counts as the panel its chain started from, with that panel's instance_scope and
instance_limit. A person who opens a settings hub and pushes two screens deep still has one panel open, and
opening the hub again replaces the screen they are on. A check on the hub's class covers the whole chain.
A pushed class checked on its own counts only the views of it that were sent directly, so it returns True for a
person already inside a chain. Pass the root's key as session_origin to count the way the library does for a
pushed view, for example before adding a player to a game the hub pushed:
HUB_KEY = f"{HubView.__module__}.{HubView.__qualname__}"
if not GameView.check_instance_available(
user_id=joiner.id,
guild_id=interaction.guild_id,
session_origin=HUB_KEY,
):
await interaction.response.send_message("You are already in a game.", ephemeral=True)
return
The check then counts under the hub's key and the hub's instance_scope, against HubView.instance_limit: the
same count register_participant() makes on the pushed game. A hub that sets session_class_key is keyed by that
value instead.
Less common cases
A panel sent to a channel. A view built with context=channel has no one to tell privately, so a refusal
raises InstanceLimitError from send() for the code that sent it to handle.
A persistent panel in the count. Replace never closes a persistent panel to make room for a view that is
not persistent. A persistent screen a regular hub pushed counts as the hub, so opening the hub again is
refused, as under "reject".
Which classes count together. A class is known by f"{cls.__module__}.{cls.__qualname__}", so two
classes that share a name in different modules count apart. That key also names the class's sessions and,
for a persistent panel, the class its stored row restores. A session_class_key class attribute sets the key
instead, without inheriting, and its real use is keeping a renamed or moved persistent class restorable. See
Keeping the Class Findable.
Related¶
- Who Can Click: participants, and who may use a panel.
- Navigation:
push(),pop(), andreplace(). - Errors:
InstanceLimitErrorin full. - Panels That Survive Restarts: the setup for a persistent panel.