Client

ACord’s built in client enables rapid development, but this doesn’t mean you can’t create your own!

Example

from acord import Client, Message, Intents
from typing import Any

class MyClient(Client):
    async def on_message_create(self, message: Message) -> Any:
        if message.content == ".ping":
            return message.reply(content="Pong!")

if __name__ == "__main__":
    client = MyClient(token="My token", intents=Intents.ALL)
    client.run()

Client

class acord.Client(*, token: typing.Optional[str] = None, dispatch_on_recv: bool = False, intents: typing.Optional[typing.Union[acord.bases.flags.intents.Intents, int]] = 0, presence: typing.Optional[acord.bases.presence.Presence] = None, loop: typing.Optional[asyncio.events.AbstractEventLoop] = <_UnixSelectorEventLoop running=False closed=False debug=False>, encoding: typing.Optional[str] = 'JSON', compress: typing.Optional[bool] = False, cache: acord.client.caches.cache.Cache = DefaultCache(sections={'messages': {}, 'users': <WeakValueDictionary>, 'guilds': {}, 'channels': {}, 'stage_instances': {}}), gateway_ratelimiter: acord.client.ratelimiter.GatewayRatelimiter = DefaultGatewayRatelimiter(max_requests=(117, 60), current_requests={}, refreshed_at=1647170145.1627147, tasks={}, shards={}))[source]

Client for interacting with the discord API

Parameters
  • loop (AbstractEventLoop) – An existing loop to run the client off of

  • token (str) – Your API Token which can be generated at the developer portal

  • intents (Union[Intents, int]) – Intents to be passed through when connecting to gateway, defaults to 0

  • presence (Presence) – Presence to be sent in the identity packet

  • encoding (str) – Any of ETF and JSON are allowed to be chosen, controls data recieved by discord, defaults to False.

  • compress (bool) – Whether to read compressed stream when receiving requests, defaults to False

  • dispatch_on_recv (bool) – Whether on_socket_recv should be dispatched

  • cache (Cache) –

    Cache for the client to use

    New in version 0.2.3a0.

  • gateway_ratelimiter (GatewayRatelimiter) –

    Gateway ratelimiter for client to use

    New in version 0.2.3a0.

loop

Loop client uses

Type

AbstractEventLoop

token

Token set when initialising class

Type

str

dispatch_on_recv

Whether the on_socket_recv should be dispatched

Type

bool

intents

Intents set when intialising class

Type

Union[Intents, int]

presence

Presence to be sent in the identity packet

Type

Presence

encoding

Encoding set when initialising class

Type

str

compress

Whether to read compressed stream when receiving requests

Type

bool

session_id

Session ID recieved when connecting to gateway

Type

str

gateway_version

Selected gateway version, available after connecting to gateway. In form v[0-9].

Type

str

user

Client user object

Type

User

application_commands

Mapping of registered application commands

Type

Dict[str, List[UDAppCommand]]

shards

Mapping of shards client is handling

New in version 0.2.3a0.

Type

Dict[int, Shard]

cache

Cache of gateway objects, recommended to fetch using built in methods, e.g. Client.get_user().

New in version 0.2.3a0.

Type

Cache

gateway_ratelimiter

Gateway ratelimiter for client to use, we recommend not playing around with this as it may lead to unexpected errors

New in version 0.2.3a0.

Type

GatewayRatelimiter

max_concurrency

Number of identity requests client is allowed per 5 seconds

New in version 0.2.3a0.

Changed in version 0.2.3a0: Name changed from MAX_CONC to max_concurrency

Type

int

num_shards

Number of shards client is using, if None it means client has not been ran yet.

Note

This value can be overwritten but only before client is ran. We dont recommend you do but oh well.

New in version 0.2.3a0.

Type

Optional[int]

guilds

List of guilds client has access to

Type

List[Guilds]

rest

An instance of the Rest API object

Type

RestApi

async bulk_update_global_app_commands(commands: List[acord.ext.application_commands.base.UDAppCommand]) None[source]

This function is a coroutine.

Updates global application commands in bulk

Parameters

commands (List[UDAppCommand]) – List of application commands to update

async bulk_update_guild_app_commands(guild_id: acord.models.Snowflake, commands: List[acord.ext.application_commands.base.UDAppCommand]) None[source]

This function is a coroutine.

Updates application commands for a guild in bulk

Parameters
  • guild_id (Snowflake) – ID of target guild

  • commands (List[UDAppCommand]) – List of application commands to update

async create_application_command(command: acord.ext.application_commands.base.UDAppCommand, *, guild_ids: Optional[List[int]] = None, extend: bool = True) Union[acord.ext.application_commands.base.ApplicationCommand, List[acord.ext.application_commands.base.ApplicationCommand]][source]

