0
# Core Discord Objects
1
2
Essential Discord entities that form the foundation of all bot interactions. These objects represent users, servers, channels, messages, and other core Discord concepts with comprehensive attribute access and methods for common operations.
3
4
## Capabilities
5
6
### Client & Connection
7
8
The main client class manages the bot's connection to Discord, handles events, and provides access to the HTTP API and gateway connection.
9
10
```python { .api }
11
class Client:
12
"""
13
Main Discord client for bot connections and API access.
14
15
Parameters:
16
- intents: Intents object specifying which events to receive
17
- heartbeat_timeout: Seconds to wait for heartbeat response (default: 60.0)
18
- guild_ready_timeout: Seconds to wait for guild data (default: 2.0)
19
- max_messages: Maximum messages to cache (default: 1000)
20
"""
21
def __init__(
22
self,
23
*,
24
intents: Intents,
25
heartbeat_timeout: float = 60.0,
26
guild_ready_timeout: float = 2.0,
27
max_messages: Optional[int] = 1000
28
): ...
29
30
async def start(self, token: str) -> None:
31
"""Start the client connection with the provided bot token."""
32
33
async def close(self) -> None:
34
"""Close the connection and cleanup resources."""
35
36
async def connect(self, *, reconnect: bool = True) -> None:
37
"""Connect to Discord's gateway."""
38
39
async def login(self, token: str) -> None:
40
"""Login with the provided token without connecting."""
41
42
def run(
43
self,
44
token: str,
45
*,
46
reconnect: bool = True,
47
log_handler: Optional[logging.Handler] = None,
48
log_formatter: logging.Formatter = None,
49
log_level: int = logging.INFO,
50
root_logger: bool = False
51
) -> None:
52
"""Convenience method to login and connect with logging setup."""
53
54
async def wait_until_ready(self) -> None:
55
"""Wait until the client is ready to process events."""
56
57
# Properties
58
user: Optional[ClientUser] # The bot user
59
guilds: List[Guild] # List of guilds the bot is in
60
users: List[User] # Cached users
61
cached_messages: List[Message] # Cached messages
62
latency: float # WebSocket latency in seconds
63
is_ready: bool # Whether the client is ready
64
is_closed: bool # Whether the connection is closed
65
```
66
67
### Users
68
69
User objects represent Discord accounts, including both regular users and the bot itself.
70
71
```python { .api }
72
class User:
73
"""
74
Represents a Discord user account.
75
"""
76
id: int # User's unique snowflake ID
77
name: str # Username (without discriminator for new usernames)
78
discriminator: str # User discriminator (0000 for new usernames)
79
global_name: Optional[str] # Display name
80
avatar: Optional[Asset] # User's avatar asset
81
bot: bool # Whether the user is a bot
82
system: bool # Whether the user is a system user
83
created_at: datetime # Account creation timestamp
84
default_avatar: Asset # Default avatar asset
85
display_avatar: Asset # Avatar or default if none
86
mention: str # Mention string (<@user_id>)
87
88
async def create_dm(self) -> DMChannel:
89
"""Create a DM channel with this user."""
90
91
def mentioned_in(self, message: Message) -> bool:
92
"""Check if user is mentioned in a message."""
93
94
class ClientUser(User):
95
"""
96
Represents the bot user account with additional properties.
97
"""
98
email: Optional[str] # Bot's email (if available)
99
verified: bool # Whether email is verified
100
mfa_enabled: bool # Whether 2FA is enabled
101
102
async def edit(self, *, username: str = None, avatar: bytes = None) -> ClientUser:
103
"""Edit the bot's profile."""
104
```
105
106
### Members
107
108
Member objects represent users within the context of a specific guild, including guild-specific data like roles and permissions.
109
110
```python { .api }
111
class Member(User):
112
"""
113
Represents a guild member (user + guild-specific data).
114
"""
115
nick: Optional[str] # Member's nickname in the guild
116
roles: List[Role] # Member's roles (includes @everyone)
117
joined_at: Optional[datetime] # When member joined the guild
118
premium_since: Optional[datetime] # When member started boosting
119
guild: Guild # The guild this member belongs to
120
voice: Optional[VoiceState] # Member's voice state
121
activities: List[Activity] # Member's activities/presence
122
status: Status # Member's status (online, idle, dnd, offline)
123
raw_status: str # Raw status string
124
mobile_status: Status # Mobile client status
125
desktop_status: Status # Desktop client status
126
web_status: Status # Web client status
127
guild_permissions: Permissions # Member's guild-wide permissions
128
display_name: str # Nick or global_name or name
129
display_avatar: Asset # Guild avatar or user avatar
130
131
async def edit(
132
self,
133
*,
134
nick: str = None,
135
roles: List[Role] = None,
136
mute: bool = None,
137
deafen: bool = None,
138
voice_channel: Optional[VoiceChannel] = None,
139
timeout_until: Optional[datetime] = None
140
) -> None:
141
"""Edit member properties (requires permissions)."""
142
143
async def add_roles(self, *roles: Role, reason: str = None) -> None:
144
"""Add roles to the member."""
145
146
async def remove_roles(self, *roles: Role, reason: str = None) -> None:
147
"""Remove roles from the member."""
148
149
async def ban(self, *, reason: str = None, delete_message_days: int = 1) -> None:
150
"""Ban the member from the guild."""
151
152
async def kick(self, *, reason: str = None) -> None:
153
"""Kick the member from the guild."""
154
155
async def timeout(self, until: datetime, *, reason: str = None) -> None:
156
"""Timeout the member until the specified time."""
157
158
def permissions_in(self, channel: GuildChannel) -> Permissions:
159
"""Calculate member's permissions in a specific channel."""
160
```
161
162
### Guilds
163
164
Guild objects represent Discord servers with comprehensive access to channels, members, roles, and server settings.
165
166
```python { .api }
167
class Guild:
168
"""
169
Represents a Discord guild (server).
170
"""
171
id: int # Guild's unique snowflake ID
172
name: str # Guild name
173
icon: Optional[Asset] # Guild icon asset
174
splash: Optional[Asset] # Guild splash asset
175
discovery_splash: Optional[Asset] # Guild discovery splash
176
banner: Optional[Asset] # Guild banner asset
177
description: Optional[str] # Guild description
178
owner_id: int # Guild owner's user ID
179
owner: Optional[Member] # Guild owner member object
180
region: str # Voice region
181
verification_level: VerificationLevel # Verification level required
182
default_notifications: NotificationLevel # Default notification setting
183
explicit_content_filter: ContentFilter # Content filter level
184
features: List[str] # Guild feature flags
185
premium_tier: int # Server boost level (0-3)
186
premium_subscription_count: int # Number of boosts
187
member_count: int # Total member count
188
large: bool # Whether guild is considered large (>250 members)
189
max_members: int # Maximum member limit
190
max_presences: Optional[int] # Maximum presence limit
191
vanity_url_code: Optional[str] # Vanity URL code
192
premium_progress_bar_enabled: bool # Whether boost progress bar is enabled
193
created_at: datetime # Guild creation timestamp
194
195
# Collections
196
members: List[Member] # Guild members
197
channels: List[GuildChannel] # Guild channels
198
roles: List[Role] # Guild roles
199
emojis: List[Emoji] # Custom emojis
200
stickers: List[GuildSticker] # Custom stickers
201
voice_channels: List[VoiceChannel] # Voice channels only
202
text_channels: List[TextChannel] # Text channels only
203
categories: List[CategoryChannel] # Category channels only
204
205
# Useful properties
206
system_channel: Optional[TextChannel] # System messages channel
207
rules_channel: Optional[TextChannel] # Rules channel
208
public_updates_channel: Optional[TextChannel] # Community updates channel
209
me: Member # Bot's member object in this guild
210
211
async def leave(self) -> None:
212
"""Leave the guild."""
213
214
async def delete(self) -> None:
215
"""Delete the guild (bot must be owner)."""
216
217
async def edit(self, *, name: str = None, description: str = None, icon: bytes = None) -> Guild:
218
"""Edit guild properties."""
219
220
async def create_text_channel(self, name: str, **options) -> TextChannel:
221
"""Create a new text channel."""
222
223
async def create_voice_channel(self, name: str, **options) -> VoiceChannel:
224
"""Create a new voice channel."""
225
226
async def create_category(self, name: str, **options) -> CategoryChannel:
227
"""Create a new category channel."""
228
229
async def create_role(self, *, name: str = None, permissions: Permissions = None, **options) -> Role:
230
"""Create a new role."""
231
232
async def ban(self, user: User, *, reason: str = None, delete_message_days: int = 1) -> None:
233
"""Ban a user from the guild."""
234
235
async def unban(self, user: User, *, reason: str = None) -> None:
236
"""Unban a user from the guild."""
237
238
async def kick(self, user: Member, *, reason: str = None) -> None:
239
"""Kick a member from the guild."""
240
241
async def fetch_member(self, user_id: int) -> Member:
242
"""Fetch a member by ID."""
243
244
async def fetch_ban(self, user: User) -> BanEntry:
245
"""Fetch ban information for a user."""
246
247
def get_member(self, user_id: int) -> Optional[Member]:
248
"""Get a cached member by ID."""
249
250
def get_channel(self, channel_id: int) -> Optional[GuildChannel]:
251
"""Get a cached channel by ID."""
252
253
def get_role(self, role_id: int) -> Optional[Role]:
254
"""Get a cached role by ID."""
255
```
256
257
### Channels
258
259
Channel objects represent different types of Discord channels with specialized functionality for text, voice, and organizational purposes.
260
261
```python { .api }
262
class TextChannel:
263
"""
264
Represents a guild text channel.
265
"""
266
id: int # Channel's unique snowflake ID
267
name: str # Channel name
268
guild: Guild # Guild this channel belongs to
269
position: int # Channel position in the list
270
category: Optional[CategoryChannel] # Parent category
271
topic: Optional[str] # Channel topic
272
slowmode_delay: int # Slowmode delay in seconds
273
nsfw: bool # Whether channel is age-restricted
274
permissions_synced: bool # Whether permissions sync with category
275
created_at: datetime # Channel creation timestamp
276
mention: str # Channel mention string (<#channel_id>)
277
278
async def send(
279
self,
280
content: str = None,
281
*,
282
embed: Embed = None,
283
embeds: List[Embed] = None,
284
file: File = None,
285
files: List[File] = None,
286
view: View = None,
287
tts: bool = False,
288
ephemeral: bool = False,
289
allowed_mentions: AllowedMentions = None,
290
reference: MessageReference = None
291
) -> Message:
292
"""Send a message to the channel."""
293
294
async def edit(self, *, name: str = None, topic: str = None, position: int = None) -> TextChannel:
295
"""Edit channel properties."""
296
297
async def delete(self, *, reason: str = None) -> None:
298
"""Delete the channel."""
299
300
async def purge(self, *, limit: int = 100, check: Callable = None) -> List[Message]:
301
"""Bulk delete messages."""
302
303
async def create_webhook(self, *, name: str, avatar: bytes = None) -> Webhook:
304
"""Create a webhook in this channel."""
305
306
def history(self, *, limit: int = 100, before: datetime = None) -> AsyncIterator[Message]:
307
"""Iterate through channel message history."""
308
309
def permissions_for(self, obj: Union[Member, Role]) -> Permissions:
310
"""Calculate permissions for a member or role."""
311
312
class VoiceChannel:
313
"""
314
Represents a guild voice channel.
315
"""
316
id: int # Channel's unique snowflake ID
317
name: str # Channel name
318
guild: Guild # Guild this channel belongs to
319
position: int # Channel position
320
category: Optional[CategoryChannel] # Parent category
321
bitrate: int # Voice bitrate
322
user_limit: int # User limit (0 = unlimited)
323
rtc_region: Optional[str] # Voice server region
324
video_quality_mode: int # Video quality mode
325
members: List[Member] # Connected members
326
327
async def connect(self, *, timeout: float = 60.0, reconnect: bool = True) -> VoiceClient:
328
"""Connect to the voice channel."""
329
330
async def edit(self, *, name: str = None, bitrate: int = None, user_limit: int = None) -> VoiceChannel:
331
"""Edit voice channel properties."""
332
333
class DMChannel:
334
"""
335
Represents a direct message channel.
336
"""
337
id: int # Channel ID
338
recipient: User # The other user in the DM
339
me: ClientUser # The bot user
340
341
async def send(self, content: str = None, **kwargs) -> Message:
342
"""Send a DM message."""
343
344
class CategoryChannel:
345
"""
346
Represents a channel category for organization.
347
"""
348
id: int # Category ID
349
name: str # Category name
350
guild: Guild # Guild this category belongs to
351
position: int # Category position
352
channels: List[GuildChannel] # Channels in this category
353
354
async def create_text_channel(self, name: str, **options) -> TextChannel:
355
"""Create a text channel in this category."""
356
357
async def create_voice_channel(self, name: str, **options) -> VoiceChannel:
358
"""Create a voice channel in this category."""
359
```
360
361
### Messages
362
363
Message objects represent Discord messages with comprehensive metadata, content access, and interaction methods.
364
365
```python { .api }
366
class Message:
367
"""
368
Represents a Discord message.
369
"""
370
id: int # Message's unique snowflake ID
371
channel: Union[TextChannel, DMChannel, GroupChannel] # Channel message was sent in
372
guild: Optional[Guild] # Guild if sent in a guild channel
373
author: Union[User, Member] # Message author
374
content: str # Message text content
375
clean_content: str # Content with mentions resolved
376
created_at: datetime # Message creation timestamp
377
edited_at: Optional[datetime] # Last edit timestamp
378
tts: bool # Whether message is text-to-speech
379
mention_everyone: bool # Whether message mentions @everyone
380
mentions: List[Union[User, Member]] # Mentioned users
381
channel_mentions: List[GuildChannel] # Mentioned channels
382
role_mentions: List[Role] # Mentioned roles
383
attachments: List[Attachment] # File attachments
384
embeds: List[Embed] # Rich embeds
385
reactions: List[Reaction] # Message reactions
386
pinned: bool # Whether message is pinned
387
type: MessageType # Message type (default, reply, etc.)
388
system_content: Optional[str] # System message content
389
flags: MessageFlags # Message flags
390
reference: Optional[MessageReference] # Reference to replied message
391
components: List[Component] # UI components attached
392
393
async def edit(
394
self,
395
*,
396
content: str = None,
397
embed: Embed = None,
398
embeds: List[Embed] = None,
399
attachments: List[Attachment] = None,
400
view: View = None
401
) -> Message:
402
"""Edit the message (bot must be author)."""
403
404
async def delete(self, *, delay: float = None) -> None:
405
"""Delete the message."""
406
407
async def pin(self, *, reason: str = None) -> None:
408
"""Pin the message."""
409
410
async def unpin(self, *, reason: str = None) -> None:
411
"""Unpin the message."""
412
413
async def add_reaction(self, emoji: Union[Emoji, str]) -> None:
414
"""Add a reaction to the message."""
415
416
async def remove_reaction(self, emoji: Union[Emoji, str], member: Member) -> None:
417
"""Remove a reaction from the message."""
418
419
async def clear_reactions(self) -> None:
420
"""Clear all reactions from the message."""
421
422
async def reply(self, content: str = None, **kwargs) -> Message:
423
"""Reply to the message."""
424
425
def to_reference(self) -> MessageReference:
426
"""Create a message reference for replies."""
427
428
class Attachment:
429
"""
430
Represents a message file attachment.
431
"""
432
id: int # Attachment ID
433
filename: str # Original filename
434
description: Optional[str] # Alt text description
435
content_type: Optional[str] # MIME type
436
size: int # File size in bytes
437
url: str # Attachment URL
438
proxy_url: str # Proxied URL
439
height: Optional[int] # Image/video height
440
width: Optional[int] # Image/video width
441
ephemeral: bool # Whether attachment is ephemeral
442
443
async def save(self, fp: Union[str, bytes, os.PathLike], *, seek_begin: bool = True) -> int:
444
"""Save attachment to file."""
445
446
async def read(self) -> bytes:
447
"""Read attachment data."""
448
449
def to_file(self) -> File:
450
"""Convert to a File object for re-uploading."""
451
```
452
453
### Roles & Permissions
454
455
Role and permission objects manage access control and user organization within guilds.
456
457
```python { .api }
458
class Role:
459
"""
460
Represents a guild role.
461
"""
462
id: int # Role's unique snowflake ID
463
name: str # Role name
464
guild: Guild # Guild this role belongs to
465
colour: Colour # Role color
466
color: Colour # Alias for colour
467
hoist: bool # Whether role is displayed separately
468
position: int # Role position in hierarchy
469
managed: bool # Whether role is managed by integration
470
mentionable: bool # Whether role can be mentioned
471
permissions: Permissions # Role permissions
472
tags: Optional[RoleTags] # Role tags (bot, premium subscriber, etc.)
473
created_at: datetime # Role creation timestamp
474
mention: str # Role mention string (<@&role_id>)
475
members: List[Member] # Members with this role
476
477
async def edit(
478
self,
479
*,
480
name: str = None,
481
permissions: Permissions = None,
482
colour: Colour = None,
483
hoist: bool = None,
484
mentionable: bool = None,
485
position: int = None
486
) -> Role:
487
"""Edit role properties."""
488
489
async def delete(self, *, reason: str = None) -> None:
490
"""Delete the role."""
491
492
def is_default(self) -> bool:
493
"""Check if this is the @everyone role."""
494
495
def is_bot_managed(self) -> bool:
496
"""Check if role is managed by a bot."""
497
498
def is_premium_subscriber(self) -> bool:
499
"""Check if role is the premium subscriber role."""
500
501
class Permissions:
502
"""
503
Represents Discord permissions as a bitfield.
504
"""
505
value: int # Permission bitfield value
506
507
def __init__(self, permissions: int = 0): ...
508
509
@classmethod
510
def none(cls) -> Permissions:
511
"""Create permissions with no flags set."""
512
513
@classmethod
514
def all(cls) -> Permissions:
515
"""Create permissions with all flags set."""
516
517
@classmethod
518
def all_channel(cls) -> Permissions:
519
"""Create permissions with all channel-specific flags."""
520
521
@classmethod
522
def general(cls) -> Permissions:
523
"""Create permissions with general flags."""
524
525
@classmethod
526
def text(cls) -> Permissions:
527
"""Create permissions with text channel flags."""
528
529
@classmethod
530
def voice(cls) -> Permissions:
531
"""Create permissions with voice channel flags."""
532
533
@classmethod
534
def stage(cls) -> Permissions:
535
"""Create permissions with stage channel flags."""
536
537
# Permission properties (read/write)
538
create_instant_invite: bool
539
kick_members: bool
540
ban_members: bool
541
administrator: bool
542
manage_channels: bool
543
manage_guild: bool
544
add_reactions: bool
545
view_audit_log: bool
546
priority_speaker: bool
547
stream: bool
548
read_messages: bool
549
view_channel: bool # Alias for read_messages
550
send_messages: bool
551
send_tts_messages: bool
552
manage_messages: bool
553
embed_links: bool
554
attach_files: bool
555
read_message_history: bool
556
mention_everyone: bool
557
external_emojis: bool
558
use_external_emojis: bool # Alias for external_emojis
559
view_guild_insights: bool
560
connect: bool
561
speak: bool
562
mute_members: bool
563
deafen_members: bool
564
move_members: bool
565
use_voice_activation: bool
566
change_nickname: bool
567
manage_nicknames: bool
568
manage_roles: bool
569
manage_permissions: bool # Alias for manage_roles
570
manage_webhooks: bool
571
manage_emojis: bool
572
manage_emojis_and_stickers: bool
573
use_application_commands: bool
574
use_slash_commands: bool # Alias for use_application_commands
575
request_to_speak: bool
576
manage_events: bool
577
manage_threads: bool
578
create_public_threads: bool
579
create_private_threads: bool
580
external_stickers: bool
581
use_external_stickers: bool # Alias for external_stickers
582
send_messages_in_threads: bool
583
start_embedded_activities: bool
584
moderate_members: bool
585
586
def update(self, **kwargs) -> None:
587
"""Update multiple permission flags."""
588
589
def is_subset(self, other: Permissions) -> bool:
590
"""Check if permissions are a subset of another."""
591
592
def is_superset(self, other: Permissions) -> bool:
593
"""Check if permissions are a superset of another."""
594
595
def is_strict_subset(self, other: Permissions) -> bool:
596
"""Check if permissions are a strict subset."""
597
598
def is_strict_superset(self, other: Permissions) -> bool:
599
"""Check if permissions are a strict superset."""
600
```
601
602
### Emojis & Assets
603
604
Emoji and asset objects provide access to Discord's custom emojis and media assets like avatars and icons.
605
606
```python { .api }
607
class Emoji:
608
"""
609
Represents a custom guild emoji.
610
"""
611
id: int # Emoji's unique snowflake ID
612
name: str # Emoji name
613
guild: Guild # Guild this emoji belongs to
614
animated: bool # Whether emoji is animated
615
managed: bool # Whether emoji is managed by integration
616
require_colons: bool # Whether emoji requires colons
617
roles: List[Role] # Roles that can use this emoji
618
user: Optional[User] # User who created the emoji
619
available: bool # Whether emoji is available for use
620
created_at: datetime # Emoji creation timestamp
621
url: str # Emoji image URL
622
623
async def edit(self, *, name: str = None, roles: List[Role] = None) -> Emoji:
624
"""Edit emoji properties."""
625
626
async def delete(self, *, reason: str = None) -> None:
627
"""Delete the emoji."""
628
629
def __str__(self) -> str:
630
"""Return emoji string for sending in messages."""
631
632
class PartialEmoji:
633
"""
634
Represents a partial emoji (from reactions, etc.).
635
"""
636
id: Optional[int] # Emoji ID (None for unicode)
637
name: str # Emoji name or unicode character
638
animated: bool # Whether emoji is animated
639
640
def __str__(self) -> str:
641
"""Return emoji string."""
642
643
@property
644
def url(self) -> Optional[str]:
645
"""Emoji URL if custom emoji."""
646
647
class Asset:
648
"""
649
Represents a Discord CDN asset (avatar, icon, etc.).
650
"""
651
url: str # Asset URL
652
key: str # Asset key/hash
653
654
def replace(self, *, size: int = None, format: str = None, static_format: str = None) -> Asset:
655
"""Create a new asset with different parameters."""
656
657
def with_size(self, size: int) -> Asset:
658
"""Create asset with specific size."""
659
660
def with_format(self, format: str) -> Asset:
661
"""Create asset with specific format."""
662
663
def with_static_format(self, format: str) -> Asset:
664
"""Create asset with static format."""
665
666
async def save(self, fp: Union[str, bytes, os.PathLike], *, seek_begin: bool = True) -> int:
667
"""Save asset to file."""
668
669
async def read(self) -> bytes:
670
"""Read asset data."""
671
```
672
673
## Error Handling
674
675
```python { .api }
676
# Base Exceptions
677
class DiscordException(Exception):
678
"""Base exception for discord.py."""
679
pass
680
681
class ClientException(DiscordException):
682
"""Exception for client-side errors."""
683
pass
684
685
# Connection Exceptions
686
class GatewayNotFound(DiscordException):
687
"""Gateway URL could not be found."""
688
pass
689
690
class ConnectionClosed(ClientException):
691
"""WebSocket connection was closed."""
692
def __init__(self, socket, *, shard_id: int, code: int = None): ...
693
shard_id: int
694
code: Optional[int]
695
696
# HTTP Exceptions
697
class HTTPException(DiscordException):
698
"""Exception for HTTP request errors."""
699
def __init__(self, response, message: str): ...
700
response: aiohttp.ClientResponse
701
status: int
702
code: int
703
text: str
704
705
class Forbidden(HTTPException):
706
"""403 Forbidden HTTP error."""
707
pass
708
709
class NotFound(HTTPException):
710
"""404 Not Found HTTP error."""
711
pass
712
713
class DiscordServerError(HTTPException):
714
"""5xx server error."""
715
pass
716
717
class RateLimited(HTTPException):
718
"""429 Rate Limited error."""
719
retry_after: float
720
721
# Authentication Exceptions
722
class LoginFailure(ClientException):
723
"""Invalid authentication credentials."""
724
pass
725
726
class PrivilegedIntentsRequired(ClientException):
727
"""Bot requires privileged intents."""
728
pass
729
730
# Data Exceptions
731
class InvalidData(ClientException):
732
"""Invalid or unexpected data received."""
733
pass
734
735
class InvalidArgument(ClientException):
736
"""Invalid argument passed to function."""
737
pass
738
```