GitHub

chat_interaction

API reference for chat_interaction.

Typed buttons, selects, modals and slash commands, and the service that receives their clicks, submits and commands (Effect's effect/chat/ChatInteraction).

A definition carries an element's id and the schema of its value. It builds the element to post (of, open) and its handler (handler), the way a Tool does. A group of definitions becomes a layer of handlers, and chat_interaction.layer provides the Handler service adapters call::

Deploy = S.Struct(DeployDict)
Reject = ci.button("reject", label="Reject", style="danger", value=Deploy)
RejectReason = ci.modal(
    "reject-reason",
    title="Reject deploy",
    metadata=Deploy,
    fields={"reason": ci.text_input(label="Reason", multiline=True)},
)
interactions = ci.group(Reject, RejectReason).to_layer(
    Reject.handler(lambda click: fx.succeed(RejectReason.open(metadata=click.value))),
    RejectReason.handler(
        lambda submit: fx.succeed(
            ci.errors(reason="Say a bit more.")
            if len(submit.values["reason"]) < 10
            else ci.close
        )
    ),
).pipe(layer.provide_merge(ci.layer()))
  • Clicks, submits and commands are not ChatEvents. They need an answer inside the platform's 3 seconds, so they go to Handler, which answers by return value and has no error channel.
  • Slack and Discord don't redeliver them, so they carry no dedupe key.

Values

AttributeTypeDescription
INTERACTIONS.Bottom[Interaction]
VISIBILITYLiteralsSchema[Literal['ephemeral', 'public']]
ackAck
closeClose
lateLate

Types

TypeDefinitionDescription
Interactiontype Interaction = ButtonClicked | SelectChanged | ModalSubmitted | CommandInvoked

What an adapter hands to Handler.

ClickReplytype ClickReply = Ack | OpenModal
SubmitReplytype SubmitReply = Close | Errors
Visibilitytype Visibility = Literal['ephemeral', 'public']

Who sees a command's answer: the person who ran it, or the channel.

CommandReplytype CommandReply = Ack | Respond | OpenModal | Defer
ValueSchematype ValueSchema[T] = S.Codec[T, Any, Never, Never]

A value's schema; it needs no services, since of and open are plain functions.

Fieldtype Field = TextInput | Choice | SelectInput | Text

Any field of a modal.

Definitiontype Definition = Button[str, Any] | Select[str, Any] | Modal[str, Any] | Command[str]

Any definition that has a handler.

Classes

Functions

errors

errors(fields=None, **by_field) -> Errors

Puts a message under each named field of a submitted modal.

ParameterTypeDescription
fieldsMapping[str, str] | None = None
by_fieldstr = {}

Returns Errors

def errors(fields: Mapping[str, str] | None = None, /, **by_field: str) -> Errors:
    """Puts a message under each named field of a submitted modal."""
    return Errors(errors={**(fields or {}), **by_field})

respond

respond(*, markdown, actions=None, visibility='ephemeral') -> Respond

Answers a command with a message, at once. visibility defaults to "ephemeral"; a platform without ephemeral refuses a private answer and never sends it publicly instead.

ParameterTypeDescription
markdownstr
actionsSequence[U.Action] | None = None
visibilityVisibility = 'ephemeral'

Returns Respond

def respond(
    *,
    markdown: str,
    actions: Sequence[U.Action] | None = None,
    visibility: Visibility = "ephemeral",
) -> Respond:
    """Answers a command with a message, at once. ``visibility`` defaults to
    ``"ephemeral"``; a platform without ``ephemeral`` refuses a private
    answer and never sends it publicly instead."""
    return Respond(
        markdown=markdown,
        actions=None if actions is None else tuple(actions),
        visibility=visibility,
    )

defer

defer(command, *, visibility='ephemeral') -> Defer

Answers a command with a promise of a later answer, sent with Chat.follow_up, for work that does not fit the deadline. visibility holds for the follow-up. One follow-up per deferral is the portable contract.

ParameterTypeDescription
commandCommandInvoked
visibilityVisibility = 'ephemeral'

Returns Defer

def defer(command: CommandInvoked, *, visibility: Visibility = "ephemeral") -> Defer:
    """Answers a command with a promise of a later answer, sent with
    ``Chat.follow_up``, for work that does not fit the deadline.
    ``visibility`` holds for the follow-up. One follow-up per deferral is
    the portable contract."""
    return Defer(command=command, visibility=visibility)

encode_value

encode_value[T](schema, value) -> str

The string an element carries for value. The form is decided once per schema from its JSON codec's encoded side: a string-only schema sends the string as it is, any other the JSON text. Raises when the value has no JSON form.

ParameterTypeDescription
schemaValueSchema[T]
valueT

Returns str

def encode_value[T](schema: ValueSchema[T], value: T) -> str:
    """The string an element carries for ``value``. The form is decided once
    per schema from its JSON codec's encoded side: a string-only schema
    sends the string as it is, any other the JSON text. Raises when the
    value has no JSON form."""
    wire = _wire_of(schema)
    encoded = wire.encode(value)
    if wire.raw:
        return cast("str", encoded)
    return _json_text.stringify(encoded)

decode_value

decode_value[T](schema, encoded) -> Option[T]

The value an element carried, as encode_value wrote it; None for a string that no longer decodes (one posted under an older schema).

ParameterTypeDescription
schemaValueSchema[T]
encodedstr

Returns Option[T]

def decode_value[T](schema: ValueSchema[T], encoded: str) -> Option[T]:
    """The value an element carried, as ``encode_value`` wrote it; ``None``
    for a string that no longer decodes (one posted under an older
    schema)."""
    wire = _wire_of(schema)
    if wire.raw:
        return cast("Option[T]", wire.decode(encoded))
    try:
        parsed = _json_text.parse(encoded)
    except ValueError:
        return None
    return cast("Option[T]", wire.decode(parsed))

button

button[I: str](id: I, *, label: str, style: U.ButtonStyle | None = None) -> Button[I, None]
button[I: str, T](id: I, *, label: str, style: U.ButtonStyle | None = None, value: ValueSchema[T]) -> Button[I, T]

Defines a button. The id names its handler in a group and is sent to the platform as is, counting toward limits.action_data_length with the encoded value. With no value schema a click's value is None.

ParameterTypeDescription
id
label
style= None
value= None
@overload
def button[I: str](id: I, *, label: str, style: U.ButtonStyle | None = None) -> Button[I, None]: ...
@overload
def button[I: str, T](
    id: I, *, label: str, style: U.ButtonStyle | None = None, value: ValueSchema[T]
) -> Button[I, T]: ...
def button(
    id: str,
    *,
    label: str,
    style: U.ButtonStyle | None = None,
    value: ValueSchema[Any] | None = None,
) -> Button[Any, Any]:
    """Defines a button. The id names its handler in a ``group`` and is sent
    to the platform as is, counting toward ``limits.action_data_length``
    with the encoded value. With no ``value`` schema a click's value is
    ``None``."""
    return Button(id, label, style, value)

select

select[I: str](id: I, *, placeholder: str | None = None) -> Select[I, str]
select[I: str, T](id: I, *, placeholder: str | None = None, value: ValueSchema[T]) -> Select[I, T]

Defines a single-choice select for a message. With no value schema the options' values are plain strings.

ParameterTypeDescription
id
placeholder= None
value= None
@overload
def select[I: str](id: I, *, placeholder: str | None = None) -> Select[I, str]: ...
@overload
def select[I: str, T](
    id: I, *, placeholder: str | None = None, value: ValueSchema[T]
) -> Select[I, T]: ...
def select(
    id: str, *, placeholder: str | None = None, value: ValueSchema[Any] | None = None
) -> Select[Any, Any]:
    """Defines a single-choice select for a message. With no ``value``
    schema the options' values are plain strings."""
    return Select(id, placeholder, value)

text_input

text_input(*, label, multiline=False, placeholder=None, optional=False, min_length=None, max_length=None) -> TextInput

Defines a text input for a modal; its id is its key in fields.

ParameterTypeDescription
labelstr
multilinebool = False
placeholderstr | None = None
optionalbool = False
min_lengthint | None = None
max_lengthint | None = None

Returns TextInput

def text_input(
    *,
    label: str,
    multiline: bool = False,
    placeholder: str | None = None,
    optional: bool = False,
    min_length: int | None = None,
    max_length: int | None = None,
) -> TextInput:
    """Defines a text input for a modal; its id is its key in ``fields``."""
    return TextInput(
        label=label,
        multiline=multiline,
        placeholder=placeholder,
        optional=optional,
        min_length=min_length,
        max_length=max_length,
    )

choice

choice(*, label, options, placeholder=None, optional=False) -> Choice

Defines a select for a modal whose options are fixed here.

ParameterTypeDescription
labelstr
optionsSequence[OptionOf[str]]
placeholderstr | None = None
optionalbool = False

Returns Choice

def choice(
    *,
    label: str,
    options: Sequence[OptionOf[str]],
    placeholder: str | None = None,
    optional: bool = False,
) -> Choice:
    """Defines a select for a modal whose options are fixed here."""
    return Choice(label=label, placeholder=placeholder, options=tuple(options), optional=optional)

select_input

select_input(*, label, placeholder=None, value=None, optional=False) -> SelectInput

Defines a select for a modal; its id is its key in fields and its options are given to the modal's open.

ParameterTypeDescription
labelstr
placeholderstr | None = None
valueValueSchema[Any] | None = None
optionalbool = False

Returns SelectInput

def select_input(
    *,
    label: str,
    placeholder: str | None = None,
    value: ValueSchema[Any] | None = None,
    optional: bool = False,
) -> SelectInput:
    """Defines a select for a modal; its id is its key in ``fields`` and its
    options are given to the modal's ``open``."""
    return SelectInput(label=label, placeholder=placeholder, value=value, optional=optional)

text

text(text) -> Text

Defines plain (not Markdown) text for a modal.

ParameterTypeDescription
textstr

Returns Text

def text(text: str) -> Text:
    """Defines plain (not Markdown) text for a modal."""
    return Text(text)
modal[I: str](id: I, *, title: str, fields: Mapping[str, Field], submit_label: str | None = None) -> Modal[I, None]
modal[I: str, T](id: I, *, title: str, fields: Mapping[str, Field], metadata: ValueSchema[T], submit_label: str | None = None) -> Modal[I, T]

Defines a modal. The id names the submit's handler; with the encoded metadata it counts toward limits.modal_metadata_length, and inputs and texts toward limits.modal_fields. A portable modal has a title of 24 or less, labels of 45 or less, at most 5 fields, and an id plus metadata under 100 characters.

ParameterTypeDescription
id
title
fields
metadata= None
submit_label= None
@overload
def modal[I: str](
    id: I, *, title: str, fields: Mapping[str, Field], submit_label: str | None = None
) -> Modal[I, None]: ...
@overload
def modal[I: str, T](
    id: I,
    *,
    title: str,
    fields: Mapping[str, Field],
    metadata: ValueSchema[T],
    submit_label: str | None = None,
) -> Modal[I, T]: ...
def modal(
    id: str,
    *,
    title: str,
    fields: Mapping[str, Field],
    metadata: ValueSchema[Any] | None = None,
    submit_label: str | None = None,
) -> Modal[Any, Any]:
    """Defines a modal. The id names the submit's handler; with the encoded
    metadata it counts toward ``limits.modal_metadata_length``, and inputs
    and texts toward ``limits.modal_fields``. A portable modal has a title
    of 24 or less, labels of 45 or less, at most 5 fields, and an id plus
    metadata under 100 characters."""
    return Modal(id, title, submit_label, metadata, dict(fields))

command

command[I: str](id, *, description, argument=None) -> Command[I]

Defines a slash command; the id is its name without the slash and shares the registry's id space with buttons, selects and modals. Slack sends everything after the name as one string and cannot enforce required, so a portable handler checks for an empty text.

ParameterTypeDescription
idI
descriptionstr
argumentCommandArgument | None = None

Returns Command[I]

def command[I: str](
    id: I, *, description: str, argument: CommandArgument | None = None
) -> Command[I]:
    """Defines a slash command; the id is its name without the slash and
    shares the registry's id space with buttons, selects and modals. Slack
    sends everything after the name as one string and cannot enforce
    ``required``, so a portable handler checks for an empty ``text``."""
    return Command(id, description, argument)

group

group(*definitions) -> Group[str]

Groups definitions so their handlers can be registered together.

ParameterTypeDescription
definitionsDefinition = ()

Returns Group[str]

def group(*definitions: Definition) -> Group[str]:
    """Groups definitions so their handlers can be registered together."""
    return Group(definitions)

handle

handle(event: ButtonClicked | SelectChanged, deadline: DurationInput) -> Effect[ClickReply | Late, Never, Handler]
handle(event: ModalSubmitted, deadline: DurationInput) -> Effect[SubmitReply | Late, Never, Handler]
handle(event: CommandInvoked, deadline: DurationInput) -> Effect[CommandReply | Late, Never, Handler]
handle(event: Interaction, deadline: DurationInput) -> Effect[_AnyReply | Late, Never, Handler]

Calls the Handler service and gives the reply, or Late when deadline (the handler's share of the platform's 3 seconds) passes first; adapters and ChatTest call it.

  • A late click leaves its handler running, detached. When it later returns OpenModal the modal is dropped and Handler.refused gets a ChatError with reason NotFound, op openModal, detail interaction_expired.
  • A late submit or command interrupts its handler; Late is given at the deadline without waiting for its finalizers.
ParameterTypeDescription
event
deadline
@overload
def handle(
    event: ButtonClicked | SelectChanged, deadline: DurationInput
) -> Effect[ClickReply | Late, Never, Handler]: ...
@overload
def handle(
    event: ModalSubmitted, deadline: DurationInput
) -> Effect[SubmitReply | Late, Never, Handler]: ...
@overload
def handle(
    event: CommandInvoked, deadline: DurationInput
) -> Effect[CommandReply | Late, Never, Handler]: ...
@overload
def handle(
    event: Interaction, deadline: DurationInput
) -> Effect[_AnyReply | Late, Never, Handler]: ...
def handle(event: Interaction, deadline: DurationInput) -> Effect[Any, Never, Handler]:
    """Calls the ``Handler`` service and gives the reply, or ``Late`` when
    ``deadline`` (the handler's share of the platform's 3 seconds) passes
    first; adapters and ``ChatTest`` call it.

    - A late click leaves its handler running, detached. When it later
      returns ``OpenModal`` the modal is dropped and ``Handler.refused`` gets
      a ``ChatError`` with reason ``NotFound``, op ``openModal``, detail
      ``interaction_expired``.
    - A late submit or command interrupts its handler; ``Late`` is given at
      the deadline without waiting for its finalizers.
    """

    def body(restore: fx.Restore) -> Effect[Any, Never, Handler]:
        def with_handler(handler: HandlerService) -> Effect[_AnyReply | Late]:
            work: Effect[_AnyReply] = (
                handler.submit(event)
                if isinstance(event, ModalSubmitted)
                else handler.command(event)
                if isinstance(event, CommandInvoked)
                else handler.click(event)
            )
            # Detached, so the reply at the deadline waits for neither a late click nor a
            # late submit's cleanup.
            return work.fork_daemon().flat_map(lambda fiber: wait(handler, fiber))

        def wait(
            handler: HandlerService, fiber: Fiber[_AnyReply, Never]
        ) -> Effect[_AnyReply | Late]:
            timed: Effect[Option[Exit[_AnyReply, Never]]] = restore(
                fiber.await_exit().timeout_option(deadline)
            )
            return timed.on_interrupt(fiber.interrupt()).flat_map(
                lambda exit: fx.from_exit(exit.value) if exit is not None else after(handler, fiber)
            )

        def after(handler: HandlerService, fiber: Fiber[_AnyReply, Never]) -> Effect[Late]:
            if not isinstance(event, (ButtonClicked, SelectChanged)):
                # Interrupt without delaying the deadline reply.
                return fiber.interrupt().fork_daemon().as_(late)
            clicked = event

            def refuse(done: Exit[_AnyReply, Never]) -> Effect[None]:
                if isinstance(done, Success) and isinstance(done.value, OpenModal):
                    return handler.refused(clicked, _late_click(clicked))
                return fx.void

            return fiber.await_exit().flat_map(refuse).fork_daemon().as_(late)

        return Handler().flat_map(with_handler)

    return fx.uninterruptible_mask(body)

layer

layer[R = Never](*, unhandled=None) -> Layer[Handler | Registry, Never, R]

The Handler that routes by id to the registered definitions, and an empty Registry; group layers go on top with layer.provide_merge.

  • An interaction with an unknown id, or a value that no longer decodes, is logged and answered ack or close; unhandled sees it first and cannot change the answer.
  • A command with an unknown id is answered ack (the adapter sends nothing) and logged at debug level.
  • Handler.refused goes to unhandled as ReplyRefused, and is logged.
ParameterTypeDescription
unhandledCallable[[Interaction, Unhandled], Effect[None, Never, R]] | None = None

Returns Layer[Handler | Registry, Never, R]

def layer[R = Never](
    *, unhandled: Callable[[Interaction, Unhandled], Effect[None, Never, R]] | None = None
) -> Layer[Handler | Registry, Never, R]:
    """The ``Handler`` that routes by id to the registered definitions, and
    an empty ``Registry``; group layers go on top with
    ``layer.provide_merge``.

    - An interaction with an unknown id, or a value that no longer decodes,
      is logged and answered ``ack`` or ``close``; ``unhandled`` sees it
      first and cannot change the answer.
    - A command with an unknown id is answered ``ack`` (the adapter sends
      nothing) and logged at debug level.
    - ``Handler.refused`` goes to ``unhandled`` as ``ReplyRefused``, and is
      logged.
    """

    def make(context: Context[R]) -> Context[Handler | Registry]:
        entries: dict[str, Registered] = {}

        def report(event: Interaction, why: Unhandled, message: str) -> Effect[None]:
            seen: Effect[None] = (
                fx.void
                if unhandled is None
                else _call_user(unhandled, event, why).pipe(fx.provide_context(context))
            )
            log = (
                fx.log_debug(message)
                if isinstance(event, CommandInvoked) and why.reason == "UnknownId"
                else fx.log_warning(message)
            )
            return seen.and_then(
                log.annotate_logs(
                    {
                        "chat.platform": event.thread.platform,
                        "chat.interaction.id": event.id,
                        "chat.interaction.reason": why.reason,
                    }
                )
            )

        def route(event: Interaction) -> Effect[_AnyReply]:
            def run() -> Effect[_AnyReply]:
                entry = entries.get(event.id)
                if entry is None or not _matches(entry.definition, event):
                    return report(
                        event, Unhandled("UnknownId"), "ChatInteraction: no handler for this id"
                    ).as_(_fallback(event))
                if _decode_event(entry.definition, event) is None:
                    return report(
                        event,
                        Unhandled("InvalidValue"),
                        "ChatInteraction: the value no longer decodes",
                    ).as_(_fallback(event))
                return entry.handle(event)

            return fx.suspend(run)

        def refused(
            event: ButtonClicked | SelectChanged | CommandInvoked, error: ChatError
        ) -> Effect[None]:
            return report(
                event,
                Unhandled("ReplyRefused", error),
                "ChatInteraction: the reply was not carried out",
            ).annotate_logs("chat.error", error.message)

        handler = HandlerService(
            click=cast("Callable[[ButtonClicked | SelectChanged], Effect[ClickReply]]", route),
            submit=cast("Callable[[ModalSubmitted], Effect[SubmitReply]]", route),
            command=cast("Callable[[CommandInvoked], Effect[CommandReply]]", route),
            refused=refused,
        )
        return Context.make(Handler, handler).add(Registry, RegistryService(entries))

    return _layer_effect_context(fx.context().map(make))  # pyright: ignore[reportArgumentType]