Skip to content

Commit 5e6ee00

Browse files
CopilotSoheab
andcommitted
Replace InvalidArgument with TypeError and ValueError
- Replaced all 107 raise InvalidArgument statements with appropriate built-in exceptions - Removed InvalidArgument class from errors.py - Removed InvalidArgument from __all__ export - Updated all imports to remove InvalidArgument - Updated all docstrings referencing InvalidArgument - Fixed except clause in http.py to catch ValueError instead Co-authored-by: Soheab <[email protected]>
1 parent a93379e commit 5e6ee00

26 files changed

+174
-196
lines changed

discord/abc.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
from . import utils
4545
from .context_managers import Typing
4646
from .enums import ChannelType
47-
from .errors import ClientException, InvalidArgument
47+
from .errors import ClientException
4848
from .file import File, VoiceMessage
4949
from .flags import ChannelFlags, MessageFlags
5050
from .invite import Invite
@@ -357,7 +357,7 @@ async def _move(
357357
reason: str | None,
358358
) -> None:
359359
if position < 0:
360-
raise InvalidArgument("Channel position cannot be less than 0.")
360+
raise ValueError("Channel position cannot be less than 0.")
361361

362362
http = self._state.http
363363
bucket = self._sorting_bucket
@@ -460,7 +460,7 @@ async def _edit(self, options: dict[str, Any], reason: str | None) -> ChannelPay
460460
perms = []
461461
for target, perm in overwrites.items():
462462
if not isinstance(perm, PermissionOverwrite):
463-
raise InvalidArgument(f"Expected PermissionOverwrite received {perm.__class__.__name__}")
463+
raise TypeError(f"Expected PermissionOverwrite received {perm.__class__.__name__}")
464464

