Skip to content

API: Utilities

Helpers exported from the package root and from cascadeui.utils: error handling, background tasks, Discord ids, logging, and a few text and file tools. cascadeui.utils also exports three names documented beside the parts they serve: DISCORD_CALL_ERRORS, respond_safe(), and @cascade_reducer.

Error Handling

The two decorators take an async def or a plain def, and the function they return is always awaited.

@with_error_boundary(name=None)

Logs what the function raises, then raises it again for the caller to handle. The error goes to the cascadeui.utils.errors logger at ERROR, with its traceback, as Error in {name}: {error}. name defaults to the function's name.

from cascadeui import with_error_boundary

@with_error_boundary("sync_scores")
async def sync_scores(user_id):
    ...

Reach for it where an error would otherwise end in the event loop with no sign of where it came from. safe_execute() absorbs the error instead.

Raises TypeError when name is neither a str nor None (which also catches the decorator written without its parentheses), or when the decorator is applied to something that cannot be called.

@with_retry(config=None)

Calls the function again when it raises an error the RetryConfig names, waiting longer before each retry. config defaults to RetryConfig(): up to three retries, so four calls.

from cascadeui import RetryConfig, with_retry

@with_retry(RetryConfig(max_retries=5, backoff_factor=2.0, exceptions_to_retry=(ConnectionError,)))
async def fetch_profile(user_id):
    ...

Each failure before the last logs a WARNING, such as Attempt 1/6 failed for fetch_profile: ..., and waits. The last logs an ERROR and raises the function's own error, with no wait after it. An error outside exceptions_to_retry raises at once.

Raises TypeError when config is neither a RetryConfig nor None (which also catches the decorator written without its parentheses), or when the decorator is applied to something that cannot be called, a call it would otherwise retry though it can never work.

RetryConfig(max_retries=3, backoff_factor=1.0, exceptions_to_retry=(Exception,), max_backoff=30.0)

How with_retry retries.

  • max_retries (int): the calls after the first, so 3 makes up to four calls and 0 makes one
  • backoff_factor (seconds): the wait before retry n, counting from 0, is backoff_factor * 2**n, plus up to 10% more so that calls failing together do not all retry at once
  • exceptions_to_retry: an exception class, or a tuple or list of them, kept as a tuple. Any other error raises at once
  • max_backoff (seconds): the longest any one wait can be

Raises TypeError for:

  • a count that is not an int, or a wait that is not a number (a bool is neither)
  • an entry in exceptions_to_retry that is not an Exception subclass, since retrying CancelledError would swallow a cancel

Raises ValueError for:

  • a negative count
  • a negative, infinite, or NaN wait
  • an empty exceptions_to_retry

safe_execute(coro, fallback=None, log_error=True) (async)

Awaits coro and returns its result, or fallback when it raises an Exception. The error is logged at ERROR with its traceback unless log_error is False. A cancel is not caught.

from cascadeui import safe_execute

profile = await safe_execute(fetch_profile(user_id), fallback={})

coro is anything awaitable: a called coroutine, as above, a task, or a future. Raises TypeError for anything else, such as safe_execute(fetch_profile), a coroutine function passed without calling it.

Task Manager

A view's background tasks go through one manager. A view starts its own with view.create_task(coro), and the manager files them under the view's id: they are cancelled when the view exits, times out, or moves on with push() or pop(). A teardown called from one of the view's own tasks finishes first, and that task is cancelled once the call returns. Use the manager directly for work that belongs to no view.

get_task_manager()

Returns the process-wide TaskManager.

from cascadeui import get_task_manager

tasks = get_task_manager()
tasks.create_task("score_poller", poll_scores())
...
tasks.cancel_tasks("score_poller")

TaskManager

Tracks tasks under owner ids, which are any strings. A task that raises is logged at ERROR, with its traceback, on the cascadeui.tasks logger. A task leaves the manager when it finishes, whatever way it ends.

create_task(owner_id, coro) -> asyncio.Task

Starts coro as a task owned by owner_id and returns it. Under a loop with a task factory, such as asyncio.eager_task_factory, the body still starts only once the calling code has run, as it does without one.

cancel_tasks(owner_id) -> int

Cancels the owner's unfinished tasks and returns how many it cancelled. It returns without waiting for them to end.

wait_tasks(owner_id) (async)

Waits for the owner's tasks running when it is called. A task started meanwhile is not waited for, and an error a task raises is not raised here, since the manager has logged it.

get_task_count(owner_id=None) -> int

How many tasks the owner has running, or every owner's together when owner_id is None.

Snowflake Coercion

