Browse Source

Remove discord.InvalidArgument

This uses TypeError and ValueError instead.
pull/7494/head
Josh 3 years ago
committed by GitHub
parent
commit
2b69b5d545
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 59
      discord/abc.py
  2. 39
      discord/asset.py
  3. 58
      discord/channel.py
  4. 16
      discord/client.py
  5. 13
      discord/errors.py
  6. 4
      discord/gateway.py
  7. 85
      discord/guild.py
  8. 6
      discord/http.py
  9. 9
      discord/integrations.py
  10. 43
      discord/message.py
  11. 4
      discord/opus.py
  12. 3
      discord/partial_emoji.py
  13. 6
      discord/reaction.py
  14. 11
      discord/role.py
  15. 6
      discord/shard.py
  16. 5
      discord/stage_instance.py
  17. 6
      discord/template.py
  18. 6
      discord/user.py
  19. 4
      discord/utils.py
  20. 81
      discord/webhook/async_.py
  21. 51
      discord/webhook/sync.py
  22. 3
      docs/api.rst

59
discord/abc.py

@ -47,7 +47,7 @@ from typing import (
from .object import OLDEST_OBJECT, Object
from .context_managers import Typing
from .enums import ChannelType
from .errors import InvalidArgument, ClientException
from .errors import ClientException
from .mentions import AllowedMentions
from .permissions import PermissionOverwrite, Permissions
from .role import Role
@ -277,7 +277,7 @@ class GuildChannel:
reason: Optional[str],
) -> None:
if position < 0:
raise InvalidArgument('Channel position cannot be less than 0.')
raise ValueError('Channel position cannot be less than 0.')
http = self._state.http
bucket = self._sorting_bucket
@ -357,7 +357,7 @@ class GuildChannel:
perms = []
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise InvalidArgument(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
allow, deny = perm.pair()
payload = {
@ -380,7 +380,7 @@ class GuildChannel:
pass
else:
if not isinstance(ch_type, ChannelType):
raise InvalidArgument('type field must be of type ChannelType')
raise TypeError('type field must be of type ChannelType')
options['type'] = ch_type.value
if options:
@ -750,6 +750,11 @@ class GuildChannel:
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
target: Union[:class:`~discord.Member`, :class:`~discord.Role`]
@ -771,9 +776,12 @@ class GuildChannel:
Editing channel specific permissions failed.
~discord.NotFound
The role or member being edited is not part of the guild.
~discord.InvalidArgument
The overwrite parameter invalid or the target type was not
TypeError
The ``overwrite`` parameter was invalid or the target type was not
:class:`~discord.Role` or :class:`~discord.Member`.
ValueError
The ``overwrite`` parameter and ``positions`` parameters were both
unset.
"""
http = self._state.http
@ -783,18 +791,18 @@ class GuildChannel:
elif isinstance(target, Role):
perm_type = _Overwrites.ROLE
else:
raise InvalidArgument('target parameter must be either Member or Role')
raise ValueError('target parameter must be either Member or Role')
if overwrite is _undefined:
if len(permissions) == 0:
raise InvalidArgument('No overwrite provided.')
raise ValueError('No overwrite provided.')
try:
overwrite = PermissionOverwrite(**permissions)
except (ValueError, TypeError):
raise InvalidArgument('Invalid permissions given to keyword arguments.')
raise TypeError('Invalid permissions given to keyword arguments.')
else:
if len(permissions) > 0:
raise InvalidArgument('Cannot mix overwrite and keyword arguments.')
raise TypeError('Cannot mix overwrite and keyword arguments.')
# TODO: wait for event
@ -806,7 +814,7 @@ class GuildChannel:
self.id, target.id, str(allow.value), str(deny.value), perm_type, reason=reason
)
else:
raise InvalidArgument('Invalid overwrite type provided.')
raise TypeError('Invalid overwrite type provided.')
async def _clone_impl(
self: GCH,
@ -925,6 +933,10 @@ class GuildChannel:
.. versionadded:: 1.7
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
------------
beginning: :class:`bool`
@ -959,8 +971,10 @@ class GuildChannel:
Raises
-------
InvalidArgument
An invalid position was given or a bad mix of arguments were passed.
ValueError
An invalid position was given.
TypeError
A bad mix of arguments were passed.
Forbidden
You do not have permissions to move the channel.
HTTPException
@ -974,7 +988,7 @@ class GuildChannel:
before, after = kwargs.get('before'), kwargs.get('after')
offset = kwargs.get('offset', 0)
if sum(bool(a) for a in (beginning, end, before, after)) > 1:
raise InvalidArgument('Only one of [before, after, end, beginning] can be used.')
raise TypeError('Only one of [before, after, end, beginning] can be used.')
bucket = self._sorting_bucket
parent_id = kwargs.get('category', MISSING)
@ -1017,7 +1031,7 @@ class GuildChannel:
index = next((i + 1 for i, c in enumerate(channels) if c.id == after.id), None)
if index is None:
raise InvalidArgument('Could not resolve appropriate move position')
raise ValueError('Could not resolve appropriate move position')
channels.insert(max((index + offset), 0), self)
payload = []
@ -1262,6 +1276,10 @@ class Messageable:
parameter should be used with a :class:`list` of :class:`~discord.Embed` objects.
**Specifying both parameters will lead to an exception**.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
------------
content: Optional[:class:`str`]
@ -1320,9 +1338,10 @@ class Messageable:
Sending the message failed.
~discord.Forbidden
You do not have the proper permissions to send the message.
~discord.InvalidArgument
The ``files`` list is not of the appropriate size,
you specified both ``file`` and ``files``,
ValueError
The ``files`` list is not of the appropriate size.
TypeError
You specified both ``file`` and ``files``,
or you specified both ``embed`` and ``embeds``,
or the ``reference`` object is not a :class:`~discord.Message`,
:class:`~discord.MessageReference` or :class:`~discord.PartialMessage`.
@ -1347,12 +1366,12 @@ class Messageable:
try:
reference = reference.to_message_reference_dict()
except AttributeError:
raise InvalidArgument('reference parameter must be Message, MessageReference, or PartialMessage') from None
raise TypeError('reference parameter must be Message, MessageReference, or PartialMessage') from None
else:
reference = MISSING
if view and not hasattr(view, '__discord_ui_view__'):
raise InvalidArgument(f'view parameter must be View not {view.__class__!r}')
raise TypeError(f'view parameter must be View not {view.__class__!r}')
with handle_message_parameters(
content=content,

39
discord/asset.py

@ -28,7 +28,6 @@ import io
import os
from typing import Any, Literal, Optional, TYPE_CHECKING, Tuple, Union
from .errors import DiscordException
from .errors import InvalidArgument
from . import utils
import yarl
@ -290,6 +289,10 @@ class Asset(AssetMixin):
) -> Asset:
"""Returns a new asset with the passed components replaced.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
-----------
size: :class:`int`
@ -303,7 +306,7 @@ class Asset(AssetMixin):
Raises
-------
InvalidArgument
ValueError
An invalid size or format was passed.
Returns
@ -317,20 +320,20 @@ class Asset(AssetMixin):
if format is not MISSING:
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f'format must be one of {VALID_ASSET_FORMATS}')
raise ValueError(f'format must be one of {VALID_ASSET_FORMATS}')
else:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f'format must be one of {VALID_STATIC_FORMATS}')
raise ValueError(f'format must be one of {VALID_STATIC_FORMATS}')
url = url.with_path(f'{path}.{format}')
if static_format is not MISSING and not self._animated:
if static_format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f'static_format must be one of {VALID_STATIC_FORMATS}')
raise ValueError(f'static_format must be one of {VALID_STATIC_FORMATS}')
url = url.with_path(f'{path}.{static_format}')
if size is not MISSING:
if not utils.valid_icon_size(size):
raise InvalidArgument('size must be a power of 2 between 16 and 4096')
raise ValueError('size must be a power of 2 between 16 and 4096')
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)
@ -341,6 +344,10 @@ class Asset(AssetMixin):
def with_size(self, size: int, /) -> Asset:
"""Returns a new asset with the specified size.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
size: :class:`int`
@ -348,7 +355,7 @@ class Asset(AssetMixin):
Raises
-------
InvalidArgument
ValueError
The asset had an invalid size.
Returns
@ -357,7 +364,7 @@ class Asset(AssetMixin):
The new updated asset.
"""
if not utils.valid_icon_size(size):
raise InvalidArgument('size must be a power of 2 between 16 and 4096')
raise ValueError('size must be a power of 2 between 16 and 4096')
url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)
@ -365,6 +372,10 @@ class Asset(AssetMixin):
def with_format(self, format: ValidAssetFormatTypes, /) -> Asset:
"""Returns a new asset with the specified format.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
format: :class:`str`
@ -372,7 +383,7 @@ class Asset(AssetMixin):
Raises
-------
InvalidArgument
ValueError
The asset had an invalid format.
Returns
@ -383,10 +394,10 @@ class Asset(AssetMixin):
if self._animated:
if format not in VALID_ASSET_FORMATS:
raise InvalidArgument(f'format must be one of {VALID_ASSET_FORMATS}')
raise ValueError(f'format must be one of {VALID_ASSET_FORMATS}')
else:
if format not in VALID_STATIC_FORMATS:
raise InvalidArgument(f'format must be one of {VALID_STATIC_FORMATS}')
raise ValueError(f'format must be one of {VALID_STATIC_FORMATS}')
url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path)
@ -399,6 +410,10 @@ class Asset(AssetMixin):
This only changes the format if the underlying asset is
not animated. Otherwise, the asset is not changed.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
format: :class:`str`
@ -406,7 +421,7 @@ class Asset(AssetMixin):
Raises
-------
InvalidArgument
ValueError
The asset had an invalid format.
Returns

58
discord/channel.py

@ -52,7 +52,7 @@ from .object import Object
from . import utils
from .utils import MISSING
from .asset import Asset
from .errors import ClientException, InvalidArgument
from .errors import ClientException
from .stage_instance import StageInstance
from .threads import Thread
@ -300,6 +300,10 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited channel is returned instead.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
----------
name: :class:`str`
@ -334,9 +338,10 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
Raises
------
InvalidArgument
If position is less than 0 or greater than the number of channels, or if
the permission overwrite information is not in proper form.
ValueError
The new ``position`` is less than 0 or greater than the number of channels.
TypeError
The permission overwrite information is not in proper form.
Forbidden
You do not have permissions to edit the channel.
HTTPException
@ -613,6 +618,10 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
.. versionadded:: 1.3
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
destination: :class:`TextChannel`
@ -628,6 +637,10 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
Following the channel failed.
Forbidden
You do not have the permissions to create a webhook.
ClientException
The channel is not a news channel.
TypeError
The destination channel is not a text channel.
Returns
--------
@ -639,7 +652,7 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
raise ClientException('The channel must be a news channel.')
if not isinstance(destination, TextChannel):
raise InvalidArgument(f'Expected TextChannel received {destination.__class__.__name__}')
raise TypeError(f'Expected TextChannel received {destination.__class__.__name__}')
from .webhook import Webhook
@ -1065,6 +1078,10 @@ class VoiceChannel(VocalGuildChannel):
.. versionchanged:: 2.0
The ``region`` parameter now accepts :class:`str` instead of an enum.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
----------
name: :class:`str`
@ -1098,7 +1115,7 @@ class VoiceChannel(VocalGuildChannel):
Raises
------
InvalidArgument
TypeError
If the permission overwrite information is not in proper form.
Forbidden
You do not have permissions to edit the channel.
@ -1264,7 +1281,7 @@ class StageChannel(VocalGuildChannel):
Raises
------
InvalidArgument
TypeError
If the ``privacy_level`` parameter is not the proper type.
Forbidden
You do not have permissions to create a stage instance.
@ -1281,7 +1298,7 @@ class StageChannel(VocalGuildChannel):
if privacy_level is not MISSING:
if not isinstance(privacy_level, StagePrivacyLevel):
raise InvalidArgument('privacy_level field must be of type PrivacyLevel')
raise TypeError('privacy_level field must be of type PrivacyLevel')
payload['privacy_level'] = privacy_level.value
@ -1346,6 +1363,10 @@ class StageChannel(VocalGuildChannel):
.. versionchanged:: 2.0
The ``region`` parameter now accepts :class:`str` instead of an enum.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
----------
name: :class:`str`
@ -1373,7 +1394,7 @@ class StageChannel(VocalGuildChannel):
Raises
------
InvalidArgument
ValueError
If the permission overwrite information is not in proper form.
Forbidden
You do not have permissions to edit the channel.
@ -1500,6 +1521,10 @@ class CategoryChannel(discord.abc.GuildChannel, Hashable):
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited channel is returned instead.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
----------
name: :class:`str`
@ -1516,8 +1541,10 @@ class CategoryChannel(discord.abc.GuildChannel, Hashable):
Raises
------
InvalidArgument
ValueError
If position is less than 0 or greater than the number of categories.
TypeError
The overwrite information is not in proper form.
Forbidden
You do not have permissions to edit the category.
HTTPException
@ -1741,6 +1768,10 @@ class StoreChannel(discord.abc.GuildChannel, Hashable):
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited channel is returned instead.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
----------
name: :class:`str`
@ -1765,9 +1796,10 @@ class StoreChannel(discord.abc.GuildChannel, Hashable):
Raises
------
InvalidArgument
If position is less than 0 or greater than the number of channels, or if
the permission overwrite information is not in proper form.
ValueError
The new ``position`` is less than 0 or greater than the number of channels.
TypeError
The permission overwrite information is not in proper form.
Forbidden
You do not have permissions to edit the channel.
HTTPException

16
discord/client.py

@ -1124,6 +1124,10 @@ class Client:
.. versionchanged:: 2.0
Removed the ``afk`` keyword-only parameter.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
----------
activity: Optional[:class:`.BaseActivity`]
@ -1134,7 +1138,7 @@ class Client:
Raises
------
InvalidArgument
TypeError
If the ``activity`` parameter is not the proper type.
"""
@ -1355,10 +1359,16 @@ class Client:
Bot accounts in more than 10 guilds are not allowed to create guilds.
.. versionchanged:: 2.0
``name`` and ``icon`` parameters are now keyword-only.
The `region`` parameter has been removed.
.. versionchanged:: 2.0
``name`` and ``region``, and ``icon`` parameters are now keyword-only.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
----------
name: :class:`str`
@ -1375,7 +1385,7 @@ class Client:
------
HTTPException
Guild creation failed.
InvalidArgument
ValueError
Invalid icon image format given. Must be PNG or JPG.
Returns

13
discord/errors.py

@ -47,7 +47,6 @@ __all__ = (
'NotFound',
'DiscordServerError',
'InvalidData',
'InvalidArgument',
'LoginFailure',
'ConnectionClosed',
'PrivilegedIntentsRequired',
@ -186,18 +185,6 @@ class InvalidData(ClientException):
pass
class InvalidArgument(ClientException):
"""Exception that's raised when an argument to a function
is invalid some way (e.g. wrong value or wrong type).
This could be considered the analogous of ``ValueError`` and
``TypeError`` except inherited from :exc:`ClientException` and thus
:exc:`DiscordException`.
"""
pass
class LoginFailure(ClientException):
"""Exception that's raised when the :meth:`Client.login` function
fails to log you in from improper credentials or some other misc.

4
discord/gateway.py

@ -41,7 +41,7 @@ import aiohttp
from . import utils
from .activity import BaseActivity
from .enums import SpeakingState
from .errors import ConnectionClosed, InvalidArgument
from .errors import ConnectionClosed
_log = logging.getLogger(__name__)
@ -681,7 +681,7 @@ class DiscordWebSocket:
) -> None:
if activity is not None:
if not isinstance(activity, BaseActivity):
raise InvalidArgument('activity must derive from BaseActivity.')
raise TypeError('activity must derive from BaseActivity.')
activities = [activity.to_dict()]
else:
activities = []

85
discord/guild.py

@ -52,7 +52,7 @@ from .emoji import Emoji
from .errors import InvalidData
from .permissions import PermissionOverwrite
from .colour import Colour
from .errors import InvalidArgument, ClientException
from .errors import ClientException
from .channel import *
from .channel import _guild_channel_factory
from .channel import _threaded_guild_channel_factory
@ -1086,12 +1086,12 @@ class Guild(Hashable):
if overwrites is MISSING:
overwrites = {}
elif not isinstance(overwrites, dict):
raise InvalidArgument('overwrites parameter expects a dict.')
raise TypeError('overwrites parameter expects a dict.')
perms = []
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise InvalidArgument(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')
allow, deny = perm.pair()
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
@ -1138,6 +1138,10 @@ class Guild(Hashable):
other channels to follow suit. A follow-up call to :meth:`~TextChannel.edit`
will be required to update the position of the channel in the channel list.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Examples
----------
@ -1189,7 +1193,7 @@ class Guild(Hashable):
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
TypeError
The permission overwrite information is not in proper form.
Returns
@ -1237,6 +1241,10 @@ class Guild(Hashable):
This is similar to :meth:`create_text_channel` except makes a :class:`VoiceChannel` instead.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
name: :class:`str`
@ -1274,7 +1282,7 @@ class Guild(Hashable):
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
TypeError
The permission overwrite information is not in proper form.
Returns
@ -1323,6 +1331,10 @@ class Guild(Hashable):
.. versionadded:: 1.7
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
name: :class:`str`
@ -1349,7 +1361,7 @@ class Guild(Hashable):
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
TypeError
The permission overwrite information is not in proper form.
Returns
@ -1390,13 +1402,17 @@ class Guild(Hashable):
The ``category`` parameter is not supported in this function since categories
cannot have categories.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
InvalidArgument
TypeError
The permission overwrite information is not in proper form.
Returns
@ -1495,6 +1511,10 @@ class Guild(Hashable):
.. versionchanged:: 2.0
The ``region`` keyword parameter has been removed.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
----------
name: :class:`str`
@ -1562,10 +1582,14 @@ class Guild(Hashable):
You do not have permissions to edit the guild.
HTTPException
Editing the guild failed.
InvalidArgument
ValueError
The image format passed in to ``icon`` is invalid. It must be
PNG or JPG. This is also raised if you are not the owner of the
guild and request an ownership transfer.
TypeError
The type passed to the ``default_notifications``, ``verification_level``,
``explicit_content_filter``, or ``system_channel_flags`` parameter was
of the incorrect type.
Returns
--------
@ -1618,7 +1642,7 @@ class Guild(Hashable):
if default_notifications is not MISSING:
if not isinstance(default_notifications, NotificationLevel):
raise InvalidArgument('default_notifications field must be of type NotificationLevel')
raise TypeError('default_notifications field must be of type NotificationLevel')
fields['default_message_notifications'] = default_notifications.value
if afk_channel is not MISSING:
@ -1647,25 +1671,25 @@ class Guild(Hashable):
if owner is not MISSING:
if self.owner_id != self._state.self_id:
raise InvalidArgument('To transfer ownership you must be the owner of the guild.')
raise ValueError('To transfer ownership you must be the owner of the guild.')
fields['owner_id'] = owner.id
if verification_level is not MISSING:
if not isinstance(verification_level, VerificationLevel):
raise InvalidArgument('verification_level field must be of type VerificationLevel')
raise TypeError('verification_level field must be of type VerificationLevel')
fields['verification_level'] = verification_level.value
if explicit_content_filter is not MISSING:
if not isinstance(explicit_content_filter, ContentFilter):
raise InvalidArgument('explicit_content_filter field must be of type ContentFilter')
raise TypeError('explicit_content_filter field must be of type ContentFilter')
fields['explicit_content_filter'] = explicit_content_filter.value
if system_channel_flags is not MISSING:
if not isinstance(system_channel_flags, SystemChannelFlags):
raise InvalidArgument('system_channel_flags field must be of type SystemChannelFlags')
raise TypeError('system_channel_flags field must be of type SystemChannelFlags')
fields['system_channel_flags'] = system_channel_flags.value
@ -1675,7 +1699,7 @@ class Guild(Hashable):
if 'rules_channel_id' in fields and 'public_updates_channel_id' in fields:
features.append('COMMUNITY')
else:
raise InvalidArgument(
raise ValueError(
'community field requires both rules_channel and public_updates_channel fields to be provided'
)
@ -1982,6 +2006,10 @@ class Guild(Hashable):
.. versionchanged:: 1.4
The ``roles`` keyword-only parameter was added.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
days: :class:`int`
@ -2003,7 +2031,7 @@ class Guild(Hashable):
You do not have permissions to prune members.
HTTPException
An error occurred while pruning members.
InvalidArgument
TypeError
An integer was not passed for ``days``.
Returns
@ -2014,7 +2042,7 @@ class Guild(Hashable):
"""
if not isinstance(days, int):
raise InvalidArgument(f'Expected int for ``days``, received {days.__class__.__name__} instead.')
raise TypeError(f'Expected int for ``days``, received {days.__class__.__name__} instead.')
if roles:
role_ids = [str(role.id) for role in roles]
@ -2083,6 +2111,10 @@ class Guild(Hashable):
.. versionchanged:: 2.0
The returned value can be ``None``.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
days: :class:`int`
@ -2099,7 +2131,7 @@ class Guild(Hashable):
You do not have permissions to prune members.
HTTPException
An error occurred while fetching the prune members estimate.
InvalidArgument
TypeError
An integer was not passed for ``days``.
Returns
@ -2109,7 +2141,7 @@ class Guild(Hashable):
"""
if not isinstance(days, int):
raise InvalidArgument(f'Expected int for ``days``, received {days.__class__.__name__} instead.')
raise TypeError(f'Expected int for ``days``, received {days.__class__.__name__} instead.')
if roles:
role_ids = [str(role.id) for role in roles]
@ -2594,6 +2626,10 @@ class Guild(Hashable):
.. versionadded:: 2.0
The ``display_icon`` keyword-only parameter was added.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
name: :class:`str`
@ -2623,7 +2659,7 @@ class Guild(Hashable):
You do not have permissions to create the role.
HTTPException
Creating the role failed.
InvalidArgument
TypeError
An invalid keyword argument was given.
Returns
@ -2674,7 +2710,12 @@ class Guild(Hashable):
.. versionadded:: 1.4
Example:
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Example
----------
.. code-block:: python3
@ -2700,7 +2741,7 @@ class Guild(Hashable):
You do not have permissions to move the roles.
HTTPException
Moving the roles failed.
InvalidArgument
TypeError
An invalid keyword argument was given.
Returns
@ -2709,7 +2750,7 @@ class Guild(Hashable):
A list of all the roles in the guild.
"""
if not isinstance(positions, dict):
raise InvalidArgument('positions parameter expects a dict.')
raise TypeError('positions parameter expects a dict.')
role_positions = []
for role, position in positions.items():

6
discord/http.py

@ -50,7 +50,7 @@ import weakref
import aiohttp
from .errors import HTTPException, Forbidden, NotFound, LoginFailure, DiscordServerError, GatewayNotFound, InvalidArgument
from .errors import HTTPException, Forbidden, NotFound, LoginFailure, DiscordServerError, GatewayNotFound
from .gateway import DiscordClientWebSocketResponse
from .file import File
from . import __version__, utils
@ -169,7 +169,7 @@ def handle_message_parameters(
payload = {}
if embeds is not MISSING:
if len(embeds) > 10:
raise InvalidArgument('embeds has a maximum of 10 elements.')
raise ValueError('embeds has a maximum of 10 elements.')
payload['embeds'] = [e.to_dict() for e in embeds]
if embed is not MISSING:
@ -1233,7 +1233,7 @@ class HTTPClient:
try:
mime_type = utils._get_mime_type_for_image(initial_bytes)
except InvalidArgument:
except ValueError:
if initial_bytes.startswith(b'{'):
mime_type = 'application/json'
else:

9
discord/integrations.py

@ -28,7 +28,6 @@ import datetime
from typing import Any, Dict, Optional, TYPE_CHECKING, overload, Type, Tuple
from .utils import _get_as_snowflake, parse_time, MISSING
from .user import User
from .errors import InvalidArgument
from .enums import try_enum, ExpireBehaviour
__all__ = (
@ -232,6 +231,10 @@ class StreamIntegration(Integration):
You must have the :attr:`~Permissions.manage_guild` permission to
do this.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
expire_behaviour: :class:`ExpireBehaviour`
@ -247,13 +250,13 @@ class StreamIntegration(Integration):
You do not have permission to edit the integration.
HTTPException
Editing the guild failed.
InvalidArgument
TypeError
``expire_behaviour`` did not receive a :class:`ExpireBehaviour`.
"""
payload: Dict[str, Any] = {}
if expire_behaviour is not MISSING:
if not isinstance(expire_behaviour, ExpireBehaviour):
raise InvalidArgument('expire_behaviour field must be of type ExpireBehaviour')
raise TypeError('expire_behaviour field must be of type ExpireBehaviour')
payload['expire_behavior'] = expire_behaviour.value

43
discord/message.py

@ -50,7 +50,7 @@ from .reaction import Reaction
from .emoji import Emoji
from .partial_emoji import PartialEmoji
from .enums import MessageType, ChannelType, try_enum
from .errors import InvalidArgument, HTTPException
from .errors import HTTPException
from .components import _component_factory
from .embeds import Embed
from .member import Member
@ -118,7 +118,7 @@ def convert_emoji_reaction(emoji):
# No existing emojis have <> in them, so this should be okay.
return emoji.strip('<>')
raise InvalidArgument(f'emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}.')
raise TypeError(f'emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}.')
class Attachment(Hashable):
@ -1223,6 +1223,10 @@ class Message(Hashable):
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited role is returned instead.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
content: Optional[:class:`str`]
@ -1274,7 +1278,7 @@ class Message(Hashable):
Forbidden
Tried to suppress a message without permissions or
edited a message's content or embed that isn't yours.
~discord.InvalidArgument
TypeError
You specified both ``embed`` and ``embeds``
Returns
@ -1457,6 +1461,10 @@ class Message(Hashable):
``emoji`` parameter is now positional-only.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
@ -1470,7 +1478,7 @@ class Message(Hashable):
You do not have the proper permissions to react to the message.
NotFound
The emoji you specified was not found.
InvalidArgument
TypeError
The emoji parameter is invalid.
"""
@ -1490,6 +1498,10 @@ class Message(Hashable):
The ``member`` parameter must represent a member and meet
the :class:`abc.Snowflake` abc.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
------------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
@ -1505,7 +1517,7 @@ class Message(Hashable):
You do not have the proper permissions to remove the reaction.
NotFound
The member or emoji you specified was not found.
InvalidArgument
TypeError
The emoji parameter is invalid.
"""
@ -1527,6 +1539,10 @@ class Message(Hashable):
.. versionadded:: 1.3
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
-----------
emoji: Union[:class:`Emoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`]
@ -1540,7 +1556,7 @@ class Message(Hashable):
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
TypeError
The emoji parameter is invalid.
"""
@ -1589,7 +1605,7 @@ class Message(Hashable):
You do not have permissions to create a thread.
HTTPException
Creating the thread failed.
InvalidArgument
ValueError
This message does not have guild info attached.
Returns
@ -1598,7 +1614,7 @@ class Message(Hashable):
The created thread.
"""
if self.guild is None:
raise InvalidArgument('This message does not have guild info attached.')
raise ValueError('This message does not have guild info attached.')
default_auto_archive_duration: ThreadArchiveDuration = getattr(self.channel, 'default_auto_archive_duration', 1440)
data = await self._state.http.start_thread_with_message(
@ -1617,15 +1633,20 @@ class Message(Hashable):
.. versionadded:: 1.6
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Raises
--------
~discord.HTTPException
Sending the message failed.
~discord.Forbidden
You do not have the proper permissions to send the message.
~discord.InvalidArgument
The ``files`` list is not of the appropriate size or
you specified both ``file`` and ``files``.
ValueError
The ``files`` list is not of the appropriate size
TypeError
You specified both ``file`` and ``files``.
Returns
---------

4
discord/opus.py

@ -35,7 +35,7 @@ import os.path
import struct
import sys
from .errors import DiscordException, InvalidArgument
from .errors import DiscordException
if TYPE_CHECKING:
T = TypeVar('T')
@ -447,7 +447,7 @@ class Decoder(_OpusStruct):
def decode(self, data: Optional[bytes], *, fec: bool = False) -> bytes:
if data is None and fec:
raise InvalidArgument("Invalid arguments: FEC cannot be used with null data")
raise TypeError("Invalid arguments: FEC cannot be used with null data")
if data is None:
frame_size = self._get_last_packet_duration() or self.SAMPLES_PER_FRAME

3
discord/partial_emoji.py

@ -28,7 +28,6 @@ from typing import Any, Dict, Optional, TYPE_CHECKING, Type, TypeVar, Union
import re
from .asset import Asset, AssetMixin
from .errors import InvalidArgument
from . import utils
# fmt: off
@ -230,6 +229,6 @@ class PartialEmoji(_EmojiTag, AssetMixin):
async def read(self) -> bytes:
if self.is_unicode_emoji():
raise InvalidArgument('PartialEmoji is not a custom emoji')
raise ValueError('PartialEmoji is not a custom emoji')
return await super().read()

6
discord/reaction.py

@ -148,6 +148,10 @@ class Reaction:
.. versionadded:: 1.3
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Raises
--------
HTTPException
@ -156,7 +160,7 @@ class Reaction:
You do not have the proper permissions to clear the reaction.
NotFound
The emoji you specified was not found.
InvalidArgument
TypeError
The emoji parameter is invalid.
"""
await self.message.clear_reaction(self.emoji)

11
discord/role.py

@ -27,7 +27,6 @@ from typing import Any, Dict, List, Optional, TypeVar, Union, overload, TYPE_CHE
from .asset import Asset
from .permissions import Permissions
from .errors import InvalidArgument
from .colour import Colour
from .mixins import Hashable
from .utils import snowflake_time, _bytes_to_base64_data, _get_as_snowflake, MISSING
@ -360,10 +359,10 @@ class Role(Hashable):
async def _move(self, position: int, reason: Optional[str]) -> None:
if position <= 0:
raise InvalidArgument("Cannot move role to position 0 or below")
raise ValueError("Cannot move role to position 0 or below")
if self.is_default():
raise InvalidArgument("Cannot move default role")
raise ValueError("Cannot move default role")
if self.position == position:
return # Save discord the extra request.
@ -412,6 +411,10 @@ class Role(Hashable):
.. versionadded:: 2.0
The ``display_icon`` keyword-only parameter was added.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
-----------
name: :class:`str`
@ -442,7 +445,7 @@ class Role(Hashable):
You do not have permissions to change the role.
HTTPException
Editing the role failed.
InvalidArgument
ValueError
An invalid position was given or the default
role was asked to be moved.

6
discord/shard.py

@ -495,6 +495,10 @@ class AutoShardedClient(Client):
.. versionchanged:: 2.0
Removed the ``afk`` keyword-only parameter.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`TypeError`.
Parameters
----------
activity: Optional[:class:`BaseActivity`]
@ -509,7 +513,7 @@ class AutoShardedClient(Client):
Raises
------
InvalidArgument
TypeError
If the ``activity`` parameter is not of proper type.
"""

5
discord/stage_instance.py

@ -28,7 +28,6 @@ from typing import Optional, TYPE_CHECKING
from .utils import MISSING, cached_slot_property
from .mixins import Hashable
from .errors import InvalidArgument
from .enums import StagePrivacyLevel, try_enum
# fmt: off
@ -139,7 +138,7 @@ class StageInstance(Hashable):
Raises
------
InvalidArgument
TypeError
If the ``privacy_level`` parameter is not the proper type.
Forbidden
You do not have permissions to edit the stage instance.
@ -154,7 +153,7 @@ class StageInstance(Hashable):
if privacy_level is not MISSING:
if not isinstance(privacy_level, StagePrivacyLevel):
raise InvalidArgument('privacy_level field must be of type PrivacyLevel')
raise TypeError('privacy_level field must be of type PrivacyLevel')
payload['privacy_level'] = privacy_level.value

6
discord/template.py

@ -177,6 +177,10 @@ class Template:
.. versionchanged:: 2.0
The ``region`` parameter has been removed.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
----------
name: :class:`str`
@ -189,7 +193,7 @@ class Template:
------
HTTPException
Guild creation failed.
InvalidArgument
ValueError
Invalid icon image format given. Must be PNG or JPG.
Returns

6
discord/user.py

@ -366,6 +366,10 @@ class ClientUser(BaseUser):
.. versionchanged:: 2.0
The edit is no longer in-place, instead the newly edited client user is returned.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
-----------
username: :class:`str`
@ -378,7 +382,7 @@ class ClientUser(BaseUser):
------
HTTPException
Editing your profile failed.
InvalidArgument
ValueError
Wrong image format passed for ``avatar``.
Returns

4
discord/utils.py

@ -63,8 +63,6 @@ import sys
import types
import warnings
from .errors import InvalidArgument
try:
import orjson
except ModuleNotFoundError:
@ -562,7 +560,7 @@ def _get_mime_type_for_image(data: bytes):
elif data.startswith(b'RIFF') and data[8:12] == b'WEBP':
return 'image/webp'
else:
raise InvalidArgument('Unsupported image type given')
raise ValueError('Unsupported image type given')
def _bytes_to_base64_data(data: bytes) -> str:

81
discord/webhook/async_.py

@ -37,7 +37,7 @@ import weakref
import aiohttp
from .. import utils
from ..errors import InvalidArgument, HTTPException, Forbidden, NotFound, DiscordServerError
from ..errors import HTTPException, Forbidden, NotFound, DiscordServerError
from ..message import Message
from ..enums import try_enum, WebhookType
from ..user import BaseUser, User
@ -456,7 +456,7 @@ def interaction_message_response_params(
if embeds is not MISSING:
if len(embeds) > 10:
raise InvalidArgument('embeds has a maximum of 10 elements.')
raise ValueError('embeds has a maximum of 10 elements.')
data['embeds'] = [e.to_dict() for e in embeds]
if embed is not MISSING:
@ -669,6 +669,10 @@ class WebhookMessage(Message):
.. versionchanged:: 2.0
The edit is no longer in-place, instead the newly edited message is returned.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
content: Optional[:class:`str`]
@ -705,9 +709,8 @@ class WebhookMessage(Message):
TypeError
You specified both ``embed`` and ``embeds``
ValueError
The length of ``embeds`` was invalid
InvalidArgument
There was no token associated with this webhook.
The length of ``embeds`` was invalid or
there was no token associated with this webhook.
Returns
--------
@ -1059,6 +1062,10 @@ class Webhook(BaseWebhook):
def from_url(cls, url: str, *, session: aiohttp.ClientSession, bot_token: Optional[str] = None) -> Webhook:
"""Creates a partial :class:`Webhook` from a webhook URL.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
url: :class:`str`
@ -1077,7 +1084,7 @@ class Webhook(BaseWebhook):
Raises
-------
InvalidArgument
ValueError
The URL is invalid.
Returns
@ -1088,7 +1095,7 @@ class Webhook(BaseWebhook):
"""
m = re.search(r'discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,20})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url)
if m is None:
raise InvalidArgument('Invalid webhook URL given.')
raise ValueError('Invalid webhook URL given.')
data: Dict[str, Any] = m.groupdict()
data['type'] = 1
@ -1142,7 +1149,7 @@ class Webhook(BaseWebhook):
Could not fetch the webhook
NotFound
Could not find the webhook by this ID
InvalidArgument
ValueError
This webhook does not have a token associated with it.
Returns
@ -1157,7 +1164,7 @@ class Webhook(BaseWebhook):
elif self.token:
data = await adapter.fetch_webhook_with_token(self.id, self.token, session=self.session)
else:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
return Webhook(data, self.session, token=self.auth_token, state=self._state)
@ -1186,11 +1193,11 @@ class Webhook(BaseWebhook):
This webhook does not exist.
Forbidden
You do not have permissions to delete this webhook.
InvalidArgument
ValueError
This webhook does not have a token associated with it.
"""
if self.token is None and self.auth_token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter = async_context.get()
@ -1212,6 +1219,10 @@ class Webhook(BaseWebhook):
Edits this Webhook.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
name: Optional[:class:`str`]
@ -1238,12 +1249,12 @@ class Webhook(BaseWebhook):
Editing the webhook failed.
NotFound
This webhook does not exist.
InvalidArgument
ValueError
This webhook does not have a token associated with it
or it tried editing a channel without authentication.
"""
if self.token is None and self.auth_token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
payload = {}
if name is not MISSING:
@ -1258,7 +1269,7 @@ class Webhook(BaseWebhook):
# If a channel is given, always use the authenticated endpoint
if channel is not None:
if self.auth_token is None:
raise InvalidArgument('Editing channel requires authenticated webhook')
raise ValueError('Editing channel requires authenticated webhook')
payload['channel_id'] = channel.id
data = await adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason)
@ -1352,6 +1363,10 @@ class Webhook(BaseWebhook):
it must be a rich embed type. You cannot mix the ``embed`` parameter with the
``embeds`` parameter, which must be a :class:`list` of :class:`Embed` objects to send.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
content: :class:`str`
@ -1415,10 +1430,9 @@ class Webhook(BaseWebhook):
TypeError
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``.
ValueError
The length of ``embeds`` was invalid.
InvalidArgument
There was no token associated with this webhook or ``ephemeral``
was passed with the improper webhook type or there was no state
The length of ``embeds`` was invalid, there was no token
associated with this webhook or ``ephemeral`` was passed
with the improper webhook type or there was no state
attached with this webhook when giving it a view.
Returns
@ -1428,7 +1442,7 @@ class Webhook(BaseWebhook):
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None)
if content is None:
@ -1440,14 +1454,14 @@ class Webhook(BaseWebhook):
application_webhook = self.type is WebhookType.application
if ephemeral and not application_webhook:
raise InvalidArgument('ephemeral messages can only be sent from application webhooks')
raise ValueError('ephemeral messages can only be sent from application webhooks')
if application_webhook:
wait = True
if view is not MISSING:
if isinstance(self._state, _WebhookState):
raise InvalidArgument('Webhook views require an associated state with the webhook')
raise ValueError('Webhook views require an associated state with the webhook')
if ephemeral is True and view.timeout is None:
view.timeout = 15 * 60.0
@ -1511,7 +1525,7 @@ class Webhook(BaseWebhook):
You do not have the permissions required to get a message.
~discord.HTTPException
Retrieving the message failed.
InvalidArgument
ValueError
There was no token associated with this webhook.
Returns
@ -1521,7 +1535,7 @@ class Webhook(BaseWebhook):
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter = async_context.get()
data = await adapter.get_webhook_message(
@ -1555,6 +1569,10 @@ class Webhook(BaseWebhook):
.. versionchanged:: 2.0
The edit is no longer in-place, instead the newly edited message is returned.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
message_id: :class:`int`
@ -1590,9 +1608,8 @@ class Webhook(BaseWebhook):
TypeError
You specified both ``embed`` and ``embeds``
ValueError
The length of ``embeds`` was invalid
InvalidArgument
There was no token associated with this webhook or the webhook had
The length of ``embeds`` was invalid,
there was no token associated with this webhook or the webhook had
no state.
Returns
@ -1602,11 +1619,11 @@ class Webhook(BaseWebhook):
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
if view is not MISSING:
if isinstance(self._state, _WebhookState):
raise InvalidArgument('This webhook does not have state associated with it')
raise ValueError('This webhook does not have state associated with it')
self._state.prevent_view_updates_for(message_id)
@ -1650,6 +1667,10 @@ class Webhook(BaseWebhook):
``message_id`` parameter is now positional-only.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError`.
Parameters
------------
message_id: :class:`int`
@ -1661,9 +1682,11 @@ class Webhook(BaseWebhook):
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
ValueError
This webhook does not have a token associated with it.
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter = async_context.get()
await adapter.delete_webhook_message(

51
discord/webhook/sync.py

@ -41,7 +41,7 @@ from typing import Any, Dict, List, Literal, Optional, TYPE_CHECKING, Tuple, Typ
import weakref
from .. import utils
from ..errors import InvalidArgument, HTTPException, Forbidden, NotFound, DiscordServerError
from ..errors import HTTPException, Forbidden, NotFound, DiscordServerError
from ..message import Message
from ..http import Route, handle_message_parameters
from ..channel import PartialMessageable
@ -387,6 +387,10 @@ class SyncWebhookMessage(Message):
) -> SyncWebhookMessage:
"""Edits the message.
.. versionchanged:: 2.0
This function no-longer raises ``InvalidArgument`` instead raising
:exc:`ValueError` or :exc:`TypeError` in various cases.
Parameters
------------
content: Optional[:class:`str`]
@ -418,9 +422,8 @@ class SyncWebhookMessage(Message):
TypeError
You specified both ``embed`` and ``embeds``
ValueError
The length of ``embeds`` was invalid
InvalidArgument
There was no token associated with this webhook.
The length of ``embeds`` was invalid or
there was no token associated with this webhook.
Returns
--------
@ -636,7 +639,7 @@ class SyncWebhook(BaseWebhook):
Raises
-------
InvalidArgument
ValueError
The URL is invalid.
Returns
@ -647,7 +650,7 @@ class SyncWebhook(BaseWebhook):
"""
m = re.search(r'discord(?:app)?.com/api/webhooks/(?P<id>[0-9]{17,20})/(?P<token>[A-Za-z0-9\.\-\_]{60,68})', url)
if m is None:
raise InvalidArgument('Invalid webhook URL given.')
raise ValueError('Invalid webhook URL given.')
data: Dict[str, Any] = m.groupdict()
data['type'] = 1
@ -683,7 +686,7 @@ class SyncWebhook(BaseWebhook):
Could not fetch the webhook
NotFound
Could not find the webhook by this ID
InvalidArgument
ValueError
This webhook does not have a token associated with it.
Returns
@ -698,7 +701,7 @@ class SyncWebhook(BaseWebhook):
elif self.token:
data = adapter.fetch_webhook_with_token(self.id, self.token, session=self.session)
else:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
return SyncWebhook(data, self.session, token=self.auth_token, state=self._state)
@ -723,11 +726,11 @@ class SyncWebhook(BaseWebhook):
This webhook does not exist.
Forbidden
You do not have permissions to delete this webhook.
InvalidArgument
ValueError
This webhook does not have a token associated with it.
"""
if self.token is None and self.auth_token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter: WebhookAdapter = _get_webhook_adapter()
@ -769,7 +772,7 @@ class SyncWebhook(BaseWebhook):
Editing the webhook failed.
NotFound
This webhook does not exist.
InvalidArgument
ValueError
This webhook does not have a token associated with it
or it tried editing a channel without authentication.
@ -779,7 +782,7 @@ class SyncWebhook(BaseWebhook):
The newly edited webhook.
"""
if self.token is None and self.auth_token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
payload = {}
if name is not MISSING:
@ -794,7 +797,7 @@ class SyncWebhook(BaseWebhook):
# If a channel is given, always use the authenticated endpoint
if channel is not None:
if self.auth_token is None:
raise InvalidArgument('Editing channel requires authenticated webhook')
raise ValueError('Editing channel requires authenticated webhook')
payload['channel_id'] = channel.id
data = adapter.edit_webhook(self.id, self.auth_token, payload=payload, session=self.session, reason=reason)
@ -924,9 +927,8 @@ class SyncWebhook(BaseWebhook):
TypeError
You specified both ``embed`` and ``embeds`` or ``file`` and ``files``
ValueError
The length of ``embeds`` was invalid
InvalidArgument
There was no token associated with this webhook.
The length of ``embeds`` was invalid or
there was no token associated with this webhook.
Returns
---------
@ -935,7 +937,7 @@ class SyncWebhook(BaseWebhook):
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None)
if content is None:
@ -989,7 +991,7 @@ class SyncWebhook(BaseWebhook):
You do not have the permissions required to get a message.
~discord.HTTPException
Retrieving the message failed.
InvalidArgument
ValueError
There was no token associated with this webhook.
Returns
@ -999,7 +1001,7 @@ class SyncWebhook(BaseWebhook):
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter: WebhookAdapter = _get_webhook_adapter()
data = adapter.get_webhook_message(
@ -1056,13 +1058,12 @@ class SyncWebhook(BaseWebhook):
TypeError
You specified both ``embed`` and ``embeds``
ValueError
The length of ``embeds`` was invalid
InvalidArgument
There was no token associated with this webhook.
The length of ``embeds`` was invalid or
there was no token associated with this webhook.
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None)
params = handle_message_parameters(
@ -1104,9 +1105,11 @@ class SyncWebhook(BaseWebhook):
Deleting the message failed.
Forbidden
Deleted a message that is not yours.
ValueError
This webhook does not have a token associated with it.
"""
if self.token is None:
raise InvalidArgument('This webhook does not have a token associated with it')
raise ValueError('This webhook does not have a token associated with it')
adapter: WebhookAdapter = _get_webhook_adapter()
adapter.delete_webhook_message(

3
docs/api.rst

@ -4230,8 +4230,6 @@ The following exceptions are thrown by the library.
.. autoexception:: InvalidData
.. autoexception:: InvalidArgument
.. autoexception:: GatewayNotFound
.. autoexception:: ConnectionClosed
@ -4253,7 +4251,6 @@ Exception Hierarchy
- :exc:`DiscordException`
- :exc:`ClientException`
- :exc:`InvalidData`
- :exc:`InvalidArgument`
- :exc:`LoginFailure`
- :exc:`ConnectionClosed`
- :exc:`PrivilegedIntentsRequired`

Loading…
Cancel
Save