GitHub

API reference for Service.

Drives the fake platform: what a user does on it, and what it holds.

  • make_thread makes a channel, a direct address, or a thread under a user's opener.
  • user_posts stores a message from another identity and gives the MessageCreated the platform would deliver; deliver hands an event to ChatHandler.
  • fail_next fails the next times calls of an op with reason (landed runs the call first, as a write that landed but answered with an error); refuse_files refuses the next posts with files.
  • click, command and submit build the interaction the platform would send; interact runs it through chat_interaction.handle and carries out the reply as the platform would, calling Handler.refused when it cannot.

Attributes

AttributeTypeDescription
platformstr

The fake platform's name.

self_idstr

The bot's own user id on the fake platform.

callsEffect[tuple[Call, ...]]

Every adapter call made so far, in order.

Functions

__init__

__init__(fake) -> None
ParameterTypeDescription
fake_Fake
def __init__(self, fake: _Fake) -> None:
    self._fake = fake

make_thread

make_thread(kind='channel') -> Effect[ChatThread]

A new channel, direct address, or thread under a user's opener.

ParameterTypeDescription
kindThreadKind = 'channel'

Returns Effect[ChatThread]

def make_thread(self, kind: ThreadKind = "channel") -> Effect[ChatThread]:
    """A new channel, direct address, or thread under a user's opener."""
    if kind != "thread":
        return self._add_thread(kind)

    @fx.gen
    def under_opener() -> Generator[Effect[Any, Never, Never], Any, ChatThread]:
        channel: ChatThread = yield from self._add_thread("channel")
        event: MessageCreated = yield from self.user_posts(channel, text="thread opener")
        created: ChatThread = yield from self._fake.create_thread(
            "makeThread", channel, event.message.id, None
        ).or_die()
        return created

    return under_opener

user_posts

user_posts(thread, *, text, author_id='user', is_bot=False, mentions_self=False, reply_to=None, files=()) -> Effect[MessageCreated]

Stores a message from another identity and gives the MessageCreated the platform would deliver.

ParameterTypeDescription
threadChatThread
textstr
author_idstr = 'user'
is_botbool = False
mentions_selfbool = False
reply_toReplyTo | None = None
filesSequence[File] = ()

Returns Effect[MessageCreated]

def user_posts(
    self,
    thread: ChatThread,
    *,
    text: str,
    author_id: str = "user",
    is_bot: bool = False,
    mentions_self: bool = False,
    reply_to: ReplyTo | None = None,
    files: Sequence[File] = (),
) -> Effect[MessageCreated]:
    """Stores a message from another identity and gives the
    ``MessageCreated`` the platform would deliver."""
    fake = self._fake

    def post() -> Effect[MessageCreated]:
        stored = fake.threads.get(thread.id)
        if stored is None:
            return fx.die(RuntimeError("ChatTest.user_posts: unknown thread"))
        fake.users[author_id] = is_bot
        body = f"<@{fake.self_id}> {text}" if mentions_self else text
        target = None if reply_to is None else fake.messages.get(reply_to.message_id)
        # The author is read from the stored message, as a platform does, not from the caller.
        replied = (
            None
            if reply_to is None
            else ReplyTo(
                message_id=reply_to.message_id,
                author_id=None if target is None else target.author_id,
            )
        )
        return fake.store(
            thread=thread,
            author_id=author_id,
            is_bot=is_bot,
            is_self=False,
            text=body,
            mentions=_parse_mentions(body, fake.self_id),
            reply_to=replied,
            attachments=fake.store_files(files),
            actions=(),
        ).map(
            lambda created: MessageCreated(
                thread=thread,
                kind=stored.kind,
                message=fake.to_message(created),
                raw={"type": "event_callback", "event_id": fake.next_id("e")},
            )
        )

    return fx.suspend(post)

deliver

deliver(event) -> Effect[None, NotAccepted, ChatHandler]

Hands event to ChatHandler.

ParameterTypeDescription
eventChatEvent

Returns Effect[None, NotAccepted, ChatHandler]

def deliver(self, event: ChatEvent) -> Effect[None, NotAccepted, ChatHandler]:
    """Hands ``event`` to ``ChatHandler``."""
    return ChatHandler().flat_map(lambda handler: handler.handle(event))

messages

messages(thread) -> Effect[tuple[ChatMessage, ...]]

The messages stored in thread, oldest first.

ParameterTypeDescription
threadChatThread

Returns Effect[tuple[ChatMessage, ...]]