This function is a coroutine.

Creates an application command from a UDAppCommand class.

Note

It can take up to an hour for discord to process the command!

:param same as Client.register_application_command():

async create_stage_instance(*, reason: Optional[str] = None, **data) acord.models.channels.stage.StageInstance[source]

This function is a coroutine.

Creates a stage instance

Parameters
  • channel_id (Snowflake) – ID of channel to create stage instance, channel type must be ChannelTypes.GUILD_STAGE_VOICE

  • topic (str) – The topic of the Stage instance (1-120 characters)

  • privacy_level (StagePrivacyLevel) – The privacy level of the Stage instance (default GUILD_ONLY)

async disconnect()[source]

This function is a coroutine.

Disconnects client from discord, ends:

  • Client spawned sessions

  • Shards

  • Voice Connections

dispatch(event_name: str, *args, **kwargs) None[source]

Dispatch a registered event

Parameters
  • event_name (str) – Name of event

  • *args – Additional args or kwargs to be passed through

  • **kwargs – Additional args or kwargs to be passed through

async fetch_channel(channel_id: int) Optional[acord.models.channels.base.Channel][source]

Fetches channel from API and caches it

async fetch_glob_app_command(command_id: acord.models.Snowflake) acord.ext.application_commands.base.ApplicationCommand[source]

This function is a coroutine.

Fetches a global application command registered by the client

Parameters

command_id (Snowflake) – ID of command to fetch

async fetch_glob_app_commands() AsyncIterator[acord.ext.application_commands.base.ApplicationCommand][source]

This function is a coroutine.

Fetches all global application commands registered by the client

async fetch_guild(guild_id: int, *, with_counts: bool = False) Optional[acord.models.guild.Guild][source]

Fetches guild from API and caches it.

Note

If with_counts is set to True, it will allow fields approximate_presence_count, approximate_member_count to be used.

async fetch_message(channel_id: int, message_id: int) Optional[acord.models.message.Message][source]

Fetches message from API and caches it

async fetch_user(user_id: int) Optional[acord.models.user.User][source]

Fetches user from API and caches it

get_channel(channel_id: int) Optional[acord.models.channels.base.Channel][source]

Returns the channel stored in the internal cache, may be outdated

get_guild(guild_id: int) Optional[acord.models.guild.Guild][source]

Returns the guild stored in the internal cache, may be outdated

get_message(channel_id: int, message_id: int) Optional[acord.models.message.Message][source]

Returns the message stored in the internal cache, may be outdated

get_shard(guild_id: acord.models.Snowflake) Optional[acord.client.shard.Shard][source]

Gets a shard from Client.shards using a guild id

Parameters

guild_id (Snowflake) – Guild ID to use

get_user(user_id: int) Optional[acord.models.user.User][source]

Returns the user stored in the internal cache, may be outdated

on(name: str, *, once: bool = False) Optional[Callable[[...], Coroutine]][source]

Register an event to be dispatched on call.

This is a decorator, if you do not want to use the decorator consider trying:

from acord import Client
from xyz import some_event_handler

client = Client(...)
client.on("message")(some_event_handler)
Parameters
  • name (str) – Name of event, consider checking out all events

  • once (bool) – Whether the event should be ran once before being removed.

  • check (Callable[…, bool]) – Check to be ran before dispatching event

on_error(event_method, task: Optional[_asyncio.Task] = None, err=None)[source]

This function is a coroutine.

Built in base error handler for events

register_application_command(command: acord.ext.application_commands.base.UDAppCommand, *, guild_ids: Optional[List[int]] = None, extend: bool = True) None[source]

Registers application command internally before client is ran, after client is ran this method is redundant. Consider using Client.create_application_command().

Parameters
  • command (UDAppCommand) –

    Note

    UDAppCommand represents any class which inherits it, this includes SlashBase.

    Command to register internally, to be dispatched.

  • guild_ids (Union[List[int], None]) –

    Additional guild IDs to restrict command to,

    if value is set to:
    • None: Reads from class (Default option)

    • [] (Empty List): Makes it global

    Note

    If final value is false, command will be registered globally

  • extend (bool) – Whether to extend current guild ids from the command class

run(token: Optional[str] = None, reconnect: bool = True, update_app_commands: bool = True, exclude_app_cmds: set = {}, asyncio_debug: bool = False)[source]

Runs client, loop blocking.

