Skip to content

Scoped State

Scoped state keeps data for each person, each server, each person in a server, or the whole bot, with no reducer of your own: set state_scope on the view, read self.scoped_state, and write with dispatch_scoped(). This page covers reading and writing it, keeping other panels in step, and saving it across a restart.

Diagram: the scoped slot holds one entry per key. Kael's settings panel, with state_scope "user", reads user:100, Kael's own entry. Kael's and Mira's server counters, with state_scope "guild", both read guild:22, the one entry for server 22. Kael's profile, with state_scope "user_guild", reads user_guild:100:22, and a notice for everyone, with state_scope "global", reads global.

A Counter With No Reducer

The counter on Store, Actions, and Reducers writes its own reducer. Scoped state does the same with the one the library has:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, StateStore, card


class CounterView(StatefulLayoutView):
    state_scope = "guild"  # (1)!
    subscribed_actions = {"SCOPED_UPDATE"}  # (2)!

    def state_selector(self, state):
        return StateStore.get_scoped_from(state, "guild", guild_id=self.guild_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)  # (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)!
  1. One entry per server, under the key guild:<server id>.
  2. Every scoped write is a SCOPED_UPDATE. The selector keeps this view to its own server's count.
  3. The view's own entry: {} until the first write.
  4. The function gets the entry as it stands when the write runs, so two clicks at once both count (see Values Computed From the Current One).

Kael clicks +1 in server 22. The count there becomes 1, and every counter open in server 22 redraws: Kael's, and Mira's beside it. A counter in server 33 keeps its own count.

Choosing a Scope

state_scope Key One entry for
"user" user:<user id> each person, in every server
"guild" guild:<server id> each server
"user_guild" user_guild:<user id>:<server id> each person in each server
"global" global the whole bot
None (default) nothing: dispatch_scoped() needs scope=

The ids come from the view: user_id is the person who opened it and guild_id the server it opened in. A view opened in a direct message has no server, so a "guild" or "user_guild" view there reads {}, and a write raises ValueError naming the missing id.

state_scope and instance_scope

The two take the same values but answer different questions. state_scope decides whose data a view reads and writes. instance_scope decides how many panels can be open at once, and for whom.

Reading

self.scoped_state is the view's own entry. Four methods read another scope's entry, by default for the view's own person and server:

settings = self.user_scoped_state()               # this person, every server
server = self.guild_scoped_state()                 # this server
profile = self.user_guild_scoped_state()           # this person in this server
notice = self.global_scoped_state()                # the whole bot

rival = self.user_scoped_state(user_id=member)     # someone else's entry

scoped_state_for("user", user_id=...) does the same with the scope named as text. Ids may be an int, a string of digits, or a Member or Guild. Anything else, a name or True, raises TypeError.

An entry that does not exist yet reads as an empty dict, and so does a scope whose id the view lacks. Reading never raises for a missing entry.

Read the entry, then write through dispatch_scoped()

A read returns the entry the store holds, not a copy. self.scoped_state["count"] = 99 changes the store with no action: no other panel redraws, undo cannot put it back, and a saved slot keeps the old value until the next write. The same assignment to an entry that does not exist yet goes nowhere.

Writing

dispatch_scoped(data) merges data into the view's entry. The merge is one level deep: a key in data replaces the key in the entry, and keys data leaves out stay.

await self.dispatch_scoped({"name": "Kael", "prefs": {"theme": "dark", "lang": "en"}})
await self.dispatch_scoped({"prefs": {"theme": "light"}})
# The entry is now {"name": "Kael", "prefs": {"theme": "light"}}: the whole "prefs" dict was replaced.

Two keyword arguments change where the write goes:

  • scope= writes to another scope than the view's state_scope. A view with state_scope = None writes this way.
  • user_id= or guild_id= writes to someone else's entry: a game that records both players' wins writes the loser's with user_id=loser.

data must be a dict or a function (below). Anything else raises TypeError at the call, and so do an id that is no Discord id and a scope that is not a str. No scope at all, an unknown one, or a missing id raises ValueError.

Values Computed From the Current One

A value worked out from the current one, a count plus one or a total so far, is written as a function of the current entry. The function runs inside the store's reducer, after every write before it:

await self.dispatch_scoped(lambda current: {"count": current.get("count", 0) + 1})

Reading first and writing after loses clicks. Two panels that each read the count, wait on something, and write the count plus one both read 0 and both write 1:

Animation: Kael and Mira click +1 on the server counter at the same moment. On the left, each click reads the count, 0, waits on a lookup, and writes 0 + 1: Kael's write and then Mira's both write 1, and one click is lost. On the right, each click waits on the same lookup and sends a function, and the store runs Kael's on 0 and writes 1, then Mira's on 1 and writes 2, so both clicks count.

The function gets a copy of the entry, so changing it in place changes nothing, and returns a dict of the keys to change. It must be a plain function of one argument: an async def or a function that takes no argument raises TypeError when dispatch_scoped() is called. What the function raises comes out of the dispatch_scoped() await as itself, a KeyError from current["n"] on an entry with no "n" included, and a function that returns something other than a dict raises TypeError there. Either way nothing is written and no one is told of a change.

