-
Notifications
You must be signed in to change notification settings - Fork 139
/
converter.py
1322 lines (1014 loc) · 42.7 KB
/
converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: MIT
from __future__ import annotations
import functools
import inspect
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
Iterable,
List,
Literal,
Optional,
Protocol,
Tuple,
Type,
TypeVar,
Union,
runtime_checkable,
)
import disnake
from .context import AnyContext, Context
from .errors import (
BadArgument,
BadBoolArgument,
BadColourArgument,
BadInviteArgument,
BadLiteralArgument,
BadUnionArgument,
ChannelNotFound,
ChannelNotReadable,
CommandError,
ConversionError,
EmojiNotFound,
GuildNotFound,
GuildScheduledEventNotFound,
GuildStickerNotFound,
MemberNotFound,
MessageNotFound,
NoPrivateMessage,
ObjectNotFound,
PartialEmojiConversionFailure,
RoleNotFound,
ThreadNotFound,
UserNotFound,
)
if TYPE_CHECKING:
from disnake.abc import MessageableChannel
# TODO: USE ACTUAL FUNCTIONS INSTEAD OF USELESS CLASSES
__all__ = (
"Converter",
"IDConverter",
"ObjectConverter",
"MemberConverter",
"UserConverter",
"PartialMessageConverter",
"MessageConverter",
"GuildChannelConverter",
"TextChannelConverter",
"VoiceChannelConverter",
"StageChannelConverter",
"CategoryChannelConverter",
"ForumChannelConverter",
"ThreadConverter",
"ColourConverter",
"ColorConverter",
"RoleConverter",
"GameConverter",
"InviteConverter",
"GuildConverter",
"EmojiConverter",
"PartialEmojiConverter",
"GuildStickerConverter",
"PermissionsConverter",
"GuildScheduledEventConverter",
"clean_content",
"Greedy",
"run_converters",
)
_utils_get = disnake.utils.get
T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)
CT = TypeVar("CT", bound=disnake.abc.GuildChannel)
TT = TypeVar("TT", bound=disnake.Thread)
def _get_from_guilds(
client: disnake.Client, func: Callable[[disnake.Guild], Optional[T]]
) -> Optional[T]:
for guild in client.guilds:
if result := func(guild):
return result
return None
@runtime_checkable
class Converter(Protocol[T_co]):
"""The base class of custom converters that require the :class:`.Context`
or :class:`.ApplicationCommandInteraction` to be passed to be useful.
This allows you to implement converters that function similar to the
special cased ``disnake`` classes.
Classes that derive from this should override the :meth:`~.Converter.convert`
method to do its conversion logic. This method must be a :ref:`coroutine <coroutine>`.
"""
async def convert(self, ctx: AnyContext, argument: str) -> T_co:
"""|coro|
The method to override to do conversion logic.
If an error is found while converting, it is recommended to
raise a :exc:`.CommandError` derived exception as it will
properly propagate to the error handlers.
Parameters
----------
ctx: Union[:class:`.Context`, :class:`.ApplicationCommandInteraction`]
The invocation context that the argument is being used in.
argument: :class:`str`
The argument that is being converted.
Raises
------
CommandError
A generic exception occurred when converting the argument.
BadArgument
The converter failed to convert the argument.
"""
raise NotImplementedError("Derived classes need to implement this.")
_ID_REGEX = re.compile(r"([0-9]{17,19})$")
class IDConverter(Converter[T_co]):
@staticmethod
def _get_id_match(argument: str) -> Optional[re.Match[str]]:
return _ID_REGEX.match(argument)
class ObjectConverter(IDConverter[disnake.Object]):
"""Converts to a :class:`~disnake.Object`.
The argument must follow the valid ID or mention formats (e.g. `<@80088516616269824>`).
.. versionadded:: 2.0
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by member, role, or channel mention.
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Object:
match = self._get_id_match(argument) or re.match(
r"<(?:@(?:!|&)?|#)([0-9]{17,19})>$", argument
)
if match is None:
raise ObjectNotFound(argument)
result = int(match.group(1))
return disnake.Object(id=result)
class MemberConverter(IDConverter[disnake.Member]):
"""Converts to a :class:`~disnake.Member`.
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID
2. Lookup by mention
3. Lookup by username#discrim
4. Lookup by username#0
5. Lookup by nickname
6. Lookup by global name
7. Lookup by username
The name resolution order matches the one used by :meth:`.Guild.get_member_named`.
.. versionchanged:: 1.5
Raise :exc:`.MemberNotFound` instead of generic :exc:`.BadArgument`
.. versionchanged:: 1.5.1
This converter now lazily fetches members from the gateway and HTTP APIs,
optionally caching the result if :attr:`.MemberCacheFlags.joined` is enabled.
.. versionchanged:: 2.9
Name resolution order changed from ``username > nick`` to
``nick > global_name > username`` to account for the username migration.
"""
async def query_member_named(
self, guild: disnake.Guild, argument: str
) -> Optional[disnake.Member]:
cache = guild._state.member_cache_flags.joined
username, _, discriminator = argument.rpartition("#")
if username and (
discriminator == "0" or (len(discriminator) == 4 and discriminator.isdecimal())
):
# legacy behavior
members = await guild.query_members(username, limit=100, cache=cache)
return _utils_get(members, name=username, discriminator=discriminator)
else:
members = await guild.query_members(argument, limit=100, cache=cache)
return disnake.utils.find(
lambda m: m.nick == argument or m.global_name == argument or m.name == argument,
members,
)
async def query_member_by_id(
self, bot: disnake.Client, guild: disnake.Guild, user_id: int
) -> Optional[disnake.Member]:
ws = bot._get_websocket(shard_id=guild.shard_id)
cache = guild._state.member_cache_flags.joined
if ws.is_ratelimited():
# If we're being rate limited on the WS, then fall back to using the HTTP API
# So we don't have to wait ~60 seconds for the query to finish
try:
member = await guild.fetch_member(user_id)
except disnake.HTTPException:
return None
if cache:
guild._add_member(member)
return member
# If we're not being rate limited then we can use the websocket to actually query
members = await guild.query_members(limit=1, user_ids=[user_id], cache=cache)
if not members:
return None
return members[0]
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Member:
bot: disnake.Client = ctx.bot
match = self._get_id_match(argument) or re.match(r"<@!?([0-9]{17,19})>$", argument)
guild = ctx.guild
result: Optional[disnake.Member] = None
user_id: Optional[int] = None
if match is None:
# not a mention...
if guild:
result = guild.get_member_named(argument)
else:
result = _get_from_guilds(bot, lambda g: g.get_member_named(argument))
else:
user_id = int(match.group(1))
if guild:
mentions: Iterable[disnake.Member]
if isinstance(ctx, Context):
mentions = (
user for user in ctx.message.mentions if isinstance(user, disnake.Member)
)
else:
mentions = []
result = guild.get_member(user_id) or _utils_get(mentions, id=user_id)
else:
result = _get_from_guilds(bot, lambda g: g.get_member(user_id))
if result is None:
if guild is None:
raise MemberNotFound(argument)
if user_id is not None:
result = await self.query_member_by_id(bot, guild, user_id)
else:
result = await self.query_member_named(guild, argument)
if not result:
raise MemberNotFound(argument)
return result
class UserConverter(IDConverter[disnake.User]):
"""Converts to a :class:`~disnake.User`.
All lookups are via the global user cache.
The lookup strategy is as follows (in order):
1. Lookup by ID
2. Lookup by mention
3. Lookup by username#discrim
4. Lookup by username#0
5. Lookup by global name
6. Lookup by username
.. versionchanged:: 1.5
Raise :exc:`.UserNotFound` instead of generic :exc:`.BadArgument`
.. versionchanged:: 1.6
This converter now lazily fetches users from the HTTP APIs if an ID is passed
and it's not available in cache.
.. versionchanged:: 2.9
Now takes :attr:`~disnake.User.global_name` into account.
No longer automatically removes ``"@"`` prefix from arguments.
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.User:
match = self._get_id_match(argument) or re.match(r"<@!?([0-9]{17,19})>$", argument)
state = ctx._state
bot: disnake.Client = ctx.bot
result: Optional[Union[disnake.User, disnake.Member]] = None
if match is not None:
user_id = int(match.group(1))
mentions: Iterable[Union[disnake.User, disnake.Member]]
if isinstance(ctx, Context):
mentions = ctx.message.mentions
else:
mentions = []
result = bot.get_user(user_id) or _utils_get(mentions, id=user_id)
if result is None:
try:
result = await bot.fetch_user(user_id)
except disnake.HTTPException:
raise UserNotFound(argument) from None
if isinstance(result, disnake.Member):
return result._user
return result
username, _, discriminator = argument.rpartition("#")
# n.b. there's no builtin method that only matches arabic digits, `isdecimal` is the closest one.
# it really doesn't matter much, worst case is unnecessary computations
if username and (
discriminator == "0" or (len(discriminator) == 4 and discriminator.isdecimal())
):
# legacy behavior
result = _utils_get(state._users.values(), name=username, discriminator=discriminator)
if result is not None:
return result
result = disnake.utils.find(
lambda u: u.global_name == argument or u.name == argument,
state._users.values(),
)
if result is None:
raise UserNotFound(argument)
return result
class PartialMessageConverter(Converter[disnake.PartialMessage]):
"""Converts to a :class:`~disnake.PartialMessage`.
.. versionadded:: 1.7
The creation strategy is as follows (in order):
1. By "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID")
2. By message ID (The message is assumed to be in the context channel.)
3. By message URL
"""
@staticmethod
def _get_id_matches(ctx: AnyContext, argument: str) -> Tuple[Optional[int], int, int]:
id_regex = re.compile(r"(?:(?P<channel_id>[0-9]{17,19})-)?(?P<message_id>[0-9]{17,19})$")
link_regex = re.compile(
r"https?://(?:(ptb|canary|www)\.)?discord(?:app)?\.com/channels/"
r"(?P<guild_id>[0-9]{17,19}|@me)"
r"/(?P<channel_id>[0-9]{17,19})/(?P<message_id>[0-9]{17,19})/?$"
)
match = id_regex.match(argument) or link_regex.match(argument)
if not match:
raise MessageNotFound(argument)
data = match.groupdict()
channel_id = disnake.utils._get_as_snowflake(data, "channel_id") or ctx.channel.id
message_id = int(data["message_id"])
guild_id_str: Optional[str] = data.get("guild_id")
if guild_id_str is None:
guild_id = ctx.guild and ctx.guild.id
elif guild_id_str == "@me":
guild_id = None
else:
guild_id = int(guild_id_str)
return guild_id, message_id, channel_id
@staticmethod
def _resolve_channel(
ctx: AnyContext, guild_id: Optional[int], channel_id: int
) -> Optional[MessageableChannel]:
bot: disnake.Client = ctx.bot
if guild_id is None:
return bot.get_channel(channel_id) if channel_id else ctx.channel # type: ignore
guild = bot.get_guild(guild_id)
if guild is not None:
return guild._resolve_channel(channel_id) # type: ignore
return None
async def convert(self, ctx: AnyContext, argument: str) -> disnake.PartialMessage:
guild_id, message_id, channel_id = self._get_id_matches(ctx, argument)
channel = self._resolve_channel(ctx, guild_id, channel_id)
if not channel:
raise ChannelNotFound(str(channel_id))
return disnake.PartialMessage(channel=channel, id=message_id)
class MessageConverter(IDConverter[disnake.Message]):
"""Converts to a :class:`~disnake.Message`.
.. versionadded:: 1.1
The lookup strategy is as follows (in order):
1. Lookup by "{channel ID}-{message ID}" (retrieved by shift-clicking on "Copy ID")
2. Lookup by message ID (the message **must** be in the context channel)
3. Lookup by message URL
.. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound`, :exc:`.MessageNotFound` or :exc:`.ChannelNotReadable` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Message:
guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(ctx, argument)
bot: disnake.Client = ctx.bot
message = bot._connection._get_message(message_id)
if message:
return message
channel = PartialMessageConverter._resolve_channel(ctx, guild_id, channel_id)
if not channel:
raise ChannelNotFound(str(channel_id))
try:
return await channel.fetch_message(message_id)
except disnake.NotFound:
raise MessageNotFound(argument) from None
except disnake.Forbidden:
raise ChannelNotReadable(channel) from None # type: ignore
class GuildChannelConverter(IDConverter[disnake.abc.GuildChannel]):
"""Converts to a :class:`.abc.GuildChannel`.
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name.
.. versionadded:: 2.0
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.abc.GuildChannel:
return self._resolve_channel(ctx, argument, "channels", disnake.abc.GuildChannel)
@staticmethod
def _resolve_channel(ctx: AnyContext, argument: str, attribute: str, type: Type[CT]) -> CT:
bot: disnake.Client = ctx.bot
match = IDConverter._get_id_match(argument) or re.match(r"<#([0-9]{17,19})>$", argument)
result: Optional[disnake.abc.GuildChannel] = None
guild = ctx.guild
if match is None:
# not a mention
if guild:
iterable: Iterable[CT] = getattr(guild, attribute)
result = _utils_get(iterable, name=argument)
else:
result = disnake.utils.find(
lambda c: isinstance(c, type) and c.name == argument, bot.get_all_channels()
)
else:
channel_id = int(match.group(1))
if guild:
result = guild.get_channel(channel_id)
else:
result = _get_from_guilds(bot, lambda g: g.get_channel(channel_id))
if not isinstance(result, type):
raise ChannelNotFound(argument)
return result
@staticmethod
def _resolve_thread(ctx: AnyContext, argument: str, attribute: str, type: Type[TT]) -> TT:
match = IDConverter._get_id_match(argument) or re.match(r"<#([0-9]{17,19})>$", argument)
result: Optional[disnake.Thread] = None
guild = ctx.guild
if match is None:
# not a mention
if guild:
iterable: Iterable[TT] = getattr(guild, attribute)
result = _utils_get(iterable, name=argument)
else:
thread_id = int(match.group(1))
if guild:
result = guild.get_thread(thread_id)
if not isinstance(result, type):
raise ThreadNotFound(argument)
return result
class TextChannelConverter(IDConverter[disnake.TextChannel]):
"""Converts to a :class:`~disnake.TextChannel`.
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
.. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.TextChannel:
return GuildChannelConverter._resolve_channel(
ctx, argument, "text_channels", disnake.TextChannel
)
class VoiceChannelConverter(IDConverter[disnake.VoiceChannel]):
"""Converts to a :class:`~disnake.VoiceChannel`.
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
.. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.VoiceChannel:
return GuildChannelConverter._resolve_channel(
ctx, argument, "voice_channels", disnake.VoiceChannel
)
class StageChannelConverter(IDConverter[disnake.StageChannel]):
"""Converts to a :class:`~disnake.StageChannel`.
.. versionadded:: 1.7
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.StageChannel:
return GuildChannelConverter._resolve_channel(
ctx, argument, "stage_channels", disnake.StageChannel
)
class CategoryChannelConverter(IDConverter[disnake.CategoryChannel]):
"""Converts to a :class:`~disnake.CategoryChannel`.
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
.. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.CategoryChannel:
return GuildChannelConverter._resolve_channel(
ctx, argument, "categories", disnake.CategoryChannel
)
class ForumChannelConverter(IDConverter[disnake.ForumChannel]):
"""Converts to a :class:`~disnake.ForumChannel`.
.. versionadded:: 2.5
All lookups are via the local guild. If in a DM context, then the lookup
is done by the global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.ForumChannel:
return GuildChannelConverter._resolve_channel(
ctx, argument, "forum_channels", disnake.ForumChannel
)
class ThreadConverter(IDConverter[disnake.Thread]):
"""Coverts to a :class:`~disnake.Thread`.
All lookups are via the local guild.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name.
.. versionadded:: 2.0
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Thread:
return GuildChannelConverter._resolve_thread(ctx, argument, "threads", disnake.Thread)
class ColourConverter(Converter[disnake.Colour]):
"""Converts to a :class:`~disnake.Colour`.
.. versionchanged:: 1.5
Add an alias named ColorConverter
The following formats are accepted:
- ``0x<hex>``
- ``#<hex>``
- ``0x#<hex>``
- ``rgb(<number>, <number>, <number>)``
- Any of the ``classmethod`` in :class:`~disnake.Colour`
- The ``_`` in the name can be optionally replaced with spaces.
Like CSS, ``<number>`` can be either 0-255 or 0-100% and ``<hex>`` can be
either a 6 digit hex number or a 3 digit hex shortcut (e.g. #fff).
.. versionchanged:: 1.5
Raise :exc:`.BadColourArgument` instead of generic :exc:`.BadArgument`
.. versionchanged:: 1.7
Added support for ``rgb`` function and 3-digit hex shortcuts
"""
RGB_REGEX = re.compile(
r"rgb\s*\((?P<r>[0-9]{1,3}%?)\s*,\s*(?P<g>[0-9]{1,3}%?)\s*,\s*(?P<b>[0-9]{1,3}%?)\s*\)"
)
def parse_hex_number(self, argument: str) -> disnake.Color:
arg = "".join(i * 2 for i in argument) if len(argument) == 3 else argument
try:
value = int(arg, base=16)
if not (0 <= value <= 0xFFFFFF):
raise BadColourArgument(argument)
except ValueError:
raise BadColourArgument(argument) from None
else:
return disnake.Color(value=value)
def parse_rgb_number(self, argument: str, number: str) -> int:
if number[-1] == "%":
value = int(number[:-1])
if not (0 <= value <= 100):
raise BadColourArgument(argument)
return round(255 * (value / 100))
value = int(number)
if not (0 <= value <= 255):
raise BadColourArgument(argument)
return value
def parse_rgb(self, argument: str, *, regex: re.Pattern[str] = RGB_REGEX) -> disnake.Color:
match = regex.match(argument)
if match is None:
raise BadColourArgument(argument)
red = self.parse_rgb_number(argument, match.group("r"))
green = self.parse_rgb_number(argument, match.group("g"))
blue = self.parse_rgb_number(argument, match.group("b"))
return disnake.Color.from_rgb(red, green, blue)
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Color:
if argument[0] == "#":
return self.parse_hex_number(argument[1:])
if argument[0:2] == "0x":
rest = argument[2:]
# Legacy backwards compatible syntax
if rest.startswith("#"):
return self.parse_hex_number(rest[1:])
return self.parse_hex_number(rest)
arg = argument.lower()
if arg[0:3] == "rgb":
return self.parse_rgb(arg)
arg = arg.replace(" ", "_")
method = getattr(disnake.Colour, arg, None)
if arg.startswith("from_") or method is None or not inspect.ismethod(method):
raise BadColourArgument(arg)
return method()
ColorConverter = ColourConverter
class RoleConverter(IDConverter[disnake.Role]):
"""Converts to a :class:`~disnake.Role`.
All lookups are via the local guild. If in a DM context, the converter raises
:exc:`.NoPrivateMessage` exception.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by mention.
3. Lookup by name
.. versionchanged:: 1.5
Raise :exc:`.RoleNotFound` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Role:
guild = ctx.guild
if not guild:
raise NoPrivateMessage
match = self._get_id_match(argument) or re.match(r"<@&([0-9]{17,19})>$", argument)
if match:
result = guild.get_role(int(match.group(1)))
else:
result = _utils_get(guild._roles.values(), name=argument)
if result is None:
raise RoleNotFound(argument)
return result
class GameConverter(Converter[disnake.Game]):
"""Converts to :class:`~disnake.Game`."""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Game:
return disnake.Game(name=argument)
class InviteConverter(Converter[disnake.Invite]):
"""Converts to a :class:`~disnake.Invite`.
This is done via an HTTP request using :meth:`.Bot.fetch_invite`.
.. versionchanged:: 1.5
Raise :exc:`.BadInviteArgument` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Invite:
try:
return await ctx.bot.fetch_invite(argument)
except Exception as exc:
raise BadInviteArgument(argument) from exc
class GuildConverter(IDConverter[disnake.Guild]):
"""Converts to a :class:`~disnake.Guild`.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by name. (There is no disambiguation for Guilds with multiple matching names).
.. versionadded:: 1.7
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Guild:
match = self._get_id_match(argument)
bot: disnake.Client = ctx.bot
result: Optional[disnake.Guild] = None
if match is not None:
guild_id = int(match.group(1))
result = bot.get_guild(guild_id)
if result is None:
result = _utils_get(bot.guilds, name=argument)
if result is None:
raise GuildNotFound(argument)
return result
class EmojiConverter(IDConverter[disnake.Emoji]):
"""Converts to a :class:`~disnake.Emoji`.
All lookups are done for the local guild first, if available. If that lookup
fails, then it checks the client's global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID.
2. Lookup by extracting ID from the emoji.
3. Lookup by name
.. versionchanged:: 1.5
Raise :exc:`.EmojiNotFound` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Emoji:
match = self._get_id_match(argument) or re.match(
r"<a?:[a-zA-Z0-9\_]{1,32}:([0-9]{17,19})>$", argument
)
result: Optional[disnake.Emoji] = None
bot = ctx.bot
guild = ctx.guild
if match is None:
# Try to get the emoji by name. Try local guild first.
if guild:
result = _utils_get(guild.emojis, name=argument)
if result is None:
result = _utils_get(bot.emojis, name=argument)
else:
# Try to look up emoji by id.
result = bot.get_emoji(int(match.group(1)))
if result is None:
raise EmojiNotFound(argument)
return result
class PartialEmojiConverter(Converter[disnake.PartialEmoji]):
"""Converts to a :class:`~disnake.PartialEmoji`.
This is done by extracting the animated flag, name and ID from the emoji.
.. versionchanged:: 1.5
Raise :exc:`.PartialEmojiConversionFailure` instead of generic :exc:`.BadArgument`
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.PartialEmoji:
match = re.match(r"<(a?):([a-zA-Z0-9\_]{1,32}):([0-9]{17,19})>$", argument)
if match:
emoji_animated = bool(match.group(1))
emoji_name: str = match.group(2)
emoji_id = int(match.group(3))
return disnake.PartialEmoji.with_state(
ctx.bot._connection, animated=emoji_animated, name=emoji_name, id=emoji_id
)
raise PartialEmojiConversionFailure(argument)
class GuildStickerConverter(IDConverter[disnake.GuildSticker]):
"""Converts to a :class:`~disnake.GuildSticker`.
All lookups are done for the local guild first, if available. If that lookup
fails, then it checks the client's global cache.
The lookup strategy is as follows (in order):
1. Lookup by ID
2. Lookup by name
.. versionadded:: 2.0
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.GuildSticker:
match = self._get_id_match(argument)
result = None
bot: disnake.Client = ctx.bot
guild = ctx.guild
if match is None:
# Try to get the sticker by name. Try local guild first.
if guild:
result = _utils_get(guild.stickers, name=argument)
if result is None:
result = _utils_get(bot.stickers, name=argument)
else:
# Try to look up sticker by id.
result = bot.get_sticker(int(match.group(1)))
if result is None:
raise GuildStickerNotFound(argument)
return result
class PermissionsConverter(Converter[disnake.Permissions]):
"""Converts to a :class:`~disnake.Permissions`.
Accepts an integer or a string of space-separated permission names (or just a single one) as input.
.. versionadded:: 2.3
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.Permissions:
# try the permission bit value
try:
value = int(argument)
except ValueError:
pass
else:
return disnake.Permissions(value)
argument = argument.replace("server", "guild")
# try multiple attributes, then a single one
perms: List[disnake.Permissions] = []
for name in argument.split():
attr = getattr(disnake.Permissions, name, None)
if attr is None:
break
if callable(attr):
perms.append(attr())
else:
perms.append(disnake.Permissions(**{name: True}))
else:
return functools.reduce(lambda a, b: disnake.Permissions(a.value | b.value), perms)
name = argument.replace(" ", "_")
attr = getattr(disnake.Permissions, name, None)
if attr is None:
raise BadArgument(f"Invalid Permissions: {name!r}")
if callable(attr):
return attr()
else:
return disnake.Permissions(**{name: True})
class GuildScheduledEventConverter(IDConverter[disnake.GuildScheduledEvent]):
"""Converts to a :class:`~disnake.GuildScheduledEvent`.
The lookup strategy is as follows (in order):
1. Lookup by ID (in current guild)
2. Lookup as event URL
3. Lookup by name (in current guild; there is no disambiguation for scheduled events with multiple matching names)
.. versionadded:: 2.5
"""
async def convert(self, ctx: AnyContext, argument: str) -> disnake.GuildScheduledEvent:
event_regex = re.compile(
r"https?://(?:(?:ptb|canary|www)\.)?discord(?:app)?\.com/events/"
r"([0-9]{17,19})/([0-9]{17,19})/?$"
)
bot: disnake.Client = ctx.bot
result: Optional[disnake.GuildScheduledEvent] = None
guild = ctx.guild
# 1.
if guild and (match := self._get_id_match(argument)):
result = guild.get_scheduled_event(int(match.group(1)))
# 2.
if not result and (match := event_regex.match(argument)):
event_guild = bot.get_guild(int(match.group(1)))
if event_guild:
result = event_guild.get_scheduled_event(int(match.group(2)))