Wherever the library takes a Discord id, it takes an int or any object carrying an int .id (a Member, a Role), and reads the id where it is passed. These helpers are that reading, for code doing the same.

is_snowflake(value) -> bool

Whether value is an int that could be a Discord id: the creation time packed into its high bits lands between Discord's epoch (2015) and now. An id too large fails on the date it decodes to, and the small integers tests use read as False. So do a digit string, a bool, and any other type.

coerce_snowflake_id(value) -> int | None

Returns value when it is an int, value.id when that is an int, and None for None. Raises TypeError for anything else, a digit string and a bool included, so a wrong value fails where it is passed rather than in a state key later.

coerce_snowflake_id_set(values) -> set[int]

The same reading for each item of an iterable, returned as a set. None gives an empty set, and a None inside the iterable raises TypeError. The allowed_users setter applies it, which is why {ctx.author, opponent} works as well as {ctx.author.id, opponent.id}.

coerce_snowflake_match(match_dict, snowflake_keys) -> dict

Returns a copy of the groups a DynamicItem template matched, with the keys in snowflake_keys turned from strings into ints. Other keys, and None for an optional group, pass through unchanged. A value int() cannot read raises ValueError.

from cascadeui import coerce_snowflake_match

data = coerce_snowflake_match(match.groupdict(), frozenset({"user_id", "guild_id"}))

Logging

The library logs nothing until setup_logging() attaches handlers: the package root carries a NullHandler, and each module logs to logging.getLogger(__name__).

setup_logging(*, ...)

Attaches a colored console sink and a dated file sink to the cascadeui logger, and an action log. Call it once at startup:

from cascadeui import setup_logging

setup_logging()

That logs at INFO to the console, to a file in ./logs, and every dispatched action. Every argument is a keyword:

Keyword Default What it sets
level logging.INFO The cascadeui logger's level: an int or a name such as "DEBUG"
actions True Installs LoggingMiddleware, which logs every dispatched action. False leaves it out, and a level name such as "DEBUG" writes the action lines at that level
file True Writes the file sink
stream True Writes the console sink
trace False Installs ViewStore dispatch tracing
path "logs" The folder the file sink writes to
max_files 10 How many of its own dated files to keep, 0 for all
prefix "cascadeui" The start of the file name: <prefix>-YYYY-MM-DD.log
mode "a" The file open mode
encoding "utf-8" The file encoding
colors None A ColorScheme, or a preset name: "default", "ocean", "forest", "none"
color None Color on or off, None to detect it
template None A FormatTemplate, or a preset name: "default", "minimal", "detailed", "compact"
stream_formatter None A logging.Formatter for the console, in place of the built one
file_formatter None A logging.Formatter for the file, in place of the built one
handler None A handler attached in place of both sinks, run on the calling thread. file, stream, colors, color, template, and both formatters are then ignored
setup_logging(level="DEBUG", colors="ocean", template="minimal", max_files=30)

The file sink moves to the new day's file at midnight, so a long-running bot keeps one file per day. At the start and at each midnight it deletes the oldest of its dated files past max_files, and leaves every other file in path alone.

Both sinks run behind a QueueHandler and QueueListener, so the console and file writes happen on a background thread, and the queue drains when the interpreter exits. That thread does not survive os.fork(): a forked child calls setup_logging() again.

A second call replaces what the first attached, so no line is logged twice. That includes the action log: a later call changes its level or, with actions=False, removes it. A LoggingMiddleware the bot installed with setup_middleware() is the bot's, and setup_logging() leaves it as it is.

Raises ValueError for a level, actions, colors, or template name it does not know, and TypeError for a level, colors, or template of the wrong type, or a max_files that is not an int. Either way the earlier setup stays in place.

Python's own controls still work afterwards, so one noisy module can be raised or lowered alone:

import logging

logging.getLogger("cascadeui.state.store").setLevel(logging.DEBUG)

ColorScheme(debug=..., info=..., warning=..., error=..., critical=..., timestamp=..., function=..., name=..., reset=...)

The ANSI escape strings the console sink colors with: one per level, one each for the three fields the template marks (timestamp, function, name), and reset. An empty string leaves that part plain. Pass one to setup_logging(colors=...):

from cascadeui import ColorScheme, setup_logging

setup_logging(colors=ColorScheme(info="\x1b[36m"))

level_color(level) -> str

The color for a numeric level such as logging.INFO, and debug's for any other value. The console sink reads it for the five standard levels when it is built, and draws a custom level as it draws DEBUG.

FormatTemplate(stream_fmt=..., file_fmt=..., datefmt="%Y-%m-%d %H:%M:%S", capitalize_module=True)