One panel alone never loses a click this way, since a view's clicks run one at a time.

Keeping Other Panels in Step

A scoped write redraws only the panels that hear it. Like every action, it reaches a view only when the view lists its type in subscribed_actions (see What a View Hears).

Animation: Kael and Mira each have the server 22 counter open, and both list SCOPED_UPDATE, while Ren's counter in the same server lists nothing. Every counter shows 0. Kael clicks +1, and dispatch_scoped() writes guild:22, count 1. Kael's and Mira's selectors return 1, was 0, so both panels redraw to show 1. Ren's panel is not told and still shows 0.

There are two ways to listen:

  • List SCOPED_UPDATE, as the counter above does, with a state_selector() that returns the view's own entry. Every scoped write in the bot then runs the selector of every such panel, 4 to 6 microseconds a panel: 4 to 6 milliseconds a write with 1,000 panels open.
  • Name the action with dispatch_scoped_as(), and write a reducer for it. Only the panels that list that name hear it:
from cascadeui import StatefulLayoutView, StateStore, cascade_reducer


@cascade_reducer("SETTINGS_UPDATED")
def settings_updated(action, state):
    payload = action["payload"]
    return StateStore.merge_scoped(
        state, payload["scope"], payload["data"], subkey="settings", **payload["identifiers"]
    )


class SettingsView(StatefulLayoutView):
    state_scope = "user"
    subscribed_actions = {"SETTINGS_UPDATED"}

    def state_selector(self, state):
        return StateStore.get_scoped_from(state, "user", user_id=self.user_id).get("settings")

    async def set_theme(self, interaction, values):
        await self.dispatch_scoped_as("SETTINGS_UPDATED", {"theme": values[0]})

dispatch_scoped_as() builds the same payload dispatch_scoped() does, {"scope", "identifiers", "data", "slot_name"}, and merge_scoped() reads it back. subkey="settings" merges into entry["settings"], so two reducers can each keep a part of one person's entry. The settings examples (v2_settings.py) keep a person's settings this way.

In Reducers and Selectors

A reducer and a selector are both handed the state, and read it from there rather than from the store:

Helper Where What it does
StateStore.get_scoped_from(state, scope, **ids) Selectors, reducers Reads an entry from the state it is handed, {} when missing
StateStore.merge_scoped(state, scope, data, **ids) Reducers Merges data, or a function's result, into an entry and returns state
StateStore.iter_scoped(state, scope, **filters) Selectors, reducers Yields (ids, entry) for every entry of a scope
StateStore.scope_key(scope, user_id=, guild_id=) Anywhere Builds an entry's key, or None when an id is missing
store.get_scoped(scope, **ids) Code outside a view Reads an entry from the store's current state

merge_scoped() raises what get_scoped() raises: ValueError for an unknown scope or a missing id, so a typo in a reducer is logged by the store at ERROR, naming the action, rather than writing nothing.

iter_scoped() walks every entry of one scope, for a leaderboard or a cleanup. A filter narrows it: iter_scoped(state, "user_guild", guild_id=22) yields every person's entry in server 22. Only the ids the scope's key holds can filter it. Any other raises TypeError, as an unknown scope raises ValueError, when iter_scoped() is called.

A Slot of Its Own

Scoped entries live in one slot, state["application"]["scoped"], shared by every view. A view can keep its own in a slot of its own with scoped_slot:

class BattleshipView(StatefulLayoutView):
    state_scope = "user_guild"
    scoped_slot = "battleship_stats"
    persistent_slots = ("battleship_stats",)

Its reads, its writes, and dispatch_scoped_as()'s payload then use state["application"]["battleship_stats"]. Code outside the view names it with slot_name=: store.get_scoped(..., slot_name="battleship_stats").

A view that sets scoped_slot and lists "scoped" in persistent_slots raises ValueError when its class is defined, since its writes would go to the other slot and never be saved.

Undo

A view with enable_undo = True can undo its scoped writes (see Undo and Redo). An undo puts back only the keys its step changed, so it leaves everyone else's entries alone, though they share one slot:

Diagram: the scoped slot holds Kael's entry, count 2, and Mira's, count 5. Kael's undo puts back the key its step changed: Kael's entry returns to count 1, and Mira's stays at 5.

Saving Across a Restart

Scoped data is kept in memory until its slot is saved. With persistence set up, mark the slot in either of two places:

class SettingsView(StatefulLayoutView):
    state_scope = "user"
    persistent_slots = ("scoped",)  # or the view's scoped_slot

or SlotPolicy(persistent=True) for the slot in the persistence setup (see Saving Data). Marking "scoped" saves every view's scoped entries, since they share the slot. Entry keys are text already, so they come back as they went.

Writing without an action: set_scoped()

store.set_scoped(scope, data, **ids) replaces an entry outright, outside any action, for seeding data at startup. It takes a dict and keeps a copy of it. No panel hears the write and undo does not record it, but a saved slot is saved as it is after any other write.