GitHub

DiscordChatService

API reference for DiscordChatService.

The Discord side of the adapter, for what the core has no op for.

  • bot_user_id comes from GET /users/@me, read once. A failed read is tried again next time.
  • dispatch takes one gateway dispatch, t and d, and hands its events to the ChatHandler one at a time. When a MESSAGE_CREATE carries no channel_type, it looks the channel up, cached and with a five second timeout. A failed lookup is logged and fails with NotAccepted; one that would fail the same way again, such as a deleted channel, is logged and the event dropped.
  • interaction takes one INTERACTION_CREATE payload from the gateway and answers through the interaction callback endpoint, which has to land inside Discord's 3 seconds: deadline is the handler's share, 2 seconds by default. It ignores an interaction it can't express: a message or user command, an autocomplete request, a slash command with anything but at most one string option.
  • A click is answered with callback type 6, or type 9 for OpenModal. A submit's close is type 6. An errors reply is type 4 with the ephemeral flag, listing each message as plain text, and the modal closes: Discord can't show an error inside a modal.
  • A slash command goes to Handler.command. respond is callback type 4, defer type 5 and OpenModal type 9, each with the ephemeral flag when private. An Ack sends nothing, so a command another library owns is left to it. with_post_options does not reach a command's answer.
  • A modal that can't be built, a reply to a command that fails the checks of a post, or a callback that fails, goes to Handler.refused. A callback that comes back 404 Unknown interaction was late: NotFound with detail interaction_expired.
  • guild reads the channel, cached; None for a direct.

Attributes

AttributeTypeDescription
bot_user_idEffect[str, ChatError]

The bot's user id, from GET /users/@me.

adapterDiscordAdapter

The registered adapter.

Functions

__init__

__init__(*, bot_user_id, adapter) -> None
ParameterTypeDescription
bot_user_idEffect[str, ChatError]
adapterDiscordAdapter
def __init__(
    self,
    *,
    bot_user_id: Effect[str, ChatError],
    adapter: DiscordAdapter,
) -> None:
    self._bot_user_id = bot_user_id
    self._adapter = adapter

dispatch

dispatch(payload) -> Effect[None, NotAccepted, ChatHandler]

Hands one gateway dispatch's events to the ChatHandler; see the class.

ParameterTypeDescription
payloadGatewayDispatch

Returns Effect[None, NotAccepted, ChatHandler]

def dispatch(self, payload: GatewayDispatch) -> Effect[None, NotAccepted, ChatHandler]:
    """Hands one gateway dispatch's events to the ``ChatHandler``; see the class."""
    t, d = payload.t, payload.d
    if t not in _normalize.HANDLED:
        return fx.void
    adapter = self._adapter

    def refuse(message: str, error: ChatError) -> Effect[Never, NotAccepted]:
        return fx.log_warning(message, error).and_then(fx.fail(NotAccepted()))

    @fx.gen
    def run() -> Generator[Effect[Any, NotAccepted, Any], Any]:
        handler = yield from ChatHandler()
        bot_user_id = yield from self._bot_user_id.catch_all(
            lambda error: refuse("discord dispatch: bot user lookup failed", error)
        )
        result = _normalize.normalize(t, d, bot_user_id=bot_user_id)
        if isinstance(result, _normalize.MissingChannelType):

            def failed(error: ChatError) -> Effect[float | None, NotAccepted]:
                if error.retry == "denied":
                    return fx.log_warning(
                        "discord dispatch: channel lookup denied, event dropped", error
                    ).as_(None)
                return refuse("discord dispatch: channel lookup failed", error)

            found = (
                yield from adapter.channel_type(result.channel_id)
                .timeout_or_else(
                    _LOOKUP_TIMEOUT,
                    lambda: fx.fail(
                        _errors.chat_error(
                            "dispatch", _errors.transport(False, "lookup_timeout")
                        )
                    ),
                )
                .catch_all(failed)
            )
            if found is None:
                return
            result = _normalize.normalize(t, d, bot_user_id=bot_user_id, channel_type=found)
            if isinstance(result, _normalize.MissingChannelType):
                return
        for event in result.events:
            yield from handler.handle(event)

    return run

interaction

interaction(payload, *, deadline=DEFAULT_DEADLINE) -> Effect[None, Never, Handler]

Handles one INTERACTION_CREATE payload from the gateway; see the class.

ParameterTypeDescription
payloadobject
deadlineDurationInput = DEFAULT_DEADLINE

Returns Effect[None, Never, Handler]

def interaction(
    self, payload: object, *, deadline: DurationInput = DEFAULT_DEADLINE
) -> Effect[None, Never, Handler]:
    """Handles one ``INTERACTION_CREATE`` payload from the gateway; see the class."""
    return self._adapter.interaction(
        payload, from_input_unsafe(deadline), self._adapter.send_callback
    )

guild

guild(thread) -> Effect[str | None, ChatError]

The guild a channel or thread is in; None for a direct.

ParameterTypeDescription
threadChatThread

Returns Effect[str | None, ChatError]

def guild(self, thread: ChatThread) -> Effect[str | None, ChatError]:
    """The guild a channel or thread is in; ``None`` for a direct."""
    return self._adapter.guild(thread)