Welcome to discord-ws!

discord-ws is a minimal, asynchronous Python wrapper for the Discord Gateway API.

Note

This library is not associated with discord-ws on PyPI, which is written by a different author. For now, there are no plans to release this package on PyPI.

Features

Usage

Assuming you have Python 3.11+ and Git installed, you can install this library with:

pip install git+https://github.com/thegamecracks/discord-ws

If you want to test out the library without writing a script, create a bot on Discord’s Developer Portal, copy your bot token, and try out the built-in CLI:

python -m discord_ws --standard-intents --zlib-stream

If you do want to write a script, import the library and use the Client class to establish a connection yourself:

import asyncio
import discord_ws

client = discord_ws.Client(
    token="Bot YOUR_TOKEN_HERE",
    intents=discord_ws.Intents.standard(),
)

@client.on_dispatch
async def handle_event(event: discord_ws.DispatchEvent):
    ...  # Do something with the events received from Discord

asyncio.run(client.run())

Resources

License

This project is written under the MIT license.

Client API Reference

class discord_ws.Client

Bases: object

The websocket client for connecting to the Discord Gateway.

Public Data Attributes:

gateway_url

The URL to use when connecting to the gateway.

token

The token to use for authenticating with the gateway.

intents

The gateway intents to use when identifying with the gateway.

user_agent

The user agent used when connecting to the gateway.

compress

If true, zlib transport compression will be enabled for data received by Discord.

large_threshold

The threshold where offline guild members are no longer sent, provided when identifying with the gateway.

presence

The presence for the client to use when identifying to the gateway.

shard

The shard identifier used for routing traffic.

Public Methods:

__init__(*, token, intents[, gateway_url, ...])

param token:

on_dispatch(func)

Sets the callback function to invoke when an event is dispatched.

run(*[, reconnect])

Begins and maintains a connection to the gateway.

set_presence(presence, *[, persistent])

Sets the bot's presence for the current connection, if any.

close()

Gracefully closes the current connection.


__init__(*, token: str, intents: Intents, gateway_url: str | None = None, user_agent: str | None = None, compress: bool = True, large_threshold: int | None = None, presence: GatewayPresenceUpdate | None = None, shard: Shard | None = None) None
Parameters:
  • token – The token to use for authenticating with the gateway.

  • intents – The gateway intents to use when identifying with the gateway.

  • gateway_url – The URL to use when connecting to the gateway. If this is not provided, it will automatically be fetched from the Get Gateway HTTP endpoint during Client.run().

  • user_agent – An optional user agent used when connecting to the gateway, overriding the library’s default.

  • compress – If true, zlib transport compression will be enabled for data received by Discord. This is distinct from payload compression which is not implemented by this library.

  • large_threshold – The threshold where offline guild members are no longer sent, provided when identifying with the gateway.

  • presence – An optional presence for the client to use when identifying to the gateway.

  • shard

    The shard identifier used for routing traffic.

    Added in version unreleased.

gateway_url: str | None

The URL to use when connecting to the gateway.

If this is not provided, it will automatically be fetched from the Get Gateway HTTP endpoint during Client.run().

token: str

The token to use for authenticating with the gateway.

intents: Intents

The gateway intents to use when identifying with the gateway.

user_agent: str

The user agent used when connecting to the gateway.

compress: bool

If true, zlib transport compression will be enabled for data received by Discord.

This is distinct from payload compression which is not implemented by this library.

large_threshold: int | None

The threshold where offline guild members are no longer sent, provided when identifying with the gateway.

presence: GatewayPresenceUpdate | None

The presence for the client to use when identifying to the gateway.

shard: Shard | None

The shard identifier used for routing traffic.

Added in version unreleased.

on_dispatch(func: Callable[[DispatchEvent], Any] | None) Callable[[DispatchEvent], Any] | None

Sets the callback function to invoke when an event is dispatched.

This can be a coroutine function or return an awaitable object.

async run(*, reconnect: bool = True) None

Begins and maintains a connection to the gateway.

Use the close() method to gracefully close the connection.

This method may raise an ExceptionGroup so it is recommended to handle errors using except* syntax.

