GitHub

discord_gateway

API reference for discord_gateway.

Discord's Gateway, one shard over a websocket (in Effect, dfx's DiscordGateway): it identifies or resumes, heartbeats, keeps the session in a ShardStateStore and hands each dispatch to the DispatchHook before storing its sequence, then to every subscriber of dispatch.

  • The websocket is DiscordWs; layer_ws builds it on a WebSocketConstructor (pyfect.socket.ws, extra websockets). It reconnects by itself, and a RECONNECT written to it drops the connection with close code 4000, which keeps the session for a RESUME.
  • A host built again with the same ShardStateStore sends RESUME, not IDENTIFY, and Discord sends what it missed.
  • A hook that fails or dies drops the connection without storing the dispatch's sequence, so the RESUME brings it back: after 1 second, doubling with every failure in a row up to 2 minutes. Whatever was already read from a dropped connection is skipped, unstored, until the next HELLO, and comes back with the RESUME too. A refused READY stores no session.
  • Op 7 (reconnect) resumes; op 9 (invalid session) that can't be resumed clears the stored session and identifies again. A heartbeat Discord did not acknowledge before the next one drops the connection.
  • Inbound frames are untrusted: one that is not a JSON object, or nests deeper than 64, is dropped.

Values

AttributeTypeDescription
DEFAULT_URLLiteral['wss://gateway.discord.gg'] = 'wss://gateway.discord.gg'

Discord's gateway; /?v=10&encoding=json is added to it, and to the resume URL Discord gives.

GUILDSLiteral[1]
GUILD_MESSAGESLiteral[512]
GUILD_MESSAGE_REACTIONSLiteral[1024]
DIRECT_MESSAGESLiteral[4096]
DIRECT_MESSAGE_REACTIONSLiteral[8192]
MESSAGE_CONTENTLiteral[32768]

A privileged intent: switch it on for the application in the developer portal.

DEFAULT_INTENTSLiteral[46593]

The intents the chat adapter reads.

RECONNECTReconnect
layer_wsLayer[DiscordWs, Never, WebSocketConstructor]

DiscordWs on the WebSocketConstructor in context.

Types

TypeDefinitionDescription
Hooktype Hook = Callable[[GatewayDispatch], Effect[None, object]]
GatewaySendtype GatewaySend = Mapping[str, object]

Classes

Functions

with_query

with_query(url) -> str

A gateway URL with the version and encoding the shard speaks.

ParameterTypeDescription
urlstr

Returns str

def with_query(url: str) -> str:
    """A gateway URL with the version and encoding the shard speaks."""
    base = url.split("?", 1)[0].rstrip("/")
    return f"{base}/?v=10&encoding=json"

layer

layer(*, token, intents=DEFAULT_INTENTS, shard=(0, 1), url=DEFAULT_URL) -> Layer[DiscordGateway, Never, DiscordWs]

One shard of the gateway, running until the layer's scope closes. It keeps its session in the ShardStateStore in context, or in memory, and runs the DispatchHook in context on each dispatch.

ParameterTypeDescription
tokenRedacted[str]
intentsint = DEFAULT_INTENTS
shardtuple[int, int] = (0, 1)
urlstr = DEFAULT_URL

Returns Layer[DiscordGateway, Never, DiscordWs]

def layer(
    *,
    token: Redacted[str],
    intents: int = DEFAULT_INTENTS,
    shard: tuple[int, int] = (0, 1),
    url: str = DEFAULT_URL,
) -> Layer[DiscordGateway, Never, DiscordWs]:
    """One shard of the gateway, running until the layer's scope closes. It
    keeps its session in the ``ShardStateStore`` in context, or in memory,
    and runs the ``DispatchHook`` in context on each dispatch."""
    if not (0 <= shard[0] < shard[1]):
        raise ValueError(f"shard must be (id, count) with 0 <= id < count, got {shard!r}")

    @fx.gen
    def build() -> Generator[Effect[Any, Never, Any], Any, DiscordGatewayService]:
        ws = yield from DiscordWs()
        found = yield from fx.service_option(ShardStateStore)
        stores: ShardStateStoreService = MemoryStateStore() if found is None else found.value
        hook = yield from DispatchHook()
        store = yield from fx.sync(lambda: stores.for_shard(shard))
        pubsub: PubSub[GatewayDispatch] = yield from PubSub[GatewayDispatch].unbounded()
        state = _Shard(
            token=token,
            intents=intents,
            shard=shard,
            url=url,
            store=store,
            hook=hook,
            pubsub=pubsub,
        )
        stored = yield from state._get()  # pyright: ignore[reportPrivateUsage]
        start = with_query(url if stored is None else stored.resume_url)
        state.conn = yield from ws.connect(start, fx.sync(state.on_connecting))
        conn = state.conn
        yield from conn.take.flat_map(state.on_payload).forever().fork_scoped()

        def stop(_: object) -> Effect[None]:
            beating = state.heartbeat
            return fx.void if beating is None else beating.interrupt()

        yield from fx.add_finalizer(stop)
        return DiscordGatewayService(pubsub)

    return _layer_effect(DiscordGateway, build)