Adding Shared State¶
On Your First Panel the count lives on the view: only that panel can read it, and a new counter starts again at 0. This page moves the count into CascadeUI's store, kept for each person. Every counter a person opens then shows their count, in any server, and a second panel can show it too.
Move the Count Into the Store¶
Start from the counter you built. The count leaves __init__ and moves into the store:
import discord
from cascadeui import StatefulButton, StatefulLayoutView, StateStore, card
class CounterView(StatefulLayoutView):
instance_limit = 1
state_scope = "user" # (1)!
subscribed_actions = {"SCOPED_UPDATE"} # (2)!
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_ui()
def build_ui(self):
count = self.scoped_state.get("count", 0) # (3)!
self.clear_items()
self.add_item(card(f"Count: **{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):
await self.dispatch_scoped(lambda current: {"count": current.get("count", 0) + 1}) # (4)!
- Keeps one entry for each person, under the key
user:<user id>. A person's counters in every server share it. Choosing a Scope lists the other scopes. - A write through
dispatch_scoped()is aSCOPED_UPDATEaction. A view hears only the action types it lists, and the list starts empty: without this line the count is stored, but the panel never redraws. scoped_statecomes with every view: the person's entry,{}until their first click.- The function receives the entry as the store holds it when the write runs, and returns the keys to change. Values Computed From the Current One shows why a count is written this way.
The callback no longer redraws the panel. The store takes the write and tells every view that listens, and a
view's default on_state_changed() calls build_ui() and then refresh(). That refresh answers the click, in one
request, as before.
How CascadeUI Thinks follows one click through each of those steps.
Redraw Only When the Count Changes¶
Every person's write is a SCOPED_UPDATE, so as it stands, each click by anyone rebuilds every open counter. A
rebuilt panel that matches the screen sends no edit, but each one still runs build_ui(). A selector tells the
store what the panel shows:
class CounterView(StatefulLayoutView):
# ... instance_limit, state_scope, and subscribed_actions, as above
def state_selector(self, state): # (1)!
return StateStore.get_scoped_from(state, "user", user_id=self.user_id).get("count", 0)
StateStore.get_scoped_from()reads an entry from the state it is given: here, the state the store hands the selector.
After each action the counter hears, the store calls state_selector() and compares the result with the last
one. When the two match, the panel is left alone, and when the count changed, it redraws. The first action a panel
hears after it is sent redraws it whatever the selector returns, and that redraw matches the screen, so no edit
goes out. Selectors has the rules.
Show the Count on a Second Panel¶
Any view with state_scope = "user" reads the same entry. A badge that shows the count and has nothing to click:
class ScoreView(StatefulLayoutView):
instance_limit = 1
timeout = None # (1)!
state_scope = "user"
subscribed_actions = {"SCOPED_UPDATE"}
def state_selector(self, state):
return StateStore.get_scoped_from(state, "user", user_id=self.user_id).get("count", 0)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_ui()
def build_ui(self):
count = self.scoped_state.get("count", 0)
self.clear_items()
self.add_item(card(f"Score: **{count}**"))
@bot.tree.command(description="Show your score")
async def score(interaction: discord.Interaction):
await ScoreView(interaction=interaction).send()
- A view closes once its
timeoutpasses with no click, and each redraw starts the wait again. A badge has nothing to click, so with the default 180 seconds it would close three minutes after it was sent or last redrawn, and stop following the count with nothing on screen to show it.Nonekeeps it open until the bot stops, andinstance_limit = 1keeps one badge per person in each server.
Kael clicks +1 on the counter. The store writes Kael's entry, the counter answers the click with the new count, and Kael's badge in another server redraws to match. Mira's badge reads Mira's own entry: that count did not change, so the badge is left alone.
Try It¶
- Run the file below. Type
/counterin your server, then/scorein the same server or another one. - Click +1. The counter and the badge both show the new count.
- Ask someone else to type
/score. Their badge shows their own count, 0, and stays at 0 while you click. - Type
/counteragain. The new counter replaces the old one and shows your count, not 0. - Restart the bot and type
/counter. The count is back at 0: the store lives in the bot's memory.
Keep the Count Across a Restart¶
To keep the count, save the slot it lives in: set up persistence in setup_hook with PersistenceMiddleware, and
add persistent_slots = ("scoped",) to CounterView. Saving Across a Restart
shows both lines, and Persistence covers the setup and where the data is kept.
The Whole File¶
import discord
from discord.ext import commands
from cascadeui import StatefulButton, StatefulLayoutView, StateStore, card
bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
class CounterView(StatefulLayoutView):
instance_limit = 1
state_scope = "user"
subscribed_actions = {"SCOPED_UPDATE"}
def state_selector(self, state):
return StateStore.get_scoped_from(state, "user", user_id=self.user_id).get("count", 0)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_ui()
def build_ui(self):
count = self.scoped_state.get("count", 0)
self.clear_items()
self.add_item(card(f"Count: **{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):
await self.dispatch_scoped(lambda current: {"count": current.get("count", 0) + 1})
class ScoreView(StatefulLayoutView):
instance_limit = 1
timeout = None
state_scope = "user"
subscribed_actions = {"SCOPED_UPDATE"}
def state_selector(self, state):
return StateStore.get_scoped_from(state, "user", user_id=self.user_id).get("count", 0)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.build_ui()
def build_ui(self):
count = self.scoped_state.get("count", 0)
self.clear_items()
self.add_item(card(f"Score: **{count}**"))
@bot.tree.command(description="Open a counter")
async def counter(interaction: discord.Interaction):
await CounterView(interaction=interaction).send()
@bot.tree.command(description="Show your score")
async def score(interaction: discord.Interaction):
await ScoreView(interaction=interaction).send()
@bot.event
async def setup_hook():
await bot.tree.sync() # registers /counter and /score with Discord
bot.run("YOUR_BOT_TOKEN")
Next¶
How CascadeUI Thinks follows a click from the callback to the edit and maps the store's state tree. Scoped State covers the other scopes and reading another person's entry, and Subscribers and Slots covers views that listen for actions of your own.