465465
allow, deny = perm.pair()
466466
payload = {
@@ -479,7 +479,7 @@ async def _edit(self, options: dict[str, Any], reason: str | None) -> ChannelPay
479479
pass
480480
else:
481481
if not isinstance(ch_type, ChannelType):
482-
raise InvalidArgument("type field must be of type ChannelType")
482+
raise TypeError("type field must be of type ChannelType")
483483
options["type"] = ch_type.value
484484

485485
try:
@@ -496,7 +496,7 @@ async def _edit(self, options: dict[str, Any], reason: str | None) -> ChannelPay
496496
elif default_reaction_emoji is None:
497497
pass
498498
else:
499-
raise InvalidArgument("default_reaction_emoji must be of type: GuildEmoji | int | str | None")
499+
raise TypeError("default_reaction_emoji must be of type: GuildEmoji | int | str | None")
500500

501501
options["default_reaction_emoji"] = (
502502
default_reaction_emoji._to_forum_reaction_payload() if default_reaction_emoji else None
@@ -893,7 +893,7 @@ async def set_permissions(self, target, *, overwrite=MISSING, reason=None, **per
893893
Editing channel specific permissions failed.
894894
~discord.NotFound
895895
The role or member being edited is not part of the guild.
896-
~discord.InvalidArgument
896+
TypeError or ValueError
897897
The overwrite parameter invalid or the target type was not
898898
:class:`~discord.Role` or :class:`~discord.Member`.
899899
"""
@@ -905,17 +905,17 @@ async def set_permissions(self, target, *, overwrite=MISSING, reason=None, **per
905905
elif isinstance(target, Role):
906906
perm_type = _Overwrites.ROLE
907907
else:
908-
raise InvalidArgument("target parameter must be either Member or Role")
908+
raise TypeError("target parameter must be either Member or Role")
909909

910910
if overwrite is MISSING:
911911
if len(permissions) == 0:
912-
raise InvalidArgument("No overwrite provided.")
912+
raise ValueError("No overwrite provided.")
913913
try:
914914
overwrite = PermissionOverwrite(**permissions)
915915
except (ValueError, TypeError) as e:
916-
raise InvalidArgument("Invalid permissions given to keyword arguments.") from e
916+
raise ValueError("Invalid permissions given to keyword arguments.") from e
917917
elif len(permissions) > 0:
918-
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")
918+
raise ValueError("Cannot mix overwrite and keyword arguments.")
919919

920920
# TODO: wait for event
921921

@@ -925,7 +925,7 @@ async def set_permissions(self, target, *, overwrite=MISSING, reason=None, **per
925925
(allow, deny) = overwrite.pair()
926926
await http.edit_channel_permissions(self.id, target.id, allow.value, deny.value, perm_type, reason=reason)
927927
else:
928-
raise InvalidArgument("Invalid overwrite type provided.")
928+
raise ValueError("Invalid overwrite type provided.")
929929

930930
async def _clone_impl(
931931
self: GCH,
@@ -1074,7 +1074,7 @@ async def move(self, **kwargs) -> None:
10741074
10751075
Raises
10761076
------
1077-
InvalidArgument
1077+
ValueError
10781078
An invalid position was given or a bad mix of arguments was passed.
10791079
Forbidden
10801080
You do not have permissions to move the channel.
@@ -1089,7 +1089,7 @@ async def move(self, **kwargs) -> None:
10891089
before, after = kwargs.get("before"), kwargs.get("after")
10901090
offset = kwargs.get("offset", 0)
10911091
if sum(bool(a) for a in (beginning, end, before, after)) > 1:
1092-
raise InvalidArgument("Only one of [before, after, end, beginning] can be used.")
1092+
raise ValueError("Only one of [before, after, end, beginning] can be used.")
10931093

10941094
bucket = self._sorting_bucket
10951095
parent_id = kwargs.get("category", MISSING)
@@ -1124,7 +1124,7 @@ async def move(self, **kwargs) -> None:
11241124
index = next((i + 1 for i, c in enumerate(channels) if c.id == after.id), None)
11251125

11261126
if index is None:
1127-
raise InvalidArgument("Could not resolve appropriate move position")
1127+
raise ValueError("Could not resolve appropriate move position")
11281128

11291129
channels.insert(max((index + offset), 0), self)
11301130
payload = []
@@ -1481,7 +1481,7 @@ async def send(
14811481
Sending the message failed.
14821482
~discord.Forbidden
14831483
You do not have the proper permissions to send the message.
1484-
~discord.InvalidArgument
1484+
TypeError or ValueError
14851485
The ``files`` list is not of the appropriate size,
14861486
you specified both ``file`` and ``files``,
14871487
or you specified both ``embed`` and ``embeds``,
@@ -1494,14 +1494,14 @@ async def send(
14941494
content = str(content) if content is not None else None
14951495

14961496
if embed is not None and embeds is not None:
1497-
raise InvalidArgument("cannot pass both embed and embeds parameter to send()")
1497+
raise ValueError("cannot pass both embed and embeds parameter to send()")
14981498

14991499
if embed is not None:
15001500
embed = embed.to_dict()
15011501

15021502
elif embeds is not None:
15031503
if len(embeds) > 10:
1504-
raise InvalidArgument("embeds parameter must be a list of up to 10 elements")
1504+
raise ValueError("embeds parameter must be a list of up to 10 elements")
15051505
embeds = [embed.to_dict() for embed in embeds]
15061506

15071507
flags = MessageFlags(
@@ -1537,13 +1537,13 @@ async def send(
15371537
"3.0",
15381538
)
15391539
except AttributeError:
1540-
raise InvalidArgument(
1540+
raise ValueError(
15411541
"reference parameter must be Message, MessageReference, or PartialMessage"
15421542
) from None
15431543

15441544
if view:
15451545
if not hasattr(view, "__discord_ui_view__"):
1546-
raise InvalidArgument(f"view parameter must be View not {view.__class__!r}")
1546+
raise TypeError(f"view parameter must be View not {view.__class__!r}")
15471547

15481548
components = view.to_components()
15491549
if view.is_components_v2():
@@ -1557,17 +1557,17 @@ async def send(
15571557
poll = poll.to_dict()
15581558

15591559
if file is not None and files is not None:
1560-
raise InvalidArgument("cannot pass both file and files parameter to send()")
1560+
raise ValueError("cannot pass both file and files parameter to send()")
15611561

15621562
if file is not None:
15631563
if not isinstance(file, File):
1564-
raise InvalidArgument("file parameter must be File")
1564+
raise TypeError("file parameter must be File")
15651565
files = [file]
15661566
elif files is not None:
15671567
if len(files) > 10:
1568-
raise InvalidArgument("files parameter must be a list of up to 10 elements")
1568+
raise ValueError("files parameter must be a list of up to 10 elements")
15691569
elif not all(isinstance(file, File) for file in files):
1570-
raise InvalidArgument("files parameter must be a list of File")
1570+
raise TypeError("files parameter must be a list of File")
15711571

15721572
if files is not None:
15731573
flags = flags + MessageFlags(is_voice_message=any(isinstance(f, VoiceMessage) for f in files))

discord/asset.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
import yarl
3333

3434
from . import utils
35-
from .errors import DiscordException, InvalidArgument
35+
from .errors import DiscordException
3636

3737
__all__ = ("Asset",)
3838

@@ -401,7 +401,7 @@ def replace(
401401
402402
Raises
403403
------
404-
InvalidArgument
404+
TypeError or ValueError
405405
An invalid size or format was passed.
406406
"""
407407
url = yarl.URL(self._url)
@@ -410,21 +410,21 @@ def replace(
410410
if format is not MISSING:
411411
if self._animated:
412412
if format not in VALID_ASSET_FORMATS:
413-
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
413+
raise ValueError(f"format must be one of {VALID_ASSET_FORMATS}")
414414
url = url.with_path(f"{path}.{format}")
415415
elif static_format is MISSING:
416416
if format not in VALID_STATIC_FORMATS:
417-
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
417+
raise ValueError(f"format must be one of {VALID_STATIC_FORMATS}")
418418
url = url.with_path(f"{path}.{format}")
419419

420420
if static_format is not MISSING and not self._animated:
421421
if static_format not in VALID_STATIC_FORMATS:
422-
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
422+
raise ValueError(f"static_format must be one of {VALID_STATIC_FORMATS}")
423423
url = url.with_path(f"{path}.{static_format}")
424424

425425
if size is not MISSING:
426426
if not _valid_icon_size(size):
427-
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
427+
raise ValueError("size must be a power of 2 between 16 and 4096")
428428
url = url.with_query(size=size)
429429
else:
430430
url = url.with_query(url.raw_query_string)
@@ -447,11 +447,11 @@ def with_size(self, size: int, /) -> Asset:
447447
448448
Raises
449449
------
450-
InvalidArgument
450+
TypeError or ValueError
451451
The asset had an invalid size.
452452
"""
453453
if not _valid_icon_size(size):
454-
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
454+
raise ValueError("size must be a power of 2 between 16 and 4096")
455455

456456
url = str(yarl.URL(self._url).with_query(size=size))
457457
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
@@ -471,15 +471,15 @@ def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
471471
472472
Raises
473473
------
474-
InvalidArgument
474+
TypeError or ValueError
475475
The asset has an invalid format.
476476
"""
477477

478478
if self._animated:
479479
if format not in VALID_ASSET_FORMATS:
480-
raise InvalidArgument(f"format must be one of {VALID_ASSET_FORMATS}")
480+
raise ValueError(f"format must be one of {VALID_ASSET_FORMATS}")
481481
elif format not in VALID_STATIC_FORMATS:
482-
raise InvalidArgument(f"format must be one of {VALID_STATIC_FORMATS}")
482+
raise ValueError(f"format must be one of {VALID_STATIC_FORMATS}")
483483

484484
url = yarl.URL(self._url)
485485
path, _ = os.path.splitext(url.path)
@@ -504,7 +504,7 @@ def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
504504
505505
Raises
506506
------
507-
InvalidArgument
507+
TypeError or ValueError
508508
The asset had an invalid format.
509509
"""
510510

discord/channel.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
try_enum,
5656
)
5757
from .enums import ThreadArchiveDuration as ThreadArchiveDurationEnum
58-
from .errors import ClientException, InvalidArgument
58+
from .errors import ClientException
5959
from .file import File
6060
from .flags import ChannelFlags, MessageFlags
6161
from .invite import Invite
@@ -562,7 +562,7 @@ async def follow(self, *, destination: TextChannel, reason: str | None = None) -
562562
raise ClientException("The channel must be a news channel.")
563563

564564
if not isinstance(destination, TextChannel):
565-
raise InvalidArgument(f"Expected TextChannel received {destination.__class__.__name__}")
565+
raise TypeError(f"Expected TextChannel received {destination.__class__.__name__}")
566566

567567
from .webhook import Webhook # noqa: PLC0415
568568

@@ -827,7 +827,7 @@ async def edit(self, *, reason=None, **options):
827827
828828
Raises
829829
------
830-
InvalidArgument
830+
TypeError or ValueError
831831
If position is less than 0 or greater than the number of channels, or if
832832
the permission overwrite information is not in proper form.
833833
Forbidden
@@ -1138,7 +1138,7 @@ async def edit(self, *, reason=None, **options):
11381138
11391139
Raises
11401140
------
1141-
InvalidArgument
1141+
TypeError or ValueError
11421142
If position is less than 0 or greater than the number of channels, or if
11431143
the permission overwrite information is not in proper form.
11441144
Forbidden
@@ -1245,14 +1245,14 @@ async def create_thread(
12451245
message_content = str(content) if content is not None else None
12461246

12471247
if embed is not None and embeds is not None:
1248-
raise InvalidArgument("cannot pass both embed and embeds parameter to create_thread()")
1248+
raise ValueError("cannot pass both embed and embeds parameter to create_thread()")
12491249

12501250
if embed is not None:
12511251
embed = embed.to_dict()
12521252

12531253
elif embeds is not None:
12541254
if len(embeds) > 10:
1255-
raise InvalidArgument("embeds parameter must be a list of up to 10 elements")
1255+
raise ValueError("embeds parameter must be a list of up to 10 elements")
12561256
embeds = [embed.to_dict() for embed in embeds]
12571257

12581258
if stickers is not None:
@@ -1272,7 +1272,7 @@ async def create_thread(
12721272

12731273
if view:
12741274
if not hasattr(view, "__discord_ui_view__"):
1275-
raise InvalidArgument(f"view parameter must be View not {view.__class__!r}")
1275+
raise TypeError(f"view parameter must be View not {view.__class__!r}")
12761276

12771277
components = view.to_components()
12781278
if view.is_components_v2():
@@ -1286,17 +1286,17 @@ async def create_thread(
12861286
applied_tags = [str(tag.id) for tag in applied_tags]
12871287

12881288
if file is not None and files is not None:
1289-
raise InvalidArgument("cannot pass both file and files parameter to send()")
1289+
raise ValueError("cannot pass both file and files parameter to send()")
12901290

12911291
if files is not None:
12921292
if len(files) > 10:
1293-
raise InvalidArgument("files parameter must be a list of up to 10 elements")
1293+
raise ValueError("files parameter must be a list of up to 10 elements")
12941294
elif not all(isinstance(file, File) for file in files):
1295-
raise InvalidArgument("files parameter must be a list of File")
1295+
raise TypeError("files parameter must be a list of File")
12961296

12971297
if file is not None:
12981298
if not isinstance(file, File):
1299-
raise InvalidArgument("file parameter must be File")
1299+
raise TypeError("file parameter must be File")
13001300
files = [file]
13011301

13021302
try:
@@ -1499,7 +1499,7 @@ async def edit(self, *, reason=None, **options):
14991499
15001500
Raises
15011501
------
1502-
InvalidArgument
1502+
TypeError or ValueError
15031503
If position is less than 0 or greater than the number of channels, or if
15041504
the permission overwrite information is not in proper form.
15051505
Forbidden
@@ -2074,7 +2074,7 @@ async def edit(self, *, reason=None, **options):
20742074
20752075
Raises
20762076
------
2077-
InvalidArgument
2077+
TypeError or ValueError
20782078
If the permission overwrite information is not in proper form.
20792079
Forbidden
20802080
You do not have permissions to edit the channel.
@@ -2606,7 +2606,7 @@ async def create_instance(
26062606
26072607
Raises
26082608
------
2609-
InvalidArgument
2609+
TypeError or ValueError
26102610
If the ``privacy_level`` parameter is not the proper type.
26112611
Forbidden
26122612
You do not have permissions to create a stage instance.
@@ -2622,7 +2622,7 @@ async def create_instance(
26222622

26232623
if privacy_level is not MISSING:
26242624
if not isinstance(privacy_level, StagePrivacyLevel):
2625-
raise InvalidArgument("privacy_level field must be of type PrivacyLevel")
2625+
raise TypeError("privacy_level field must be of type PrivacyLevel")
26262626

26272627
payload["privacy_level"] = privacy_level.value
26282628

@@ -2725,7 +2725,7 @@ async def edit(self, *, reason=None, **options):
27252725
27262726
Raises
27272727
------
2728-
InvalidArgument
2728+
TypeError or ValueError
27292729
If the permission overwrite information is not in proper form.
27302730
Forbidden
27312731
You do not have permissions to edit the channel.
@@ -2870,7 +2870,7 @@ async def edit(self, *, reason=None, **options):
28702870
28712871
Raises
28722872
------
2873-
InvalidArgument
2873+
TypeError or ValueError
28742874
If position is less than 0 or greater than the number of categories.
28752875
Forbidden
28762876
You do not have permissions to edit the category.

0 commit comments

Comments
 (0)