Parameters:

reconnect – If True, this method will reconnect to Discord where possible.

Raises:
  • AuthenticationFailedError – The client’s token was incorrect. Can be raised even if reconnect is True.

  • ConnectionClosedError – An error caused the connection to close. Certain error codes can raise this even if reconnect is True.

  • GatewayReconnect – The gateway has asked us to reconnect. Only raised when reconnect is False.

  • HeartbeatLostError – The gateway failed to acknowledge our heartbeat. Only raised when reconnect is False.

  • PrivilegedIntentsError – The client requested privileged intents that were not enabled. Can be raised even if reconnect is True.

  • SessionInvalidated – The gateway has invalidated our session. Only raised when reconnect is False.

async set_presence(presence: GatewayPresenceUpdate, *, persistent: bool = True) None

Sets the bot’s presence for the current connection, if any.

Parameters:
  • presence – The payload to be sent over the gateway.

  • persistent – If true, this also sets the presence attribute used when reconnecting.

async close() None

Gracefully closes the current connection.

class discord_ws.DispatchEvent

Bases: TypedDict

Represents a dispatch event between the client and Discord gateway.

op: Literal[0]

The gateway opcode indicating the payload type.

d: Any

The data for the event.

s: int

The event’s sequence number used for heartbeating and session resumption.

t: str

The name of the event.

class discord_ws.Shard

Bases: NamedTuple

A pair indicating which shard a connection belongs to.

This determines which guilds a connection will receive events from, according to the formula shard_id = (guild_id >> 22) % num_shards. Shard ID 0 will also receive events from DMs.

shard_id doesn’t necessarily have to be unique, nor does num_shards have to be the same across all connections.

Added in version unreleased.

shard_id: int

The ID of the current connection. Must be within [0, num_shards).

num_shards: int

The total number of shards. Must be 1 or greater.

static __new__(_cls, shard_id: int, num_shards: int)

Create new instance of Shard(shard_id, num_shards)

Gateway Intents

class discord_ws.Intents

Bases: IntFlag

A set of event types that the client can ask to be received when identifying with the gateway.

GUILDS = 1

Corresponds with the following events:

  • GUILD_CREATE

  • GUILD_UPDATE

  • GUILD_DELETE

  • GUILD_ROLE_CREATE

  • GUILD_ROLE_UPDATE

  • GUILD_ROLE_DELETE

  • CHANNEL_CREATE

  • CHANNEL_UPDATE

  • CHANNEL_DELETE

  • CHANNEL_PINS_UPDATE

  • THREAD_CREATE

  • THREAD_UPDATE

  • THREAD_DELETE

  • THREAD_LIST_SYNC

  • THREAD_MEMBER_UPDATE

  • THREAD_MEMBERS_UPDATE *

  • STAGE_INSTANCE_CREATE

  • STAGE_INSTANCE_UPDATE

  • STAGE_INSTANCE_DELETE

GUILD_MEMBERS = 2

Corresponds with the following events:

  • GUILD_MEMBER_ADD

  • GUILD_MEMBER_UPDATE

  • GUILD_MEMBER_REMOVE

  • THREAD_MEMBERS_UPDATE *

GUILD_MODERATION = 4

Corresponds with the following events:

  • GUILD_AUDIT_LOG_ENTRY_CREATE

  • GUILD_BAN_ADD

  • GUILD_BAN_REMOVE

GUILD_EMOJIS_AND_STICKERS = 8

Corresponds with the following events:

  • GUILD_EMOJIS_UPDATE

  • GUILD_STICKERS_UPDATE

GUILD_INTEGRATIONS = 16

Corresponds with the following events:

  • GUILD_INTEGRATIONS_UPDATE

  • INTEGRATION_CREATE

  • INTEGRATION_UPDATE

  • INTEGRATION_DELETE

GUILD_WEBHOOKS = 32

Corresponds with the following events:

  • WEBHOOKS_UPDATE

GUILD_INVITES = 64

Corresponds with the following events:

  • INVITE_CREATE

  • INVITE_DELETE

GUILD_VOICE_STATES = 128