The layout of a log line. Both strings take {-style fields ({asctime}, {levelname}, {funcName}, {name}, {message}). stream_fmt also takes the color marks $ts$, $lvl$, $fn$, $name$, and $r$ (reset), filled from the active ColorScheme. file_fmt takes none.

JSONFormatter(fields=None, indent=None)

Writes each record as one JSON object, for a log aggregator. fields names the record attributes to include, and defaults to JSONFormatter.DEFAULT_FIELDS: ("asctime", "levelname", "name", "funcName", "message"). indent pretty-prints. A record with a traceback adds an exception key.

Behind the queue setup_logging() installs, the QueueHandler formats each record before this formatter sees it, so a traceback lands inside message and there is no exception key. To keep the key, attach a handler carrying this formatter through setup_logging(handler=...), which runs on the calling thread.

Developer Tools

DevToolsCog(bot)

The /cascadeui command group: the inspector, and commands that list and close views and sessions and show the store's registries. Only the bot's owner can run them. The /cascadeui Commands lists them.

from cascadeui import DevToolsCog

await bot.add_cog(DevToolsCog(bot))
  • bot (commands.Bot): the bot the cog is added to
  • is_owner_tool (class attribute): True, for a bot that handles owner-only cogs apart from the rest

InspectorView(*, scope_guild_id=None, **kwargs)

A tabbed view of the store: Overview, Views, Sessions, History, Performance, and Config. /cascadeui inspect opens one, and code can send one as it sends any view (The Inspector).

  • scope_guild_id (int or Guild): shows only that server's views and sessions. None shows every server
  • kwargs: the view's own keywords, such as context= or interaction=

Each person has one open per server, and opening another replaces it (instance_limit = 1, instance_scope = "user_guild", instance_policy = "replace"). Each tab is drawn by an async method a subclass can override, returning the tab's components: build_overview(), build_views(), build_sessions(), build_history(), build_performance(), and build_config().

Other Helpers

fetch_as_file(url, filename, *, session=None, spoiler=False, description=None, max_bytes=100 * 1024 * 1024) (async)

Fetches url into an in-memory discord.File, for the attachment:// references the media builders (gallery, image_section, file_attachment) make. Pass one aiohttp.ClientSession across several fetches in a callback. A call without one opens and closes its own. Fetching a File From a Link shows it in a panel.

An error status raises aiohttp.ClientResponseError rather than returning the error page as the file. A body larger than max_bytes raises ValueError: the bytes are counted as they arrive, and the read stops once the count passes the limit.

The default, 100 MiB, is the most Discord takes from a bot in any server. Pass guild.filesize_limit for one server's own limit, or None for no limit. A max_bytes that is not an int raises TypeError, and one below 1 ValueError, both before any request.

slugify(text) -> str

Turns display text into a custom_id fragment: lowercase ASCII letters and digits, each run of anything else one underscore.

from cascadeui import slugify

slugify("Color Roles")  # "color_roles"
slugify("He/Him")       # "he_him"
slugify("Tickets #1")   # "tickets_1"

Text in another script, or emoji alone, gives "", so an id built from such a name needs another source, such as a role's id. Raises TypeError for anything but a str.

is_emoji(text) -> bool

Whether text is one emoji (a flag, a skin tone, or a joined sequence included) or a custom server emoji's token, such as <:name:1234567890123456789>. Plain text, a shortcode such as :trophy:, a token whose id has fewer than 13 digits, and empty text or None give False. It is a check of the main emoji ranges rather than a full Unicode one.

The emoji() validator uses it. Raises TypeError for anything else that is not a str.

@cascade_component(component_id=None)

Decorates a view method so that calling it dispatches COMPONENT_INTERACTION before the body runs, with component_id, view_id, user_id, and handler in the payload. component_id defaults to the method's name. Reach for it to record a click a plain callback would not dispatch.

from cascadeui import StatefulLayoutView, cascade_component

class BoardView(StatefulLayoutView):
    @cascade_component("reroll")
    async def reroll(self, interaction):
        self._board = new_board()
        self.build_ui()       # compose the new board
        await self.refresh()  # then send it

The dispatch runs before the body, so a view that renders from on_state_changed() renders from the old state, and refresh() sends the tree the view already holds. The body composes the new render itself, as above.

register_component(name, component_class) / get_component(name)

The V1 composition registry. register_component() stores a component class under a name, replacing any class already there, and get_component() returns it, or None for a name never registered.

from cascadeui import ConfirmationButtons, get_component, register_component

register_component("confirm_row", ConfirmationButtons)

cls = get_component("confirm_row")
cls(on_confirm=save, on_cancel=discard).add_to_view(view)

It holds classes and is unrelated to @cascade_component, which dispatches actions.