0
# Utilities and Helpers
1
2
Utility functions, enumerations, flags, audio support, color handling, and various helper functions for Discord bot development. These utilities provide essential tools and constants for working with Discord's API and building robust applications.
3
4
## Capabilities
5
6
### Utility Functions (discord.utils)
7
8
Helper functions for common Discord operations, time handling, search operations, and text processing.
9
10
```python { .api }
11
# Search and Retrieval Functions
12
def find(predicate: Callable[[Any], bool], iterable: Iterable[Any]) -> Optional[Any]:
13
"""
14
Find the first item in an iterable that matches the predicate.
15
16
Parameters:
17
- predicate: Callable - Function that returns True for the desired item
18
- iterable: Iterable - Collection to search
19
20
Returns:
21
Optional[Any] - First matching item or None
22
"""
23
24
def get(iterable: Iterable[Any], **attrs) -> Optional[Any]:
25
"""
26
Get an item from an iterable by attribute values.
27
28
Parameters:
29
- iterable: Iterable - Collection to search
30
**attrs: Attribute name-value pairs to match
31
32
Returns:
33
Optional[Any] - First matching item or None
34
35
Example:
36
member = discord.utils.get(guild.members, name='Foo')
37
channel = discord.utils.get(guild.channels, name='general', type=ChannelType.text)
38
"""
39
40
async def get_or_fetch(
41
guild: Guild,
42
attribute: str,
43
id: int,
44
*,
45
default: Any = None
46
) -> Any:
47
"""
48
Get an object from cache or fetch from API if not found.
49
50
Parameters:
51
- guild: Guild - Guild to search in
52
- attribute: str - Attribute name ('members', 'channels', etc.)
53
- id: int - Object ID to find
54
- default: Any - Default value if not found
55
"""
56
57
# Time and Snowflake Functions
58
def snowflake_time(id: int) -> datetime:
59
"""
60
Get the creation time of a Discord snowflake ID.
61
62
Parameters:
63
- id: int - Discord snowflake ID
64
65
Returns:
66
datetime - When the snowflake was created
67
"""
68
69
def time_snowflake(dt: datetime, *, high: bool = False) -> int:
70
"""
71
Generate a snowflake ID for a given datetime.
72
73
Parameters:
74
- dt: datetime - Timestamp to convert
75
- high: bool - Whether to use high or low end of millisecond
76
77
Returns:
78
int - Generated snowflake ID
79
"""
80
81
def generate_snowflake() -> int:
82
"""
83
Generate a unique Discord snowflake ID.
84
85
Returns:
86
int - New snowflake ID
87
"""
88
89
def parse_time(timestamp: str) -> Optional[datetime]:
90
"""
91
Parse an ISO 8601 timestamp string.
92
93
Parameters:
94
- timestamp: str - ISO timestamp string
95
96
Returns:
97
Optional[datetime] - Parsed datetime or None if invalid
98
"""
99
100
def utcnow() -> datetime:
101
"""
102
Get the current UTC time.
103
104
Returns:
105
datetime - Current UTC time
106
"""
107
108
async def sleep_until(when: datetime, result: Any = None) -> Any:
109
"""
110
Sleep until a specific datetime.
111
112
Parameters:
113
- when: datetime - Time to sleep until
114
- result: Any - Value to return after sleeping
115
116
Returns:
117
Any - The result parameter
118
"""
119
120
def format_dt(dt: datetime, /, style: str = None) -> str:
121
"""
122
Format a datetime for Discord's timestamp formatting.
123
124
Parameters:
125
- dt: datetime - Datetime to format
126
- style: str - Format style ('f', 'F', 'd', 'D', 't', 'T', 'R')
127
128
Returns:
129
str - Discord timestamp string
130
131
Styles:
132
- 'f': Short date/time (default)
133
- 'F': Long date/time
134
- 'd': Short date
135
- 'D': Long date
136
- 't': Short time
137
- 'T': Long time
138
- 'R': Relative time
139
"""
140
141
# Text Processing Functions
142
def remove_markdown(text: str, *, ignore_links: bool = True) -> str:
143
"""
144
Remove Discord markdown formatting from text.
145
146
Parameters:
147
- text: str - Text with markdown
148
- ignore_links: bool - Whether to ignore link formatting
149
150
Returns:
151
str - Text with markdown removed
152
"""
153
154
def escape_markdown(
155
text: str,
156
*,
157
as_needed: bool = False,
158
ignore_links: bool = True
159
) -> str:
160
"""
161
Escape Discord markdown characters in text.
162
163
Parameters:
164
- text: str - Text to escape
165
- as_needed: bool - Only escape characters that would cause formatting
166
- ignore_links: bool - Don't escape characters in links
167
168
Returns:
169
str - Text with markdown characters escaped
170
"""
171
172
def escape_mentions(text: str) -> str:
173
"""
174
Escape Discord mentions in text.
175
176
Parameters:
177
- text: str - Text with mentions
178
179
Returns:
180
str - Text with mentions escaped
181
"""
182
183
# Mention Extraction Functions
184
def raw_mentions(text: str) -> List[str]:
185
"""
186
Extract raw user mentions from text.
187
188
Parameters:
189
- text: str - Text containing mentions
190
191
Returns:
192
List[str] - List of mention strings
193
"""
194
195
def raw_channel_mentions(text: str) -> List[str]:
196
"""
197
Extract raw channel mentions from text.
198
199
Parameters:
200
- text: str - Text containing channel mentions
201
202
Returns:
203
List[str] - List of channel mention strings
204
"""
205
206
def raw_role_mentions(text: str) -> List[str]:
207
"""
208
Extract raw role mentions from text.
209
210
Parameters:
211
- text: str - Text containing role mentions
212
213
Returns:
214
List[str] - List of role mention strings
215
"""
216
217
# URL Generation Functions
218
def oauth_url(
219
client_id: int,
220
*,
221
permissions: Permissions = None,
222
guild: Snowflake = None,
223
redirect_uri: str = None,
224
scopes: Iterable[str] = None,
225
disable_guild_select: bool = False,
226
state: str = None
227
) -> str:
228
"""
229
Generate an OAuth2 authorization URL for a bot.
230
231
Parameters:
232
- client_id: int - Bot's client ID
233
- permissions: Permissions - Permissions to request
234
- guild: Snowflake - Pre-select a guild
235
- redirect_uri: str - Redirect URI after authorization
236
- scopes: Iterable[str] - OAuth2 scopes to request
237
- disable_guild_select: bool - Disable guild selection
238
- state: str - State parameter for security
239
240
Returns:
241
str - OAuth2 authorization URL
242
"""
243
244
def resolve_invite(invite: Union[Invite, str]) -> str:
245
"""
246
Resolve an invite to its full URL.
247
248
Parameters:
249
- invite: Union[Invite, str] - Invite object or code
250
251
Returns:
252
str - Full invite URL
253
"""
254
255
def resolve_template(code: str) -> str:
256
"""
257
Resolve a template code to its full URL.
258
259
Parameters:
260
- code: str - Template code
261
262
Returns:
263
str - Full template URL
264
"""
265
266
# General Utilities
267
def as_chunks(iterator: Iterable[Any], max_size: int) -> List[List[Any]]:
268
"""
269
Split an iterable into chunks of maximum size.
270
271
Parameters:
272
- iterator: Iterable - Collection to split
273
- max_size: int - Maximum size per chunk
274
275
Returns:
276
List[List[Any]] - List of chunks
277
"""
278
279
async def basic_autocomplete(
280
ctx: AutocompleteContext,
281
choices: List[str],
282
*,
283
current_input: str = None
284
) -> List[OptionChoice]:
285
"""
286
Basic autocomplete implementation for slash commands.
287
288
Parameters:
289
- ctx: AutocompleteContext - Autocomplete context
290
- choices: List[str] - Available choices
291
- current_input: str - Current user input (defaults to ctx.value)
292
293
Returns:
294
List[OptionChoice] - Filtered choices
295
"""
296
297
def filter_params(params: Dict[str, Any], **filters) -> Dict[str, Any]:
298
"""
299
Filter function parameters based on criteria.
300
301
Parameters:
302
- params: Dict - Parameters to filter
303
**filters: Filter criteria
304
305
Returns:
306
Dict[str, Any] - Filtered parameters
307
"""
308
309
# Deprecation Utilities
310
def warn_deprecated(
311
name: str,
312
instead: str = None,
313
*,
314
since: str = None,
315
removed: str = None
316
) -> None:
317
"""
318
Issue a deprecation warning.
319
320
Parameters:
321
- name: str - Name of deprecated feature
322
- instead: str - What to use instead
323
- since: str - Version when deprecation started
324
- removed: str - Version when feature will be removed
325
"""
326
327
def deprecated(instead: str = None) -> Callable:
328
"""
329
Decorator to mark functions as deprecated.
330
331
Parameters:
332
- instead: str - What to use instead
333
"""
334
```
335
336
### Color Support
337
338
Color representation and manipulation for embeds and other visual elements.
339
340
```python { .api }
341
class Colour:
342
"""
343
Represents a color with Discord color constants and utilities.
344
"""
345
346
def __init__(self, value: int) -> None:
347
"""
348
Create a color from an integer value.
349
350
Parameters:
351
- value: int - RGB color value (0x000000 to 0xFFFFFF)
352
"""
353
354
@classmethod
355
def from_rgb(cls, r: int, g: int, b: int) -> Colour:
356
"""
357
Create a color from RGB values.
358
359
Parameters:
360
- r: int - Red component (0-255)
361
- g: int - Green component (0-255)
362
- b: int - Blue component (0-255)
363
"""
364
365
@classmethod
366
def from_hsv(cls, h: float, s: float, v: float) -> Colour:
367
"""
368
Create a color from HSV values.
369
370
Parameters:
371
- h: float - Hue (0.0-1.0)
372
- s: float - Saturation (0.0-1.0)
373
- v: float - Value (0.0-1.0)
374
"""
375
376
@classmethod
377
def random(cls, *, seed: Union[int, str, float, bytes, bytearray] = None) -> Colour:
378
"""
379
Generate a random color.
380
381
Parameters:
382
- seed: Union[int, str, float, bytes, bytearray] - Random seed
383
"""
384
385
@property
386
def value(self) -> int:
387
"""The raw integer color value."""
388
389
@property
390
def r(self) -> int:
391
"""Red component (0-255)."""
392
393
@property
394
def g(self) -> int:
395
"""Green component (0-255)."""
396
397
@property
398
def b(self) -> int:
399
"""Blue component (0-255)."""
400
401
def to_rgb(self) -> Tuple[int, int, int]:
402
"""Get RGB tuple."""
403
404
def to_hsv(self) -> Tuple[float, float, float]:
405
"""Get HSV tuple."""
406
407
# Discord Brand Colors
408
@classmethod
409
def teal(cls) -> Colour: ...
410
411
@classmethod
412
def dark_teal(cls) -> Colour: ...
413
414
@classmethod
415
def brand_green(cls) -> Colour: ...
416
417
@classmethod
418
def green(cls) -> Colour: ...
419
420
@classmethod
421
def dark_green(cls) -> Colour: ...
422
423
@classmethod
424
def blue(cls) -> Colour: ...
425
426
@classmethod
427
def dark_blue(cls) -> Colour: ...
428
429
@classmethod
430
def purple(cls) -> Colour: ...
431
432
@classmethod
433
def dark_purple(cls) -> Colour: ...
434
435
@classmethod
436
def magenta(cls) -> Colour: ...
437
438
@classmethod
439
def dark_magenta(cls) -> Colour: ...
440
441
@classmethod
442
def gold(cls) -> Colour: ...
443
444
@classmethod
445
def dark_gold(cls) -> Colour: ...
446
447
@classmethod
448
def orange(cls) -> Colour: ...
449
450
@classmethod
451
def dark_orange(cls) -> Colour: ...
452
453
@classmethod
454
def brand_red(cls) -> Colour: ...
455
456
@classmethod
457
def red(cls) -> Colour: ...
458
459
@classmethod
460
def dark_red(cls) -> Colour: ...
461
462
@classmethod
463
def lighter_grey(cls) -> Colour: ...
464
465
@classmethod
466
def lighter_gray(cls) -> Colour: ...
467
468
@classmethod
469
def dark_grey(cls) -> Colour: ...
470
471
@classmethod
472
def dark_gray(cls) -> Colour: ...
473
474
@classmethod
475
def light_grey(cls) -> Colour: ...
476
477
@classmethod
478
def light_gray(cls) -> Colour: ...
479
480
@classmethod
481
def darker_grey(cls) -> Colour: ...
482
483
@classmethod
484
def darker_gray(cls) -> Colour: ...
485
486
@classmethod
487
def og_blurple(cls) -> Colour: ...
488
489
@classmethod
490
def blurple(cls) -> Colour: ...
491
492
@classmethod
493
def greyple(cls) -> Colour: ...
494
495
@classmethod
496
def grayple(cls) -> Colour: ...
497
498
@classmethod
499
def dark_theme(cls) -> Colour: ...
500
501
@classmethod
502
def fuchsia(cls) -> Colour: ...
503
504
@classmethod
505
def yellow(cls) -> Colour: ...
506
507
@classmethod
508
def nitro_pink(cls) -> Colour: ...
509
510
@classmethod
511
def hypesquad_bravery(cls) -> Colour: ...
512
513
@classmethod
514
def hypesquad_brilliance(cls) -> Colour: ...
515
516
@classmethod
517
def hypesquad_balance(cls) -> Colour: ...
518
519
class Color(Colour):
520
"""Alias for Colour using American spelling."""
521
pass
522
```
523
524
### Rich Embeds
525
526
Rich embed creation and manipulation for enhanced message formatting.
527
528
```python { .api }
529
class Embed:
530
"""
531
Represents a Discord embed for rich message formatting.
532
"""
533
534
def __init__(
535
self,
536
*,
537
title: str = None,
538
description: str = None,
539
url: str = None,
540
timestamp: datetime = None,
541
color: Union[int, Colour] = None,
542
colour: Union[int, Colour] = None
543
) -> None:
544
"""
545
Create an embed.
546
547
Parameters:
548
- title: str - Embed title
549
- description: str - Embed description
550
- url: str - URL for title link
551
- timestamp: datetime - Embed timestamp
552
- color: Union[int, Colour] - Embed color
553
- colour: Union[int, Colour] - Embed colour (same as color)
554
"""
555
556
@classmethod
557
def from_dict(cls, data: Dict[str, Any]) -> Embed:
558
"""Create an embed from a dictionary."""
559
560
def to_dict(self) -> Dict[str, Any]:
561
"""Convert the embed to a dictionary."""
562
563
def copy(self) -> Embed:
564
"""Create a copy of the embed."""
565
566
@property
567
def title(self) -> Optional[str]: ...
568
@property
569
def description(self) -> Optional[str]: ...
570
@property
571
def url(self) -> Optional[str]: ...
572
@property
573
def timestamp(self) -> Optional[datetime]: ...
574
@property
575
def color(self) -> Optional[Colour]: ...
576
@property
577
def colour(self) -> Optional[Colour]: ...
578
@property
579
def footer(self) -> Optional[EmbedFooter]: ...
580
@property
581
def image(self) -> Optional[EmbedMedia]: ...
582
@property
583
def thumbnail(self) -> Optional[EmbedMedia]: ...
584
@property
585
def video(self) -> Optional[EmbedMedia]: ...
586
@property
587
def provider(self) -> Optional[EmbedProvider]: ...
588
@property
589
def author(self) -> Optional[EmbedAuthor]: ...
590
@property
591
def fields(self) -> List[EmbedField]: ...
592
593
def set_footer(
594
self,
595
*,
596
text: str = None,
597
icon_url: str = None
598
) -> Embed:
599
"""
600
Set the embed footer.
601
602
Parameters:
603
- text: str - Footer text
604
- icon_url: str - Footer icon URL
605
"""
606
607
def set_image(self, *, url: str) -> Embed:
608
"""
609
Set the embed image.
610
611
Parameters:
612
- url: str - Image URL
613
"""
614
615
def set_thumbnail(self, *, url: str) -> Embed:
616
"""
617
Set the embed thumbnail.
618
619
Parameters:
620
- url: str - Thumbnail URL
621
"""
622
623
def set_author(
624
self,
625
*,
626
name: str,
627
url: str = None,
628
icon_url: str = None
629
) -> Embed:
630
"""
631
Set the embed author.
632
633
Parameters:
634
- name: str - Author name
635
- url: str - Author URL
636
- icon_url: str - Author icon URL
637
"""
638
639
def add_field(
640
self,
641
*,
642
name: str,
643
value: str,
644
inline: bool = True
645
) -> Embed:
646
"""
647
Add a field to the embed.
648
649
Parameters:
650
- name: str - Field name
651
- value: str - Field value
652
- inline: bool - Whether the field is inline
653
"""
654
655
def insert_field_at(
656
self,
657
index: int,
658
*,
659
name: str,
660
value: str,
661
inline: bool = True
662
) -> Embed:
663
"""Insert a field at a specific position."""
664
665
def set_field_at(
666
self,
667
index: int,
668
*,
669
name: str,
670
value: str,
671
inline: bool = True
672
) -> Embed:
673
"""Set a field at a specific position."""
674
675
def remove_field(self, index: int) -> Embed:
676
"""Remove a field by index."""
677
678
def clear_fields(self) -> Embed:
679
"""Remove all fields from the embed."""
680
681
class EmbedField:
682
"""Represents an embed field."""
683
684
@property
685
def name(self) -> str: ...
686
@property
687
def value(self) -> str: ...
688
@property
689
def inline(self) -> bool: ...
690
691
class EmbedAuthor:
692
"""Represents embed author information."""
693
694
@property
695
def name(self) -> str: ...
696
@property
697
def url(self) -> Optional[str]: ...
698
@property
699
def icon_url(self) -> Optional[str]: ...
700
@property
701
def proxy_icon_url(self) -> Optional[str]: ...
702
703
class EmbedFooter:
704
"""Represents embed footer information."""
705
706
@property
707
def text(self) -> str: ...
708
@property
709
def icon_url(self) -> Optional[str]: ...
710
@property
711
def proxy_icon_url(self) -> Optional[str]: ...
712
713
class EmbedMedia:
714
"""Represents embed media (image, thumbnail, video)."""
715
716
@property
717
def url(self) -> str: ...
718
@property
719
def proxy_url(self) -> Optional[str]: ...
720
@property
721
def height(self) -> Optional[int]: ...
722
@property
723
def width(self) -> Optional[int]: ...
724
725
class EmbedProvider:
726
"""Represents embed provider information."""
727
728
@property
729
def name(self) -> Optional[str]: ...
730
@property
731
def url(self) -> Optional[str]: ...
732
```
733
734
### File Attachments
735
736
File attachment system for sending files with messages.
737
738
```python { .api }
739
class File:
740
"""
741
Represents a file attachment for Discord messages.
742
"""
743
744
def __init__(
745
self,
746
fp: Union[str, bytes, os.PathLike, io.IOBase],
747
filename: str = None,
748
*,
749
description: str = None,
750
spoiler: bool = False
751
) -> None:
752
"""
753
Create a file attachment.
754
755
Parameters:
756
- fp: Union[str, bytes, PathLike, IOBase] - File path, bytes, or file-like object
757
- filename: str - Custom filename
758
- description: str - File description
759
- spoiler: bool - Whether the file is a spoiler
760
"""
761
762
@property
763
def filename(self) -> Optional[str]: ...
764
@property
765
def description(self) -> Optional[str]: ...
766
@property
767
def spoiler(self) -> bool: ...
768
@property
769
def fp(self) -> io.IOBase: ...
770
771
def reset(self, *, seek: Union[int, bool] = True) -> None:
772
"""Reset the file pointer."""
773
774
def close(self) -> None:
775
"""Close the file."""
776
```
777
778
### Asset Management
779
780
Asset handling for avatars, icons, and other Discord CDN resources.
781
782
```python { .api }
783
class Asset:
784
"""
785
Represents a Discord CDN asset (avatar, icon, banner, etc.).
786
"""
787
788
@property
789
def url(self) -> str:
790
"""The asset's URL."""
791
792
@property
793
def key(self) -> str:
794
"""The asset's hash key."""
795
796
@property
797
def is_animated(self) -> bool:
798
"""Whether the asset is animated (GIF)."""
799
800
def replace(
801
self,
802
*,
803
size: int = None,
804
format: str = None,
805
static_format: str = None
806
) -> Asset:
807
"""
808
Create a new asset with different parameters.
809
810
Parameters:
811
- size: int - Image size (must be power of 2, 16-4096)
812
- format: str - Image format ('png', 'jpg', 'jpeg', 'webp', 'gif')
813
- static_format: str - Format for static version of animated assets
814
"""
815
816
def with_size(self, size: int) -> Asset:
817
"""Create asset with different size."""
818
819
def with_format(self, format: str) -> Asset:
820
"""Create asset with different format."""
821
822
def with_static_format(self, format: str) -> Asset:
823
"""Create asset with static format."""
824
825
async def save(
826
self,
827
fp: Union[str, bytes, os.PathLike, io.BufferedIOBase],
828
*,
829
seek_begin: bool = True
830
) -> int:
831
"""
832
Save the asset to a file.
833
834
Parameters:
835
- fp: Union[str, bytes, PathLike, BufferedIOBase] - File path or file object
836
- seek_begin: bool - Whether to seek to beginning of file
837
838
Returns:
839
int - Number of bytes written
840
"""
841
842
async def read(self) -> bytes:
843
"""
844
Read the asset data.
845
846
Returns:
847
bytes - Asset data
848
"""
849
850
async def to_file(
851
self,
852
*,
853
filename: str = None,
854
description: str = None,
855
spoiler: bool = False
856
) -> File:
857
"""
858
Convert the asset to a File object.
859
860
Parameters:
861
- filename: str - Custom filename
862
- description: str - File description
863
- spoiler: bool - Whether it's a spoiler
864
"""
865
```
866
867
### Enumerations and Constants
868
869
Important enumerations and constants used throughout py-cord.
870
871
```python { .api }
872
class Status(Enum):
873
"""User online status."""
874
online = "online"
875
offline = "offline"
876
idle = "idle"
877
dnd = "dnd"
878
do_not_disturb = "dnd"
879
invisible = "invisible"
880
881
class ChannelType(Enum):
882
"""Discord channel types."""
883
text = 0
884
private = 1
885
voice = 2
886
group = 3
887
category = 4
888
news = 5
889
news_thread = 10
890
public_thread = 11
891
private_thread = 12
892
stage_voice = 13
893
forum = 15
894
895
class MessageType(Enum):
896
"""Discord message types."""
897
default = 0
898
recipient_add = 1
899
recipient_remove = 2
900
call = 3
901
channel_name_change = 4
902
channel_icon_change = 5
903
pins_add = 6
904
new_member = 7
905
premium_guild_subscription = 8
906
premium_guild_tier_1 = 9
907
premium_guild_tier_2 = 10
908
premium_guild_tier_3 = 11
909
channel_follow_add = 12
910
guild_discovery_disqualified = 14
911
guild_discovery_requalified = 15
912
guild_discovery_grace_period_initial_warning = 16
913
guild_discovery_grace_period_final_warning = 17
914
thread_created = 18
915
reply = 19
916
chat_input_command = 20
917
thread_starter_message = 21
918
guild_invite_reminder = 22
919
context_menu_command = 23
920
auto_moderation_action = 24
921
922
class ActivityType(Enum):
923
"""Activity types for user presence."""
924
unknown = -1
925
playing = 0
926
streaming = 1
927
listening = 2
928
watching = 3
929
custom = 4
930
competing = 5
931
932
class VerificationLevel(Enum):
933
"""Guild verification levels."""
934
none = 0
935
low = 1
936
medium = 2
937
high = 3
938
highest = 4
939
940
class ContentFilter(Enum):
941
"""Explicit content filter levels."""
942
disabled = 0
943
no_role = 1
944
all_members = 2
945
946
class NotificationLevel(Enum):
947
"""Default notification levels."""
948
all_messages = 0
949
only_mentions = 1
950
951
class NSFWLevel(Enum):
952
"""NSFW content levels."""
953
default = 0
954
explicit = 1
955
safe = 2
956
age_restricted = 3
957
958
class VideoQualityMode(Enum):
959
"""Voice channel video quality."""
960
auto = 1
961
full = 2
962
963
class WebhookType(Enum):
964
"""Webhook types."""
965
incoming = 1
966
channel_follower = 2
967
application = 3
968
969
class ExpireBehaviour(Enum):
970
"""Integration expire behavior."""
971
remove_role = 0
972
kick = 1
973
974
ExpireBehavior = ExpireBehaviour # American spelling alias
975
976
class StickerType(Enum):
977
"""Sticker types."""
978
standard = 1
979
guild = 2
980
981
class StickerFormatType(Enum):
982
"""Sticker format types."""
983
png = 1
984
apng = 2
985
lottie = 3
986
gif = 4
987
988
class InviteTarget(Enum):
989
"""Invite target types."""
990
unknown = 0
991
stream = 1
992
embedded_application = 2
993
994
class VoiceRegion(Enum):
995
"""Voice server regions."""
996
amsterdam = "amsterdam"
997
brazil = "brazil"
998
dubai = "dubai"
999
eu_central = "eu-central"
1000
eu_west = "eu-west"
1001
europe = "europe"
1002
frankfurt = "frankfurt"
1003
hongkong = "hongkong"
1004
india = "india"
1005
japan = "japan"
1006
london = "london"
1007
russia = "russia"
1008
singapore = "singapore"
1009
southafrica = "southafrica"
1010
sydney = "sydney"
1011
us_central = "us-central"
1012
us_east = "us-east"
1013
us_south = "us-south"
1014
us_west = "us-west"
1015
vip_amsterdam = "vip-amsterdam"
1016
vip_us_east = "vip-us-east"
1017
vip_us_west = "vip-us-west"
1018
```
1019
1020
### Flags and Bitfields
1021
1022
Flag classes for representing Discord's bitfield flags.
1023
1024
```python { .api }
1025
class SystemChannelFlags:
1026
"""System channel behavior flags."""
1027
1028
@property
1029
def suppress_join_notifications(self) -> bool: ...
1030
@property
1031
def suppress_premium_subscriptions(self) -> bool: ...
1032
@property
1033
def suppress_guild_reminder_notifications(self) -> bool: ...
1034
@property
1035
def suppress_join_notification_replies(self) -> bool: ...
1036
@property
1037
def suppress_role_subscription_purchase_notifications(self) -> bool: ...
1038
@property
1039
def suppress_role_subscription_purchase_notification_replies(self) -> bool: ...
1040
1041
class MessageFlags:
1042
"""Message feature flags."""
1043
1044
@property
1045
def crossposted(self) -> bool: ...
1046
@property
1047
def is_crosspost(self) -> bool: ...
1048
@property
1049
def suppress_embeds(self) -> bool: ...
1050
@property
1051
def source_message_deleted(self) -> bool: ...
1052
@property
1053
def urgent(self) -> bool: ...
1054
@property
1055
def has_thread(self) -> bool: ...
1056
@property
1057
def ephemeral(self) -> bool: ...
1058
@property
1059
def loading(self) -> bool: ...
1060
@property
1061
def failed_to_mention_some_roles_in_thread(self) -> bool: ...
1062
@property
1063
def suppress_notifications(self) -> bool: ...
1064
1065
class PublicUserFlags:
1066
"""Publicly visible user flags."""
1067
1068
@property
1069
def staff(self) -> bool: ...
1070
@property
1071
def partner(self) -> bool: ...
1072
@property
1073
def hypesquad(self) -> bool: ...
1074
@property
1075
def bug_hunter(self) -> bool: ...
1076
@property
1077
def hypesquad_bravery(self) -> bool: ...
1078
@property
1079
def hypesquad_brilliance(self) -> bool: ...
1080
@property
1081
def hypesquad_balance(self) -> bool: ...
1082
@property
1083
def early_supporter(self) -> bool: ...
1084
@property
1085
def team_user(self) -> bool: ...
1086
@property
1087
def bug_hunter_level_2(self) -> bool: ...
1088
@property
1089
def verified_bot(self) -> bool: ...
1090
@property
1091
def verified_bot_developer(self) -> bool: ...
1092
@property
1093
def discord_certified_moderator(self) -> bool: ...
1094
@property
1095
def bot_http_interactions(self) -> bool: ...
1096
@property
1097
def spammer(self) -> bool: ...
1098
@property
1099
def active_developer(self) -> bool: ...
1100
1101
class ApplicationFlags:
1102
"""Application feature flags."""
1103
1104
@property
1105
def gateway_presence(self) -> bool: ...
1106
@property
1107
def gateway_presence_limited(self) -> bool: ...
1108
@property
1109
def gateway_guild_members(self) -> bool: ...
1110
@property
1111
def gateway_guild_members_limited(self) -> bool: ...
1112
@property
1113
def verification_pending_guild_limit(self) -> bool: ...
1114
@property
1115
def embedded(self) -> bool: ...
1116
@property
1117
def gateway_message_content(self) -> bool: ...
1118
@property
1119
def gateway_message_content_limited(self) -> bool: ...
1120
@property
1121
def application_command_badge(self) -> bool: ...
1122
1123
class ChannelFlags:
1124
"""Channel feature flags."""
1125
1126
@property
1127
def pinned(self) -> bool: ...
1128
@property
1129
def require_tag(self) -> bool: ...
1130
1131
class AttachmentFlags:
1132
"""File attachment flags."""
1133
1134
@property
1135
def is_remix(self) -> bool: ...
1136
1137
class RoleFlags:
1138
"""Role feature flags."""
1139
1140
@property
1141
def in_prompt(self) -> bool: ...
1142
1143
class SKUFlags:
1144
"""SKU feature flags."""
1145
1146
@property
1147
def available(self) -> bool: ...
1148
@property
1149
def guild_subscription(self) -> bool: ...
1150
@property
1151
def user_subscription(self) -> bool: ...
1152
1153
class MemberFlags:
1154
"""Guild member flags."""
1155
1156
@property
1157
def did_rejoin(self) -> bool: ...
1158
@property
1159
def completed_onboarding(self) -> bool: ...
1160
@property
1161
def bypasses_verification(self) -> bool: ...
1162
@property
1163
def started_onboarding(self) -> bool: ...
1164
```
1165
1166
### Audio and Voice Utilities
1167
1168
Audio-related utilities and voice connection support.
1169
1170
```python { .api }
1171
# Basic Audio Support
1172
class AudioSource:
1173
"""Base class for audio sources."""
1174
1175
def read(self) -> bytes:
1176
"""Read 20ms of audio data."""
1177
1178
def is_opus(self) -> bool:
1179
"""Whether the source provides Opus data."""
1180
1181
def cleanup(self) -> None:
1182
"""Clean up the audio source."""
1183
1184
class PCMAudio(AudioSource):
1185
"""Raw PCM audio source."""
1186
1187
def __init__(self, stream: io.IOBase) -> None: ...
1188
1189
class FFmpegAudio(AudioSource):
1190
"""Audio processed through FFmpeg."""
1191
1192
def __init__(self, source: str, **kwargs) -> None: ...
1193
1194
class FFmpegPCMAudio(AudioSource):
1195
"""PCM audio processed through FFmpeg."""
1196
1197
def __init__(self, source: str, **kwargs) -> None: ...
1198
1199
class FFmpegOpusAudio(AudioSource):
1200
"""Opus audio processed through FFmpeg."""
1201
1202
def __init__(self, source: str, **kwargs) -> None: ...
1203
1204
class PCMVolumeTransformer(AudioSource):
1205
"""Volume control for PCM audio."""
1206
1207
def __init__(self, original: AudioSource, volume: float = 1.0) -> None: ...
1208
1209
@property
1210
def volume(self) -> float: ...
1211
1212
@volume.setter
1213
def volume(self, value: float) -> None: ...
1214
1215
# Voice Client Support
1216
class VoiceClient:
1217
"""Voice connection client."""
1218
1219
@property
1220
def latency(self) -> float: ...
1221
@property
1222
def average_latency(self) -> float: ...
1223
1224
def is_connected(self) -> bool: ...
1225
def is_playing(self) -> bool: ...
1226
def is_paused(self) -> bool: ...
1227
1228
def play(self, source: AudioSource, *, after: Callable = None) -> None: ...
1229
def pause(self) -> None: ...
1230
def resume(self) -> None: ...
1231
def stop(self) -> None: ...
1232
1233
async def disconnect(self, *, force: bool = False) -> None: ...
1234
async def move_to(self, channel: VoiceChannel) -> None: ...
1235
1236
class VoiceProtocol:
1237
"""Base voice protocol class."""
1238
pass
1239
```
1240
1241
### Context Managers and Utilities
1242
1243
Utility context managers for common operations.
1244
1245
```python { .api }
1246
class Typing:
1247
"""
1248
Context manager for showing typing indicator.
1249
"""
1250
1251
def __init__(self, messageable: Messageable) -> None: ...
1252
1253
async def __aenter__(self) -> Typing: ...
1254
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...
1255
1256
def __enter__(self) -> Typing: ...
1257
def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...
1258
1259
# Generic Discord Object
1260
class Object:
1261
"""
1262
Generic Discord object with just an ID.
1263
Useful for operations that only need an ID.
1264
"""
1265
1266
def __init__(self, id: int) -> None: ...
1267
1268
@property
1269
def id(self) -> int: ...
1270
@property
1271
def created_at(self) -> datetime: ...
1272
```
1273
1274
### Mention Management
1275
1276
Control which mentions are allowed in messages.
1277
1278
```python { .api }
1279
class AllowedMentions:
1280
"""
1281
Controls which mentions are processed in messages.
1282
"""
1283
1284
def __init__(
1285
self,
1286
*,
1287
everyone: bool = None,
1288
users: Union[bool, List[Snowflake]] = None,
1289
roles: Union[bool, List[Snowflake]] = None,
1290
replied_user: bool = None
1291
) -> None:
1292
"""
1293
Create allowed mentions configuration.
1294
1295
Parameters:
1296
- everyone: bool - Whether to allow @everyone/@here mentions
1297
- users: Union[bool, List[Snowflake]] - User mention settings
1298
- roles: Union[bool, List[Snowflake]] - Role mention settings
1299
- replied_user: bool - Whether to mention the replied-to user
1300
"""
1301
1302
@classmethod
1303
def all(cls) -> AllowedMentions:
1304
"""Allow all mentions."""
1305
1306
@classmethod
1307
def none(cls) -> AllowedMentions:
1308
"""Allow no mentions."""
1309
1310
@property
1311
def everyone(self) -> bool: ...
1312
@property
1313
def users(self) -> Union[bool, List[Snowflake]]: ...
1314
@property
1315
def roles(self) -> Union[bool, List[Snowflake]]: ...
1316
@property
1317
def replied_user(self) -> bool: ...
1318
```
1319
1320
The utilities and helpers provide essential tools, constants, and helper functions that make Discord bot development more efficient and provide access to Discord's rich feature set including colors, embeds, file handling, audio support, and comprehensive utility functions for common operations.