Corresponds with the following events:

  • VOICE_STATE_UPDATE

GUILD_PRESENCES = 256

Corresponds with the following events:

  • PRESENCE_UPDATE

GUILD_MESSAGES = 512

Corresponds with the following events:

  • MESSAGE_CREATE

  • MESSAGE_UPDATE

  • MESSAGE_DELETE

  • MESSAGE_DELETE_BULK

GUILD_MESSAGE_REACTIONS = 1024

Corresponds with the following events:

  • MESSAGE_REACTION_ADD

  • MESSAGE_REACTION_REMOVE

  • MESSAGE_REACTION_REMOVE_ALL

  • MESSAGE_REACTION_REMOVE_EMOJI

__new__(value)
GUILD_MESSAGE_TYPING = 2048

Corresponds with the following events:

  • TYPING_START

DIRECT_MESSAGES = 4096

Corresponds with the following events:

  • MESSAGE_CREATE

  • MESSAGE_UPDATE

  • MESSAGE_DELETE

  • CHANNEL_PINS_UPDATE

DIRECT_MESSAGE_REACTIONS = 8192

Corresponds with the following events:

  • MESSAGE_REACTION_ADD

  • MESSAGE_REACTION_REMOVE

  • MESSAGE_REACTION_REMOVE_ALL

  • MESSAGE_REACTION_REMOVE_EMOJI

DIRECT_MESSAGE_TYPING = 16384

Corresponds with the following events:

  • TYPING_START

MESSAGE_CONTENT = 32768

Provides data for events that contain message content fields.

GUILD_SCHEDULED_EVENTS = 65536

Corresponds with the following events:

  • GUILD_SCHEDULED_EVENT_CREATE

  • GUILD_SCHEDULED_EVENT_UPDATE

  • GUILD_SCHEDULED_EVENT_DELETE

  • GUILD_SCHEDULED_EVENT_USER_ADD

  • GUILD_SCHEDULED_EVENT_USER_REMOVE

AUTO_MODERATION_CONFIGURATION = 1048576

Corresponds with the following events:

  • AUTO_MODERATION_RULE_CREATE

  • AUTO_MODERATION_RULE_UPDATE

  • AUTO_MODERATION_RULE_DELETE

AUTO_MODERATION_EXECUTION = 2097152

Corresponds with the following events:

  • AUTO_MODERATION_ACTION_EXECUTION

classmethod all() Self

Returns a flag with all intents enabled.

classmethod privileged() Self

Returns a flag with all privileged intents enabled.

classmethod none() Self

Returns a flag with no intents enabled.

classmethod standard() Self

Returns a flag with all standard intents enabled.

Exceptions

class discord_ws.ClientError

Bases: Exception

The base class for exceptions raised by the client.

class discord_ws.ConnectionClosedError

Bases: ClientError, ConnectionError

An error caused the connection to close.

__init__(code: int, reason: str) None
code: int

The close code that triggered this exception.

reason: str

The reason provided for this closure.

class discord_ws.AuthenticationFailedError

Bases: ConnectionClosedError

The client failed to authenticate with Discord.

class discord_ws.PrivilegedIntentsError

Bases: ConnectionClosedError

The client requested privileged intents that were not enabled.

__init__(required_intents: Intents, *args, **kwargs) None
required_intents: Intents

The privileged intents requested by the client.

class discord_ws.GatewayInterrupt

Bases: ClientError

The client has been asked by the gateway to interrupt the current connection.

This exception and its subclasses are expected to be raised during normal operation, and should not impact the client’s ability to reconnect to the gateway.

class discord_ws.GatewayReconnect

Bases: GatewayInterrupt

The client has been asked to reconnect to the gateway.

This corresponds with the Reconnect (7) opcode.

__init__() None
class discord_ws.SessionInvalidated

Bases: GatewayInterrupt

The client’s session has been invalidated by the gateway.

This corresponds with the Invalid Session (9) opcode.

__init__(resumable: bool) None
resumable: bool

Indicates if the session can be resumed.

class discord_ws.HeartbeatLostError

Bases: ClientError

A heartbeat acknowledgement from the server was missed.

__init__() None