Parameters
  • token (str) – Token to log into discord with, if Client.token is not None it will be used as a fallback, just in case this token fails

  • reconnect (bool) – Whether to reconnect it first connection fails, defaults to True.

  • update_add_commands (bool) – Whether to update app commands, in bulk.

  • exclude_app_cmds (set) – A set of app names to stop being updated/created

  • asyncio_debug (bool) – Whether to enable debugging on the current loop.

async shard_handler(*ready_scripts) None[source]

This function is a coroutine.

Default shard handler, doesn’t do much except intiate shards and waits till all have been disconnected.

wait_for(event: str, *, check: Optional[Callable[[...], bool]] = None, timeout: Optional[int] = None) Callable[[...], Coroutine][source]

This function is a coroutine.

Wait for a specific gateway event to occur.

Examples

# Simple Greeting
data = Client.wait_for(
    "message",
    check=lambda message: message.content == "Hello",
    timeout=30.0
)
message = data[0]

return message.reply(content=f"Hello, {message.author}")
Parameters
  • event (str) – Gateway event to wait for.

  • check (Callable[…, bool]) – Validate the gateway event recieved

  • timeout (int) – Time to wait for event to be recieved

Shard

class acord.Shard(url: str, shard_id: int, num_shards: int, client: typing.Any, handler: typing.Callable[[...], typing.Coroutine[typing.Any, typing.Any, typing.Any]] = <function handle_websocket>)[source]

Representation of a discord shard, which is basically a connection to the gateway.

Warning

Shards are enabled by default but only Shard 0 will receive dms

Note

When providing a handler, it must take care of reading the websocket, else see the implementation below.

Working with a shard

shard = Shard("url", shard_id, num_shards, client)

# Connect
await shard.connect()
await shard.receive_hello()
await shard.send_identity()

await shard.wait_until_ready()

# Deal with messages
async for message in shard.ws:
    ...
Parameters
  • url (str) – Gateway URL

  • shard_id (int) – ID of shard

  • num_shards (int) – Total number of shards client uses

  • handler (Callable[..., Coroutine[Any, Any, Any]]) – A handler to overwrite the default handler

  • client (Client) – Client this shard is attached to.

url

Gateway url

Type

str

shard_id

ID of shard

Type

int

num_shards

Total number of shards client has

Type

int

client

Client shard is attached to

Type

Client

session

Session being used to make requests

Type

ClientSession

handler

Handler to be used when Shard.listen() is called

Type

Callable[…, Coroutine[Any, Any, Any]]

ws

WS connected to Shard.url, only available after Shard.connect() is called

Type

ClientWebSocketResponse

ready_event

An event object which is set after shard receives READY

Type

asyncio.Event

loop

Loop that the shard is using

Type

asyncio.AbstractEventLoop

sequence

Shard sequence, value should be changed by user else unexpected errors may occur

Type

int

session_id

Session ID, used for resuming. Dont change it.

Type

str

gateway_version

Gateway version client is using

Type

str

resuming

Whether the shard is in a resuming state

Type

bool

ratelimit_key

Ratelimit key used for bucket ratelimiting gateway requests

Type

int

async change_presence(presence: acord.bases.presence.Presence) None[source]

This function is a coroutine.

Changes client presence

Parameters

presence (Presence) – New presence for client, You may want to checkout the guide for presences. Which can be found here.

async connect(**kwds) None[source]

This function is a coroutine.

Connects to gateway

Parameters
  • token (str) – Token to be used for identity packet

  • **kwds – Additional kwargs to be passed through ws_connect

async disconnect()[source]

This function is a coroutine.

Disconnects from this shard

listen(**kwds)[source]

Generates task using handler, this task is automatically terminated by Shard.disconnect().

Note

Any kwargs you pass through are sent to the handler

async receive_hello()[source]

This function is a coroutine.

Receives the hello packet from discord and begins heartbeating, should be called directly after Shard.connect()

async resume(*, restart: bool = False)[source]

This function is a coroutine.

Sends a resume packet to discord

Parameters

restart (bool) – Whether to restart the session

async send_identity(token: str, intents: int, presence: Optional[acord.bases.presence.Presence] = None) None[source]

This function is a coroutine.

Sends an identity packet to discord

Parameters
  • token (str) – Bot token

  • intents (int) – Intents to send

  • presence (Presence) – An optional presence to update the client with

async update_voice_state(**data) None[source]

This function is a coroutine.

Updates client voice state

Parameters
  • guild_id (Snowflake) – id of the guild

  • channel_id (Snowflake) – id of the voice channel client wants to join (None if disconnecting)

  • self_mute (bool) – is the client muted

  • self_deaf (bool) – is the client deafened

async wait_until_ready()[source]

This function is a coroutine.

Blocks until the shard is ready