Skip to main content

Client

The Client class represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
import discord

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
    print(f'Logged in as {client.user}')

client.run('token')

Constructor

Client

Client(
    *,
    max_messages: int | None = 1000,
    loop: asyncio.AbstractEventLoop | None = None,
    connector: aiohttp.BaseConnector | None = None,
    proxy: str | None = None,
    proxy_auth: aiohttp.BasicAuth | None = None,
    shard_id: int | None = None,
    shard_count: int | None = None,
    application_id: int | None = None,
    intents: Intents = Intents.default(),
    member_cache_flags: MemberCacheFlags | None = None,
    chunk_guilds_at_startup: bool = True,
    status: Status | None = None,
    activity: BaseActivity | None = None,
    allowed_mentions: AllowedMentions | None = None,
    heartbeat_timeout: float = 60.0,
    guild_ready_timeout: float = 2.0,
    assume_unsync_clock: bool = True,
    enable_debug_events: bool = False,
    cache_app_emojis: bool = False,
    cache_default_sounds: bool = True
)
max_messages
int | None
default:"1000"
The maximum number of messages to store in the internal message cache. Pass None to disable the message cache.
loop
asyncio.AbstractEventLoop | None
default:"None"
The event loop to use for asynchronous operations. Defaults to asyncio.get_event_loop().
connector
aiohttp.BaseConnector | None
default:"None"
The connector to use for connection pooling.
proxy
str | None
default:"None"
Proxy URL.
proxy_auth
aiohttp.BasicAuth | None
default:"None"
An object that represents proxy HTTP Basic Authorization.
shard_id
int | None
default:"None"
Integer starting at 0 and less than shard_count.
shard_count
int | None
default:"None"
The total number of shards.
application_id
int | None
default:"None"
The client’s application ID.
intents
Intents
default:"Intents.default()"
The intents that you want to enable for the session. This is a way of disabling and enabling certain gateway events from triggering and being sent.
member_cache_flags
MemberCacheFlags | None
default:"None"
Allows for finer control over how the library caches members. If not given, defaults to cache as much as possible with the currently selected intents.
chunk_guilds_at_startup
bool
default:"True"
Indicates if on_ready should be delayed to chunk all guilds at start-up if necessary. The default is True if Intents.members is True.
status
Status | None
default:"None"
A status to start your presence with upon logging on to Discord.
activity
BaseActivity | None
default:"None"
An activity to start your presence with upon logging on to Discord.
allowed_mentions
AllowedMentions | None
default:"None"
Control how the client handles mentions by default on every message sent.
heartbeat_timeout
float
default:"60.0"
The maximum numbers of seconds before timing out and restarting the WebSocket in the case of not receiving a HEARTBEAT_ACK.
guild_ready_timeout
float
default:"2.0"
The maximum number of seconds to wait for the GUILD_CREATE stream to end before preparing the member cache and firing READY.
assume_unsync_clock
bool
default:"True"
Whether to assume the system clock is unsynced. This applies to the ratelimit handling code.
enable_debug_events
bool
default:"False"
Whether to enable events that are useful only for debugging gateway related information (on_socket_raw_receive and on_socket_raw_send).
cache_app_emojis
bool
default:"False"
Whether to automatically fetch and cache the application’s emojis on startup and when fetching.
cache_default_sounds
bool
default:"True"
Whether to automatically fetch and cache the default soundboard sounds on startup.

Attributes

ws
DiscordWebSocket | None
The WebSocket gateway the client is currently connected to. Could be None.
loop
asyncio.AbstractEventLoop
The event loop that the client uses for asynchronous operations.
user
ClientUser | None
Represents the connected client. None if not logged in.
guilds
list[Guild]
The guilds that the connected client is a member of.
emojis
list[GuildEmoji | AppEmoji]
The emojis that the connected client has. Only includes application emojis if cache_app_emojis is True.
stickers
list[GuildSticker]
The stickers that the connected client has.
cached_messages
Sequence[Message]
Read-only list of messages the connected client has cached.
private_channels
list[PrivateChannel]
The private channels that the connected client is participating on. Returns only up to 128 most recent private channels.
voice_clients
list[VoiceProtocol]
Represents a list of voice connections.
application_id
int | None
The client’s application ID.
application_flags
ApplicationFlags
The client’s application flags.
latency
float
Measures latency between a HEARTBEAT and a HEARTBEAT_ACK in seconds. Returns nan if no websocket is present, or inf if no heartbeat has been received yet.
users
list[User]
Returns a list of all the users the bot can see.

