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 asmultipart/form-data, its JSON inpayload_jsonand the files asfiles[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 isRateLimitedwith theretry_afterwait. It sends nothing again by itself: the adapter retries what is safe to send again, and a 429 is, since nothing happened. - A
writeisuncertainonce 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#
| Attribute | Type | Description |
|---|---|---|
DEFAULT_BASE_URL | Literal['https://discord.com/api/v10'] = 'https://discord.com/api/v10' | Discord's API, version 10. |
USER_AGENT | str | Discord's required |
Types#
| Type | Definition | Description |
|---|---|---|
Method | type Method = Literal['GET', 'POST', 'PATCH', 'PUT', 'DELETE'] |
Classes#
Functions#
path#
path(*segments) -> strA 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.
| Parameter | Type | Description |
|---|---|---|
segments | str = () |
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) -> HttpClientRequestA request to {base_url}{route} without credentials: JSON, or
multipart when there are files.
| Parameter | Type | Description |
|---|---|---|
base_url | str | |
method | Method | |
route | str | |
body | object = None | |
files | Sequence[File] = () | |
query | Mapping[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 requestread_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.
| Parameter | Type | Description |
|---|---|---|
op | str | |
write | bool | |
sent | Effect[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.
| Parameter | Type | Description |
|---|---|---|
bot_token | Redacted[str] | |
base_url | str = 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 bodylayer#
layer(*, bot_token, base_url=DEFAULT_BASE_URL) -> Layer[DiscordRest, Never, HttpClient]The client as a layer.
| Parameter | Type | Description |
|---|---|---|
bot_token | Redacted[str] | |
base_url | str = 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))