GitHub

discord_rest

API reference for discord_rest.

The minimal Discord REST client the adapter is built on (in Effect, dfx's DiscordREST). It is public, so a consumer can call a route the adapter has no op for, with the same error mapping and the same rule for writes.

  • Every request carries the bot token and Discord's User-Agent; JSON goes as JSON and a message with files as multipart/form-data, its JSON in payload_json and the files as files[n].
  • A non-2xx answer fails with the reason for Discord's JSON error code, or for the status when there is none; a 429 is RateLimited with the retry_after wait. It sends nothing again by itself: the adapter retries what is safe to send again, and a 429 is, since nothing happened.
  • A write is uncertain once the request left: a transport failure, a server error or an unreadable answer may have landed.
  • Path segments are percent-encoded, so an id from a payload can't reach another route.

Re-exports

Values

AttributeTypeDescription
DEFAULT_BASE_URLLiteral['https://discord.com/api/v10'] = 'https://discord.com/api/v10'

Discord's API, version 10.

USER_AGENTstr

Discord's required User-Agent form: DiscordBot ($url, $version).

Types

TypeDefinitionDescription
Methodtype Method = Literal['GET', 'POST', 'PATCH', 'PUT', 'DELETE']

Classes

Functions

path

path(*segments) -> str

A route from its segments, each percent-encoded: path("channels", id, "messages") is /channels/{id}/messages. A segment that is empty, . or .. raises ValueError: a URL parser would drop it or step up a level, even percent-encoded.

ParameterTypeDescription
segmentsstr = ()

Returns str

def path(*segments: str) -> str:
    """A route from its segments, each percent-encoded: ``path("channels",
    id, "messages")`` is ``/channels/{id}/messages``. A segment that is empty,
    ``.`` or ``..`` raises ``ValueError``: a URL parser would drop it or step
    up a level, even percent-encoded."""
    for segment in segments:
        if segment in ("", ".", ".."):
            raise ValueError(f"not a path segment: {segment!r}")
    return "".join("/" + quote(segment, safe="@") for segment in segments)

build_request

build_request(base_url, method, route, body=None, files=(), query=None) -> HttpClientRequest

A request to {base_url}{route} without credentials: JSON, or multipart when there are files.

ParameterTypeDescription
base_urlstr
methodMethod
routestr
bodyobject = None
filesSequence[File] = ()
queryMapping[str, str] | None = None

Returns HttpClientRequest

def build_request(  # noqa: PLR0917
    base_url: str,
    method: Method,
    route: str,
    body: object = None,
    files: Sequence[File] = (),
    query: Mapping[str, str] | None = None,
) -> HttpClientRequest:
    """A request to ``{base_url}{route}`` without credentials: JSON, or
    multipart when there are files."""
    request = http_request.make(method, base_url + route).set_header("User-Agent", USER_AGENT)
    if query:
        request = request.set_url_params(dict(query))
    if files:
        form = http_body.FormData((("payload_json", stringify(body)),))
        for i, file in enumerate(files):
            form = form.append(
                f"files[{i}]", http_body.File(file.content, file.name, file.content_type)
            )
        return request.body_form_data(form)
    if body is not None:
        return request.body_text(stringify(body), "application/json")
    return request

read_answer

read_answer(op, write, sent) -> Effect[Json, ChatError]

Discord's answer to sent: its JSON (None for an empty body), or the ChatError of op for a failure.

ParameterTypeDescription
opstr
writebool
sentEffect[HttpClientResponse, HttpClientError]

Returns Effect[Json, ChatError]

def read_answer(
    op: str, write: bool, sent: Effect[HttpClientResponse, HttpClientError]
) -> Effect[Json, ChatError]:
    """Discord's answer to ``sent``: its JSON (``None`` for an empty body), or
    the ``ChatError`` of ``op`` for a failure."""
    require_effect(sent, "sent")

    def fail(reason: AnyReason) -> Effect[Never, ChatError]:
        return fx.fail(_errors.chat_error(op, reason))

    def answered(response: HttpClientResponse) -> Effect[Json, ChatError]:
        def read(text: str) -> Effect[Json, ChatError]:
            data = None if text == "" else _json.parse(text)
            if not 200 <= response.status < 300:
                return fail(_errors.reason_for_response(response.status, data, write=write))
            if text != "" and data is None and text.strip() != "null":
                return fail(_errors.invalid_response(write, "invalid_json"))
            return fx.succeed(cast("Json", data))

        return response.text.catch_all(
            lambda error: fail(_errors.transport(write, type(error.reason).__name__, error))
        ).flat_map(read)

    return sent.catch_all(
        lambda error: fail(_errors.transport(write, type(error.reason).__name__, error))
    ).flat_map(answered)

make

make(*, bot_token, base_url=DEFAULT_BASE_URL) -> Effect[DiscordRestService, Never, HttpClient]

Builds the client from an HttpClient and a bot token.

ParameterTypeDescription
bot_tokenRedacted[str]
base_urlstr = DEFAULT_BASE_URL

Returns Effect[DiscordRestService, Never, HttpClient]

def make(
    *, bot_token: Redacted[str], base_url: str = DEFAULT_BASE_URL
) -> Effect[DiscordRestService, Never, HttpClient]:
    """Builds the client from an ``HttpClient`` and a bot token."""

    @fx.gen
    def body() -> Generator[Effect[Any, Never, HttpClient], Any, DiscordRestService]:
        http = yield from HttpClient()
        return DiscordRestService(http, bot_token, base_url)

    return body

layer

layer(*, bot_token, base_url=DEFAULT_BASE_URL) -> Layer[DiscordRest, Never, HttpClient]

The client as a layer.

ParameterTypeDescription
bot_tokenRedacted[str]
base_urlstr = DEFAULT_BASE_URL

Returns Layer[DiscordRest, Never, HttpClient]

def layer(
    *, bot_token: Redacted[str], base_url: str = DEFAULT_BASE_URL
) -> Layer[DiscordRest, Never, HttpClient]:
    """The client as a layer."""
    return _layer_effect(DiscordRest, make(bot_token=bot_token, base_url=base_url))