def messages(self, thread: ChatThread) -> Effect[tuple[ChatMessage, ...]]:
    """The messages stored in ``thread``, oldest first."""
    fake = self._fake

    def read() -> tuple[ChatMessage, ...]:
        stored = fake.threads.get(thread.id)
        if stored is None:
            return ()
        return tuple(fake.to_message(message) for message in fake.list_messages(stored))

    return fx.sync(read)

refuse_files

refuse_files(*, times=1) -> Effect[None]

Refuses the next times posts with files.

ParameterTypeDescription
timesint = 1

Returns Effect[None]

def refuse_files(self, *, times: int = 1) -> Effect[None]:
    """Refuses the next ``times`` posts with files."""

    def refuse() -> None:
        self._fake.refused_files += times

    return fx.sync(refuse)

fail_next

fail_next(op, reason, *, times=1, landed=False) -> Effect[None]

Fails the next times calls of op with reason; landed runs the call first.

ParameterTypeDescription
opstr
reasonAnyReason
timesint = 1
landedbool = False

Returns Effect[None]

def fail_next(
    self, op: str, reason: AnyReason, *, times: int = 1, landed: bool = False
) -> Effect[None]:
    """Fails the next ``times`` calls of ``op`` with ``reason``;
    ``landed`` runs the call first."""

    def add() -> None:
        if times == 0:
            return
        self._fake.faults.setdefault(op, []).append(_Fault(reason, times, landed))

    return fx.sync(add)

click_stop

click_stop(message_id) -> Effect[None]

Clicks stop on the native stream message_id.

ParameterTypeDescription
message_idstr

Returns Effect[None]

def click_stop(self, message_id: str) -> Effect[None]:
    """Clicks stop on the native stream ``message_id``."""

    def click(stream: _StoredStream) -> None:
        stream.clicked = True

    return self._stream_for("click_stop", message_id).map(click)

close_stream

close_stream(message_id) -> Effect[None]

Closes the native stream message_id, as its expiry would.

ParameterTypeDescription
message_idstr

Returns Effect[None]

def close_stream(self, message_id: str) -> Effect[None]:
    """Closes the native stream ``message_id``, as its expiry would."""

    def close(stream: _StoredStream) -> None:
        stream.open = False

    return self._stream_for("close_stream", message_id).map(close)

click

click(message_id, id, *, user_id='user', option=None) -> Effect[ci.ButtonClicked | ci.SelectChanged, NoSuchElement]