Connection Methods

login

await client.login(token: str) -> None
Logs in the client with the specified credentials.
token
str
required
The authentication token. Do not prefix this token with anything as the library will do it for you.
Raises:
  • TypeError - The token was in invalid type.
  • LoginFailure - The wrong credentials are passed.
  • HTTPException - An unknown HTTP related error occurred.

connect

await client.connect(*, reconnect: bool = True) -> None
Creates a WebSocket connection and lets the WebSocket listen to messages from Discord. Control is not resumed until the WebSocket connection is terminated.
reconnect
bool
default:"True"
If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part.
Raises:
  • GatewayNotFound - The gateway to connect to Discord is not found.
  • ConnectionClosed - The WebSocket connection has been terminated.

close

await client.close() -> None
Closes the connection to Discord.

start

await client.start(token: str, *, reconnect: bool = True) -> None
A shorthand coroutine for login() + connect().
token
str
required
The authentication token.
reconnect
bool
default:"True"
Whether to attempt reconnecting.

run

client.run(*args, **kwargs) -> None
A blocking call that abstracts away the event loop initialisation from you. If you want more control over the event loop then this function should not be used.
This function must be the last function to call due to the fact that it is blocking. Registration of events or anything being called after this function call will not execute until it returns.

clear

client.clear() -> None
Clears the internal state of the bot. After this, the bot can be considered “re-opened”, i.e. is_closed() and is_ready() both return False along with the bot’s internal cache cleared.

Status Methods

is_closed

client.is_closed() -> bool
Indicates if the WebSocket connection is closed.Returns: bool - Whether the connection is closed.

is_ready

client.is_ready() -> bool
Specifies if the client’s internal cache is ready for use.Returns: bool - Whether the cache is ready.

is_ws_ratelimited

client.is_ws_ratelimited() -> bool
Whether the WebSocket is currently rate limited.Returns: bool - Whether the WebSocket is rate limited.

Presence Methods

change_presence

await client.change_presence(
    *,
    activity: BaseActivity | None = None,
    status: Status | None = None
) -> None
Changes the client’s presence.
activity
BaseActivity | None
default:"None"
The activity being done. None if no currently active activity is done.
status
Status | None
default:"None"
Indicates what status to change to. If None, then Status.online is used.
Example:
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)

Event Registration

event

@client.event
async def on_ready():
    pass
A decorator that registers an event to listen to. The events must be a coroutine.
This replaces any default handlers. Use listen() for adding additional handlers instead of event() unless default method replacement is intended.
Example:
@client.event
async def on_ready():
    print('Ready!')

listen

@client.listen(name: str = MISSING, once: bool = False)
A decorator that registers another function as an external event listener. This allows you to listen to multiple events from different places.
name
str
default:"function name"
The name of the event to listen for. Must start with on_.
once
bool
default:"False"
Whether the listener should only be called once.
Example:
@client.listen()
async def on_message(message):
    print('one')

@client.listen('on_message')
async def my_message(message):
    print('two')

@client.listen('on_ready', once=True)
async def on_ready():
    print('ready!')

add_listener

client.add_listener(func: Coroutine, name: str = MISSING) -> None
The non-decorator alternative to listen().
func
Coroutine
required
The function to call.
name
str
default:"func.__name__"
The name of the event to listen for. Defaults to func.__name__.

remove_listener

client.remove_listener(func: Coroutine, name: str = MISSING) -> None
Removes a listener from the pool of listeners.
func
Coroutine
required
The function that was used as a listener to remove.
name
str
default:"func.__name__"
The name of the event we want to remove.

wait_for

await client.wait_for(
    event: str,
    *,
    check: Callable[..., bool] | None = None,
    timeout: float | None = None
) -> Any
Waits for a WebSocket event to be dispatched. Returns the first event that meets the requirements.
event
str
required
The event name, similar to the event reference, but without the on_ prefix, to wait for.
check
Callable[..., bool] | None
default:"None"
A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.
timeout
float | None
default:"None"
The number of seconds to wait before timing out and raising asyncio.TimeoutError.
Example:
@client.event
async def on_message(message):
    if message.content.startswith('$greet'):
        channel = message.channel
        await channel.send('Say hello!')

        def check(m):
            return m.content == 'hello' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send(f'Hello {msg.author}!')

