0
# Core Client Functionality
1
2
The foundation of py-cord's Discord integration, providing client classes for connecting to Discord, managing bot instances, handling events, and auto-sharding for large applications.
3
4
## Capabilities
5
6
### Base Client Classes
7
8
Core client classes that handle the connection to Discord's gateway and provide the foundation for all Discord interactions.
9
10
```python { .api }
11
class Client:
12
"""
13
Represents a client connection to Discord.
14
15
Parameters:
16
- loop: Optional[asyncio.AbstractEventLoop] - Event loop to use (default None uses current loop)
17
- **options: Any - Additional options including:
18
- intents: Intents - The intents to use for the client
19
- max_messages: Optional[int] - Maximum messages in cache (default 1000, None disables)
20
- heartbeat_timeout: float - Gateway heartbeat timeout seconds (default 60.0)
21
- guild_ready_timeout: float - Guild ready timeout seconds (default 2.0)
22
- assume_unsync_clock: bool - Assume unsync clock (default True)
23
- enable_debug_events: bool - Enable debug gateway events (default False)
24
- shard_id: Optional[int] - Shard ID for this client
25
- shard_count: Optional[int] - Total number of shards
26
- connector: Optional[aiohttp.BaseConnector] - HTTP connector
27
- proxy: Optional[str] - Proxy URL
28
- proxy_auth: Optional[aiohttp.BasicAuth] - Proxy authentication
29
"""
30
31
def __init__(
32
self,
33
*,
34
loop: Optional[asyncio.AbstractEventLoop] = None,
35
**options: Any
36
): ...
37
38
async def start(self, token: str) -> None:
39
"""Start the client with the given bot token."""
40
41
async def close(self) -> None:
42
"""Close the client connection."""
43
44
def run(self, token: str, *, reconnect: bool = True) -> None:
45
"""Run the client. This is a blocking call that starts the event loop."""
46
47
def event(self, coro) -> Callable:
48
"""Decorator that registers an event handler."""
49
50
async def login(self, token: str) -> None:
51
"""Login to Discord with the given token."""
52
53
async def connect(self, *, reconnect: bool = True) -> None:
54
"""Connect to the Discord gateway."""
55
56
def is_ready(self) -> bool:
57
"""Return True if the client is ready."""
58
59
def is_closed(self) -> bool:
60
"""Return True if the client connection is closed."""
61
62
@property
63
def latency(self) -> float:
64
"""The latency between a HEARTBEAT and HEARTBEAT_ACK in seconds."""
65
66
@property
67
def user(self) -> Optional[ClientUser]:
68
"""The client user (bot account)."""
69
70
@property
71
def guilds(self) -> List[Guild]:
72
"""A list of guilds the client can see."""
73
74
@property
75
def users(self) -> List[User]:
76
"""A list of users the client can see."""
77
78
def get_guild(self, id: int) -> Optional[Guild]:
79
"""Get a guild by ID."""
80
81
def get_user(self, id: int) -> Optional[User]:
82
"""Get a user by ID."""
83
84
def get_channel(self, id: int) -> Optional[Union[GuildChannel, PrivateChannel]]:
85
"""Get a channel by ID."""
86
87
async def fetch_guild(self, guild_id: int, *, with_counts: bool = True) -> Guild:
88
"""Fetch a guild from the API."""
89
90
async def fetch_user(self, user_id: int) -> User:
91
"""Fetch a user from the API."""
92
93
async def fetch_channel(self, channel_id: int) -> Union[GuildChannel, PrivateChannel]:
94
"""Fetch a channel from the API."""
95
96
class ClientUser(User):
97
"""
98
Represents the client user (the bot itself).
99
"""
100
101
async def edit(self, *, username: str = None, avatar: bytes = None) -> ClientUser:
102
"""
103
Edit the client user.
104
105
Parameters:
106
- username: str - New username
107
- avatar: bytes - New avatar image data
108
"""
109
110
class AutoShardedClient(Client):
111
"""
112
A client that automatically shards the bot across multiple shards.
113
114
Parameters:
115
- shard_count: Optional[int] - Number of shards to use (None for automatic)
116
- shard_ids: Optional[List[int]] - Specific shard IDs to use
117
"""
118
119
def __init__(
120
self,
121
*,
122
shard_count: Optional[int] = None,
123
shard_ids: Optional[List[int]] = None,
124
**options
125
): ...
126
127
@property
128
def shard_count(self) -> Optional[int]:
129
"""The number of shards this client is using."""
130
131
@property
132
def shards(self) -> Dict[int, ShardInfo]:
133
"""A mapping of shard IDs to their info."""
134
```
135
136
### Bot Classes for Application Commands
137
138
Enhanced client classes specifically designed for building bots with application command support (slash commands, user commands, message commands).
139
140
```python { .api }
141
class Bot(Client):
142
"""
143
A subclass of Client that provides application command support.
144
145
Parameters:
146
- description: Optional[str] - Bot description (default None)
147
- **options: Any - Additional options including all Client options plus:
148
- debug_guilds: Optional[List[int]] - Guild IDs for debugging commands
149
- owner_id: Optional[int] - Bot owner user ID
150
- owner_ids: Optional[Set[int]] - Set of bot owner user IDs
151
- auto_sync_commands: bool - Whether to automatically sync commands (default True)
152
- default_command_contexts: Collection[InteractionContextType] - Default command contexts
153
- default_command_integration_types: Collection[IntegrationType] - Default integration types
154
"""
155
156
def __init__(
157
self,
158
description: Optional[str] = None,
159
*,
160
**options: Any
161
): ...
162
163
def slash_command(
164
self,
165
*,
166
name: str = None,
167
description: str = None,
168
guild_ids: List[int] = None,
169
**kwargs
170
) -> Callable:
171
"""
172
Decorator for creating slash commands.
173
174
Parameters:
175
- name: str - Command name (defaults to function name)
176
- description: str - Command description
177
- guild_ids: List[int] - Guilds where this command is available
178
"""
179
180
def user_command(
181
self,
182
*,
183
name: str = None,
184
guild_ids: List[int] = None,
185
**kwargs
186
) -> Callable:
187
"""
188
Decorator for creating user context menu commands.
189
190
Parameters:
191
- name: str - Command name (defaults to function name)
192
- guild_ids: List[int] - Guilds where this command is available
193
"""
194
195
def message_command(
196
self,
197
*,
198
name: str = None,
199
guild_ids: List[int] = None,
200
**kwargs
201
) -> Callable:
202
"""
203
Decorator for creating message context menu commands.
204
205
Parameters:
206
- name: str - Command name (defaults to function name)
207
- guild_ids: List[int] - Guilds where this command is available
208
"""
209
210
async def sync_commands(
211
self,
212
*,
213
commands: List[ApplicationCommand] = None,
214
guild_ids: List[int] = None,
215
register_guild_commands: bool = True,
216
check_guilds: List[int] = None,
217
delete_existing: bool = True,
218
force: bool = False
219
) -> None:
220
"""
221
Sync application commands with Discord.
222
223
Parameters:
224
- commands: List[ApplicationCommand] - Specific commands to sync
225
- guild_ids: List[int] - Specific guilds to sync to
226
- register_guild_commands: bool - Whether to register guild commands
227
- check_guilds: List[int] - Guilds to check for existing commands
228
- delete_existing: bool - Whether to delete existing commands not in the list
229
- force: bool - Force sync even if commands haven't changed
230
"""
231
232
@property
233
def pending_application_commands(self) -> List[ApplicationCommand]:
234
"""List of application commands pending sync."""
235
236
def get_application_command(
237
self,
238
name: str,
239
*,
240
guild_id: int = None,
241
type: ApplicationCommandType = None
242
) -> Optional[ApplicationCommand]:
243
"""Get an application command by name."""
244
245
async def is_owner(self, user: Union[User, Member]) -> bool:
246
"""Check if a user is the bot owner."""
247
248
class AutoShardedBot(Bot, AutoShardedClient):
249
"""
250
A Bot that automatically shards across multiple processes.
251
"""
252
pass
253
```
254
255
### Connection Management and Events
256
257
Event system for handling Discord gateway events and managing the bot's lifecycle.
258
259
```python { .api }
260
# Event Decorators and Registration
261
def event(coro) -> Callable:
262
"""
263
Decorator that registers a coroutine as an event handler.
264
265
Example:
266
@bot.event
267
async def on_ready():
268
print(f'{bot.user} is ready!')
269
"""
270
271
def listen(name: str = None) -> Callable:
272
"""
273
Decorator that registers a listener for a specific event.
274
275
Parameters:
276
- name: str - Event name to listen for
277
"""
278
279
# Core Events
280
async def on_ready() -> None:
281
"""Called when the client has successfully connected and is ready."""
282
283
async def on_resumed() -> None:
284
"""Called when the client has resumed a session."""
285
286
async def on_connect() -> None:
287
"""Called when the client has successfully connected to Discord."""
288
289
async def on_disconnect() -> None:
290
"""Called when the client has disconnected from Discord."""
291
292
async def on_shard_connect(shard_id: int) -> None:
293
"""Called when a shard connects."""
294
295
async def on_shard_disconnect(shard_id: int) -> None:
296
"""Called when a shard disconnects."""
297
298
async def on_shard_ready(shard_id: int) -> None:
299
"""Called when a shard is ready."""
300
301
async def on_shard_resumed(shard_id: int) -> None:
302
"""Called when a shard resumes."""
303
304
# Guild Events
305
async def on_guild_join(guild: Guild) -> None:
306
"""Called when the bot joins a guild."""
307
308
async def on_guild_remove(guild: Guild) -> None:
309
"""Called when the bot is removed from a guild."""
310
311
async def on_guild_update(before: Guild, after: Guild) -> None:
312
"""Called when a guild is updated."""
313
314
async def on_guild_available(guild: Guild) -> None:
315
"""Called when a guild becomes available."""
316
317
async def on_guild_unavailable(guild: Guild) -> None:
318
"""Called when a guild becomes unavailable."""
319
320
# Message Events
321
async def on_message(message: Message) -> None:
322
"""Called when a message is created."""
323
324
async def on_message_edit(before: Message, after: Message) -> None:
325
"""Called when a message is edited."""
326
327
async def on_message_delete(message: Message) -> None:
328
"""Called when a message is deleted."""
329
330
async def on_raw_message_edit(payload: RawMessageUpdateEvent) -> None:
331
"""Called when a message is edited (raw payload)."""
332
333
async def on_raw_message_delete(payload: RawMessageDeleteEvent) -> None:
334
"""Called when a message is deleted (raw payload)."""
335
336
# Member Events
337
async def on_member_join(member: Member) -> None:
338
"""Called when a member joins a guild."""
339
340
async def on_member_remove(member: Member) -> None:
341
"""Called when a member leaves a guild."""
342
343
async def on_member_update(before: Member, after: Member) -> None:
344
"""Called when a member is updated."""
345
346
# Application Command Events
347
async def on_application_command_error(ctx: ApplicationContext, error: Exception) -> None:
348
"""Called when an application command raises an error."""
349
350
async def on_application_command(ctx: ApplicationContext) -> None:
351
"""Called when an application command is invoked."""
352
```
353
354
### Intents and Permissions
355
356
Gateway intents control what events your bot receives, optimizing performance and respecting Discord's requirements.
357
358
```python { .api }
359
class Intents:
360
"""
361
Represents Discord gateway intents.
362
363
Intents control which events your bot receives from Discord.
364
Some intents are privileged and require approval for verified bots.
365
"""
366
367
def __init__(self, **kwargs) -> None: ...
368
369
@classmethod
370
def all(cls) -> Intents:
371
"""Create an Intents object with all intents enabled."""
372
373
@classmethod
374
def none(cls) -> Intents:
375
"""Create an Intents object with no intents enabled."""
376
377
@classmethod
378
def default(cls) -> Intents:
379
"""Create an Intents object with default intents enabled."""
380
381
# Privileged Intents (require approval for verified bots)
382
@property
383
def message_content(self) -> bool:
384
"""Access to message content in guild messages."""
385
386
@property
387
def members(self) -> bool:
388
"""Access to guild member events and member list."""
389
390
@property
391
def presences(self) -> bool:
392
"""Access to user presence updates."""
393
394
# Standard Intents
395
@property
396
def guilds(self) -> bool:
397
"""Guild and channel create/update/delete events."""
398
399
@property
400
def guild_messages(self) -> bool:
401
"""Guild message events."""
402
403
@property
404
def guild_reactions(self) -> bool:
405
"""Guild message reaction events."""
406
407
@property
408
def guild_typing(self) -> bool:
409
"""Guild typing indicator events."""
410
411
@property
412
def dm_messages(self) -> bool:
413
"""Direct message events."""
414
415
@property
416
def dm_reactions(self) -> bool:
417
"""Direct message reaction events."""
418
419
@property
420
def dm_typing(self) -> bool:
421
"""Direct message typing events."""
422
423
@property
424
def guild_integrations(self) -> bool:
425
"""Guild integration update events."""
426
427
@property
428
def webhooks(self) -> bool:
429
"""Guild webhook update events."""
430
431
@property
432
def invites(self) -> bool:
433
"""Guild invite create/delete events."""
434
435
@property
436
def voice_states(self) -> bool:
437
"""Voice state update events."""
438
439
@property
440
def guild_scheduled_events(self) -> bool:
441
"""Scheduled event create/update/delete events."""
442
443
@property
444
def auto_moderation_configuration(self) -> bool:
445
"""Auto-moderation rule create/update/delete events."""
446
447
@property
448
def auto_moderation_execution(self) -> bool:
449
"""Auto-moderation action execution events."""
450
451
@property
452
def value(self) -> int:
453
"""The raw integer value of the intents."""
454
455
class MemberCacheFlags:
456
"""
457
Controls which members are cached by the client.
458
"""
459
460
def __init__(self, **kwargs) -> None: ...
461
462
@classmethod
463
def all(cls) -> MemberCacheFlags:
464
"""Cache all members."""
465
466
@classmethod
467
def none(cls) -> MemberCacheFlags:
468
"""Cache no members."""
469
470
@classmethod
471
def from_intents(cls, intents: Intents) -> MemberCacheFlags:
472
"""Create cache flags based on intents."""
473
474
@property
475
def voice(self) -> bool:
476
"""Cache members in voice channels."""
477
478
@property
479
def joined(self) -> bool:
480
"""Cache members when they join."""
481
482
@property
483
def online(self) -> bool:
484
"""Cache online members."""
485
```
486
487
### WebSocket and Connection Details
488
489
Low-level connection management classes for advanced use cases.
490
491
```python { .api }
492
class DiscordWebSocket:
493
"""
494
The Discord WebSocket connection handler.
495
"""
496
497
@property
498
def latency(self) -> float:
499
"""The latency between heartbeat and heartbeat ack."""
500
501
async def send_heartbeat(self) -> None:
502
"""Send a heartbeat to Discord."""
503
504
async def close(self, code: int = 1000) -> None:
505
"""Close the WebSocket connection."""
506
507
class ShardInfo:
508
"""
509
Information about a shard.
510
"""
511
512
def __init__(self, shard_id: int, shard_count: int) -> None: ...
513
514
@property
515
def id(self) -> int:
516
"""The shard ID."""
517
518
@property
519
def shard_count(self) -> int:
520
"""Total number of shards."""
521
522
def is_ws_ratelimited(self) -> bool:
523
"""Check if the shard is WebSocket rate limited."""
524
525
class ConnectionClosed(Exception):
526
"""
527
Exception raised when the gateway connection is closed.
528
"""
529
530
def __init__(self, original: Exception, shard_id: Optional[int] = None) -> None: ...
531
532
@property
533
def code(self) -> int:
534
"""The close code."""
535
536
@property
537
def reason(self) -> str:
538
"""The close reason."""
539
```
540
541
The core client functionality provides the foundation for all Discord bot development with py-cord, handling connection management, event processing, application command registration, and the essential infrastructure needed for Discord integration.