The click on element id of message message_id the platform would send (a select's option).

ParameterTypeDescription
message_idstr
idstr
user_idstr = 'user'
optionstr | None = None

Returns Effect[ci.ButtonClicked | ci.SelectChanged, NoSuchElement]

def click(
    self, message_id: str, id: str, *, user_id: str = "user", option: str | None = None
) -> Effect[ci.ButtonClicked | ci.SelectChanged, NoSuchElement]:
    """The click on element ``id`` of message ``message_id`` the platform
    would send (a select's ``option``)."""
    fake = self._fake

    def build() -> Effect[ci.ButtonClicked | ci.SelectChanged, NoSuchElement]:
        missing = fx.fail(NoSuchElement(message_id=message_id, id=id))
        message = fake.messages.get(message_id)
        element = (
            None
            if message is None
            else next(
                (
                    action
                    for action in message.actions
                    if not isinstance(action, U.LinkButton) and action.id == id
                ),
                None,
            )
        )
        if message is None or element is None or isinstance(element, U.LinkButton):
            return missing
        raw: JsonValue = {
            "type": "interaction",
            "id": fake.next_id("i"),
            "message": message_id,
            "element": id,
        }
        if isinstance(element, U.Button):
            return fx.succeed(
                ci.ButtonClicked(
                    id=id,
                    value=element.value,
                    thread=message.thread,
                    message_id=message_id,
                    user_id=user_id,
                    raw=raw,
                )
            )
        chosen = (
            (element.options[0] if element.options else None)
            if option is None
            else next((o for o in element.options if o.value == option), None)
        )
        if chosen is None:
            return missing
        return fx.succeed(
            ci.SelectChanged(
                id=id,
                value=chosen.value,
                thread=message.thread,
                message_id=message_id,
                user_id=user_id,
                raw=raw,
            )
        )

    return fx.suspend(build)

command

command(thread, id, *, text='', user_id='user') -> Effect[ci.CommandInvoked]

The slash command the platform would send.

ParameterTypeDescription
threadChatThread
idstr
textstr = ''
user_idstr = 'user'

Returns Effect[ci.CommandInvoked]

def command(
    self, thread: ChatThread, id: str, *, text: str = "", user_id: str = "user"
) -> Effect[ci.CommandInvoked]:
    """The slash command the platform would send."""
    fake = self._fake
    return fx.sync(
        lambda: ci.CommandInvoked(
            id=id,
            text=text,
            thread=thread,
            user_id=user_id,
            raw={"type": "command", "id": fake.next_id("i"), "command": id, "text": text},
        )
    )

submit

submit(from_, opened, values, *, user_id=None) -> Effect[ci.ModalSubmitted]

The submit of an open modal the platform would send.

ParameterTypeDescription
from__From
openedci.OpenModal
valuesMapping[str, str]
user_idstr | None = None

Returns Effect[ci.ModalSubmitted]

def submit(
    self,
    from_: _From,
    opened: ci.OpenModal,
    values: Mapping[str, str],
    *,
    user_id: str | None = None,
) -> Effect[ci.ModalSubmitted]:
    """The submit of an open modal the platform would send."""
    fake = self._fake
    return fx.sync(
        lambda: ci.ModalSubmitted(
            id=opened.modal.id,
            metadata=opened.modal.metadata,
            values={key: value for key, value in values.items() if value != ""},
            thread=from_.thread,
            message_id=None if isinstance(from_, ci.CommandInvoked) else from_.message_id,
            user_id=user_id if user_id is not None else from_.user_id,
            raw={"type": "submission", "id": fake.next_id("i"), "modal": opened.modal.id},
        )
    )

interact

interact(event: ci.ButtonClicked | ci.SelectChanged) -> Effect[ci.ClickReply | ci.Late, Never, ci.Handler]
interact(event: ci.ModalSubmitted) -> Effect[ci.SubmitReply | ci.Late, Never, ci.Handler]
interact(event: ci.CommandInvoked) -> Effect[ci.CommandReply | ci.Late, Never, ci.Handler]
interact(event: ci.Interaction) -> Effect[Any, Never, ci.Handler]

Runs event through chat_interaction.handle and carries out the reply as the platform would, calling Handler.refused when it cannot.

ParameterTypeDescription
event
@overload
def interact(
    self, event: ci.ButtonClicked | ci.SelectChanged
) -> Effect[ci.ClickReply | ci.Late, Never, ci.Handler]: ...
@overload
def interact(
    self, event: ci.ModalSubmitted
) -> Effect[ci.SubmitReply | ci.Late, Never, ci.Handler]: ...
@overload
def interact(
    self, event: ci.CommandInvoked
) -> Effect[ci.CommandReply | ci.Late, Never, ci.Handler]: ...
@overload
def interact(self, event: ci.Interaction) -> Effect[Any, Never, ci.Handler]: ...
def interact(self, event: ci.Interaction) -> Effect[Any, Never, ci.Handler]:
    """Runs ``event`` through ``chat_interaction.handle`` and carries out
    the reply as the platform would, calling ``Handler.refused`` when it
    cannot."""
    fake = self._fake

    @fx.gen
    def run() -> Generator[Effect[Any, Never, ci.Handler], Any, object]:
        reply: object = yield from ci.handle(event, fake.interaction_deadline)
        if isinstance(event, ci.ModalSubmitted):
            return reply
        refusal: ChatError | None = None
        match reply:
            case ci.OpenModal():
                refusal = fake.modal_refusal(reply.modal)
                fake.calls.append(
                    Call(
                        op="openModal",
                        thread=event.thread,
                        message_id=None
                        if isinstance(event, ci.CommandInvoked)
                        else event.message_id,
                        outcome="ok" if refusal is None else refusal.reason._tag,  # pyright: ignore[reportPrivateUsage]
                    )
                )
            case ci.Respond():
                actions = reply.actions or ()
                exit = yield from fake.attempt(
                    op="respond",
                    thread=event.thread,
                    markdown=reply.markdown,
                    needs=_answer_needs(reply.visibility, actions),
                    body=check_message_length(
                        fake.descriptor, "respond", reply.markdown, actions
                    ).and_then(fake.check_actions("respond", actions)),
                    retries=False,
                ).exit()
                refusal = _error_of(exit)
            case ci.Defer():
                missing = first_missing(_answer_needs(reply.visibility), fake.capabilities)
                if missing is not None:
                    refusal = fake.error("defer", Unsupported(capability=missing))
                else:
                    key = _command_key(event) if isinstance(event, ci.CommandInvoked) else None
                    if key is not None:
                        now: float = yield from _clock.current_time_millis()
                        fake.deferrals[key] = _Deferral(now)
            case _:
                pass
        if refusal is not None:
            handler: ci.HandlerService = yield from ci.Handler()
            yield from handler.refused(event, refusal)
        return reply

    return run