wait_until_ready

await client.wait_until_ready() -> None
Waits until the client’s internal cache is all ready.

Cache Getters

get_channel

client.get_channel(id: int) -> GuildChannel | Thread | PrivateChannel | None
Returns a channel or thread with the given ID.
id
int
required
The ID to search for.
Returns: The returned channel or None if not found.

get_guild

client.get_guild(id: int) -> Guild | None
Returns a guild with the given ID.
id
int
required
The ID to search for.
Returns: The guild or None if not found.

get_user

client.get_user(id: int) -> User | None
Returns a user with the given ID.
id
int
required
The ID to search for.
Returns: The user or None if not found.

get_emoji

client.get_emoji(id: int) -> GuildEmoji | AppEmoji | None
Returns an emoji with the given ID.
id
int
required
The ID to search for.
Returns: The custom emoji or None if not found.

get_sticker

client.get_sticker(id: int) -> GuildSticker | None
Returns a guild sticker with the given ID.
id
int
required
The ID to search for.
Returns: The sticker or None if not found.

get_all_channels

client.get_all_channels() -> Generator[GuildChannel]
A generator that retrieves every GuildChannel the client can ‘access’.Yields: GuildChannel - A channel the client can ‘access’.

get_all_members

client.get_all_members() -> Generator[Member]
Returns a generator with every Member the client can see.Yields: Member - A member the client can see.

API Fetch Methods

fetch_guild

await client.fetch_guild(guild_id: int, *, with_counts: bool = True) -> Guild
Retrieves a Guild from an ID via API call.
guild_id
int
required
The guild’s ID to fetch from.
with_counts
bool
default:"True"
Whether to include count information in the guild.
Returns: The guild from the ID.

fetch_user

await client.fetch_user(user_id: int) -> User
Retrieves a User based on their ID via API call.
user_id
int
required
The user’s ID to fetch from.
Returns: The user you requested.

fetch_channel

await client.fetch_channel(channel_id: int) -> GuildChannel | PrivateChannel | Thread
Retrieves a channel with the specified ID via API call.
channel_id
int
required
The channel ID to fetch.
Returns: The channel from the ID.

fetch_guilds

client.fetch_guilds(
    *,
    limit: int | None = 100,
    before: SnowflakeTime = None,
    after: SnowflakeTime = None,
    with_counts: bool = True
) -> GuildIterator
Retrieves an AsyncIterator that enables receiving your guilds.
limit
int | None
default:"100"
The number of guilds to retrieve. If None, retrieves every guild.
before
Snowflake | datetime
default:"None"
Retrieves guilds before this date or object.
after
Snowflake | datetime
default:"None"
Retrieve guilds after this date or object.
with_counts
bool
default:"True"
Whether to include member count information in guilds.
Example:
async for guild in client.fetch_guilds(limit=150):
    print(guild.name)

fetch_invite

await client.fetch_invite(
    url: Invite | str,
    *,
    with_counts: bool = True,
    with_expiration: bool = True,
    event_id: int | None = None
) -> Invite
Gets an Invite from a discord.gg URL or ID.
url
Invite | str
required
The Discord invite ID or URL (must be a discord.gg URL).
with_counts
bool
default:"True"
Whether to include count information in the invite.
with_expiration
bool
default:"True"
Whether to include the expiration date of the invite.
event_id
int | None
default:"None"
The ID of the scheduled event to be associated with the event.
Returns: The invite from the URL/ID.

application_info

await client.application_info() -> AppInfo
Retrieves the bot’s application information.Returns: The bot’s application information.

Error Handlers

on_error

async def on_error(event_method: str, *args, **kwargs) -> None
The default error handler provided by the client. By default, this prints to sys.stderr however it could be overridden to have a different implementation.
event_method
str
required
The name of the event that raised the exception.
args
Any
The positional arguments for the event.
kwargs
Any
The keyword arguments for the event.

Hooks

before_identify_hook

async def before_identify_hook(
    shard_id: int | None,
    *,
    initial: bool = False
) -> None
A hook that is called before IDENTIFYing a session. The default implementation sleeps for 5 seconds.
shard_id
int | None
required
The shard ID that requested being IDENTIFY’d.
initial
bool
default:"False"
Whether this IDENTIFY is the first initial IDENTIFY.

Build docs developers (and LLMs) love