Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Large code/documentation cleanup #1476

Merged
merged 24 commits into from
Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
8ac724c
Can't even begin to summarize this
baronkobama Jul 8, 2022
5b7fdd9
Can't even begin to summarize this
baronkobama Jul 8, 2022
93e0c56
Merge branch 'code-cleanup' of https://github.com/baronkobama/pycord …
baronkobama Jul 8, 2022
41b959b
Update overwrites description
baronkobama Jul 8, 2022
c0e48de
Add Optional typehint
baronkobama Jul 8, 2022
5fc07bf
Fix indents, slicing, callable brackets
baronkobama Jul 8, 2022
01ac80f
Update discord/abc.py
Lulalaby Jul 10, 2022
aaf9e89
chore: implement suggestions
baronkobama Jul 10, 2022
a7bb9f2
chore: missed one
baronkobama Jul 10, 2022
0d66ae2
Merge branch 'master' into code-cleanup
baronkobama Jul 10, 2022
f485a0f
fix: missing TextChannel docs
baronkobama Jul 10, 2022
3f5ba96
Merge branch 'code-cleanup' of https://github.com/baronkobama/pycord …
baronkobama Jul 10, 2022
3975858
fix: missing ForumChannel docs
baronkobama Jul 10, 2022
a4a3675
fix: failing docs check
baronkobama Jul 10, 2022
7ca6ca6
Update discord/guild.py
baronkobama Jul 11, 2022
1723621
docs: remove unused guild features
baronkobama Jul 11, 2022
81cc65b
docs: undo a removed guild feature
baronkobama Jul 11, 2022
d2ce246
Merge branch 'master' into code-cleanup
Lulalaby Jul 17, 2022
e4be6dc
Update discord/stage_instance.py
Lulalaby Jul 22, 2022
099f797
Update discord/scheduled_events.py
Lulalaby Jul 22, 2022
cf113a0
Update discord/commands/permissions.py
Lulalaby Jul 22, 2022
4a38c22
Merge branch 'master' into code-cleanup
Lulalaby Jul 22, 2022
d8553fb
Update http.py
baronkobama Jul 22, 2022
e7dfdd3
Merge branch 'master' into code-cleanup
Lulalaby Jul 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 22 additions & 26 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,14 +175,6 @@ async def _purge_messages_helper(
return ret


class _Undefined:
def __repr__(self) -> str:
return "see-below"


_undefined: Any = _Undefined()


@runtime_checkable
class Snowflake(Protocol):
"""An ABC that details the common operations on a Discord model.
Expand Down Expand Up @@ -382,7 +374,7 @@ async def _move(
payload = []
for index, c in enumerate(channels):
d: Dict[str, Any] = {"id": c.id, "position": index}
if parent_id is not _undefined and c.id == self.id:
if parent_id is not MISSING and c.id == self.id:
d.update(parent_id=parent_id, lock_permissions=lock_permissions)
payload.append(d)

Expand All @@ -392,7 +384,7 @@ async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optiona
try:
parent = options.pop("category")
except KeyError:
parent_id = _undefined
parent_id = MISSING
else:
parent_id = parent and parent.id

Expand Down Expand Up @@ -420,7 +412,7 @@ async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optiona
try:
position = options.pop("position")
except KeyError:
if parent_id is not _undefined:
if parent_id is not MISSING:
if lock_permissions:
category = self.guild.get_channel(parent_id)
if category:
Expand Down Expand Up @@ -603,7 +595,7 @@ def category(self) -> Optional[CategoryChannel]:

@property
def permissions_synced(self) -> bool:
""":class:`bool`: Whether or not the permissions for this channel are synced with the
""":class:`bool`: Whether the permissions for this channel are synced with the
category it belongs to.

If there is no category then this is ``False``.
Expand Down Expand Up @@ -658,7 +650,7 @@ def permissions_for(self, obj: Union[Member, Role], /) -> Permissions:
# (or otherwise) are then OR'd together.
# After the role permissions are resolved, the member permissions
# have to take into effect.
# After all that is done.. you have to do the following:
# After all that is done... you have to do the following:
Lulalaby marked this conversation as resolved.
Show resolved Hide resolved

# If manage permissions is True, then all permissions are set to True.

Expand Down Expand Up @@ -781,7 +773,7 @@ async def set_permissions(
self,
target: Union[Member, Role],
*,
overwrite: Optional[Union[PermissionOverwrite, _Undefined]] = ...,
overwrite: Optional[PermissionOverwrite] = ...,
reason: Optional[str] = ...,
) -> None:
...
Expand All @@ -796,7 +788,7 @@ async def set_permissions(
) -> None:
...

async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **permissions):
async def set_permissions(self, target, *, overwrite=MISSING, reason=None, **permissions):
r"""|coro|

Sets the channel specific permission overwrites for a target in the
Expand Down Expand Up @@ -874,7 +866,7 @@ async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **
else:
raise InvalidArgument("target parameter must be either Member or Role")

if overwrite is _undefined:
if overwrite is MISSING:
if len(permissions) == 0:
raise InvalidArgument("No overwrite provided.")
try:
Expand Down Expand Up @@ -1046,7 +1038,7 @@ async def move(self, **kwargs) -> None:
Raises
-------
InvalidArgument
An invalid position was given or a bad mix of arguments were passed.
An invalid position was given or a bad mix of arguments was passed.
Forbidden
You do not have permissions to move the channel.
HTTPException
Expand Down Expand Up @@ -1152,20 +1144,22 @@ async def create_invite(
.. versionadded:: 2.0

target_user: Optional[:class:`User`]
The user whose stream to display for this invite, required if `target_type` is `TargetType.stream`. The user must be streaming in the channel.
The user whose stream to display for this invite, required if `target_type` is `TargetType.stream`.
The user must be streaming in the channel.

.. versionadded:: 2.0

target_application_id: Optional[:class:`int`]
The id of the embedded application for the invite, required if `target_type` is `TargetType.embedded_application`.
The id of the embedded application for the invite, required if `target_type` is
`TargetType.embedded_application`.

.. versionadded:: 2.0

target_event: Optional[:class:`ScheduledEvent`]
target_event: Optional[:class:`.ScheduledEvent`]
The scheduled event object to link to the event.
Shortcut to :meth:`Invite.set_scheduled_event`
Shortcut to :meth:`.Invite.set_scheduled_event`

See :meth:`Invite.set_scheduled_event` for more
See :meth:`.Invite.set_scheduled_event` for more
info on event invite linking.

.. versionadded:: 2.0
Expand Down Expand Up @@ -1383,11 +1377,13 @@ async def send(

.. versionadded:: 1.4

reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`, :class:`~discord.PartialMessage`]
reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`,
:class:`~discord.PartialMessage`]
A reference to the :class:`~discord.Message` to which you are replying, this can be created using
:meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control
whether this mentions the author of the referenced message using the :attr:`~discord.AllowedMentions.replied_user`
attribute of ``allowed_mentions`` or by setting ``mention_author``.
whether this mentions the author of the referenced message using the
:attr:`~discord.AllowedMentions.replied_user` attribute of ``allowed_mentions`` or by
setting ``mention_author``.

.. versionadded:: 1.6

Expand Down Expand Up @@ -1732,7 +1728,7 @@ def history(
If a datetime is provided, it is recommended to use a UTC aware datetime.
If the datetime is naive, it is assumed to be local time.
When using this argument, the maximum limit is 101. Note that if the limit is an
even number then this will return at most limit + 1 messages.
even number, then this will return at most limit + 1 messages.
oldest_first: Optional[:class:`bool`]
If set to ``True``, return messages in oldest->newest order. Defaults to ``True`` if
``after`` is specified, otherwise ``False``.
Expand Down
17 changes: 8 additions & 9 deletions discord/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@
from .types.activity import Activity as ActivityPayload
from .types.activity import (
ActivityAssets,
ActivityButton,
ActivityParty,
ActivityTimestamps,
)
Expand Down Expand Up @@ -166,15 +165,15 @@ class Activity(BaseActivity):
The user's current state. For example, "In Game".
details: Optional[:class:`str`]
The detail of the user's current activity.
timestamps: :class:`dict`
timestamps: Dict[:class:`str`, :class:`int`]
A dictionary of timestamps. It contains the following optional keys:

- ``start``: Corresponds to when the user started doing the
activity in milliseconds since Unix epoch.
- ``end``: Corresponds to when the user will finish doing the
activity in milliseconds since Unix epoch.

assets: :class:`dict`
assets: Dict[:class:`str`, :class:`str`]
A dictionary representing the images and their hover text of an activity.
It contains the following optional keys:

Expand All @@ -183,12 +182,12 @@ class Activity(BaseActivity):
- ``small_image``: A string representing the ID for the small image asset.
- ``small_text``: A string representing the text when hovering over the small image asset.

party: :class:`dict`
party: Dict[:class:`str`, Union[:class:`str`, List[:class:`int`]]]
A dictionary representing the activity party. It contains the following optional keys:

- ``id``: A string representing the party ID.
- ``size``: A list of up to two integer elements denoting (current_size, maximum_size).
buttons: Union[List[:class:`dict`], List[:class:`str`]]
buttons: Union[List[Dict[:class:`str`, :class:`str`]], List[:class:`str`]]
A list of dictionaries representing custom buttons shown in a rich presence.
Each dictionary contains the following keys:

Expand All @@ -197,7 +196,7 @@ class Activity(BaseActivity):

.. note::

Bots cannot access a user's activity button URLs. Therefore the type of this attribute
Bots cannot access a user's activity button URLs. Therefore, the type of this attribute
will be List[:class:`str`] when received through the gateway.

.. versionadded:: 2.0
Expand Down Expand Up @@ -475,8 +474,8 @@ class Streaming(BaseActivity):

url: :class:`str`
The stream's URL.
assets: :class:`dict`
A dictionary comprising of similar keys than those in :attr:`Activity.assets`.
assets: Dict[:class:`str`, :class:`str`]
A dictionary comprised of similar keys than those in :attr:`Activity.assets`.
"""

__slots__ = ("platform", "name", "game", "url", "details", "assets")
Expand Down Expand Up @@ -509,7 +508,7 @@ def twitch_name(self):
"""Optional[:class:`str`]: If provided, the twitch name of the user streaming.

This corresponds to the ``large_image`` key of the :attr:`Streaming.assets`
dictionary if it starts with ``twitch:``. Typically set by the Discord client.
dictionary if it starts with ``twitch:``. Typically, set by the Discord client.
baronkobama marked this conversation as resolved.
Show resolved Hide resolved
"""

try:
Expand Down
2 changes: 1 addition & 1 deletion discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ class AuditLogEntry(Hashable):
The reason this action was done.
extra: Any
Extra information that this entry has that might be useful.
For most actions, this is ``None``. However in some cases it
For most actions, this is ``None``. However, in some cases it
contains extra information. See :class:`AuditLogAction` for
which actions have this field filled out.
"""
Expand Down
13 changes: 7 additions & 6 deletions discord/automod.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ class AutoModActionMetadata:
Attributes
-----------
channel_id: :class:`int`
The ID of the channel to send the message to. Only for actions of type :attr:`AutoModActionType.send_alert_message`.
The ID of the channel to send the message to.
Only for actions of type :attr:`AutoModActionType.send_alert_message`.
timeout_duration: :class:`datetime.timedelta`
How long the member that triggered the action should be timed out for. Only for actions of type :attr:`AutoModActionType.timeout`.
How long the member that triggered the action should be timed out for.
Only for actions of type :attr:`AutoModActionType.timeout`.
"""
# maybe add a table of action types and attributes?

Expand Down Expand Up @@ -124,7 +126,6 @@ def __repr__(self) -> str:
return f"<AutoModActionMetadata {inner}>"



class AutoModAction:
"""Represents an action for a guild's auto moderation rule.

Expand Down Expand Up @@ -200,7 +201,7 @@ def to_dict(self) -> Dict:
return data

@classmethod
def from_dict(cls, data: AutoModActionMetadataPayload):
def from_dict(cls, data: AutoModTriggerMetadataPayload):
kwargs = {}

if (keyword_filter := data.get("keyword_filter")) is not None:
Expand Down Expand Up @@ -339,8 +340,8 @@ def exempt_roles(self) -> List[Union[Role, Object]]:

@cached_property
def exempt_channels(self) -> List[Union[Union[TextChannel, ForumChannel, VoiceChannel], Object]]:
"""List[Union[Union[:class:`TextChannel`, :class:`ForumChannel`, :class:`VoiceChannel`], :class:`Object`]]: The channels
that are exempt from this rule.
"""List[Union[Union[:class:`TextChannel`, :class:`ForumChannel`, :class:`VoiceChannel`], :class:`Object`]]:
The channels that are exempt from this rule.

If a channel is not found in the guild's cache,
then it will be returned as an :class:`Object`.
Expand Down
35 changes: 17 additions & 18 deletions discord/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,11 @@ def get_application_command(
return
return command

async def get_desynced_commands(self, guild_id: Optional[int] = None, prefetched=None) -> List[Dict[str, Any]]:
async def get_desynced_commands(
self,
guild_id: Optional[int] = None,
prefetched: Optional[List[ApplicationCommand]] = None
) -> List[Dict[str, Any]]:
"""|coro|

Gets the list of commands that are desynced from discord. If ``guild_id`` is specified, it will only return
Expand All @@ -228,12 +232,12 @@ async def get_desynced_commands(self, guild_id: Optional[int] = None, prefetched
----------
guild_id: Optional[:class:`int`]
The guild id to get the desynced commands for, else global commands if unspecified.
prefetched
prefetched: Optional[List[:class:`.ApplicationCommand`]]
If you already fetched the commands, you can pass them here to be used. Not recommended for typical usage.

Returns
-------
List[Dict[str, Any]]
List[Dict[:class:`str`, Any]]
A list of the desynced commands. Each will come with at least the ``cmd`` and ``action`` keys, which
respectively contain the command and the action to perform. Other keys may also be present depending on
the action, including ``id``.
Expand Down Expand Up @@ -355,8 +359,8 @@ async def register_command(
) -> None:
"""|coro|

Registers a command. If the command has ``guild_ids`` set, or if the ``guild_ids`` parameter is passed, the command will
be registered as a guild command for those guilds.
Registers a command. If the command has ``guild_ids`` set, or if the ``guild_ids`` parameter is passed,
the command will be registered as a guild command for those guilds.

Parameters
----------
Expand Down Expand Up @@ -644,8 +648,6 @@ async def sync_commands(
guild_commands, guild_id=guild_id, method=method, force=force, delete_existing=delete_existing
)

global_permissions: List = []

for i in registered_commands:
cmd = get(
self.pending_application_commands,
Expand Down Expand Up @@ -925,7 +927,7 @@ async def get_application_context(self, interaction: Interaction, cls=None) -> A
Returns the invocation context from the interaction.

This is a more low-level counter-part for :meth:`.process_application_commands`
to allow users more fine grained control over the processing.
to allow users more fine-grained control over the processing.

Parameters
-----------
Expand Down Expand Up @@ -953,7 +955,7 @@ async def get_autocomplete_context(self, interaction: Interaction, cls=None) ->
Returns the autocomplete context from the interaction.

This is a more low-level counter-part for :meth:`.process_application_commands`
to allow users more fine grained control over the processing.
to allow users more fine-grained control over the processing.

Parameters
-----------
Expand Down Expand Up @@ -1006,10 +1008,7 @@ def _bot(self) -> Union["Bot", "AutoShardedBot"]:
class BotBase(ApplicationCommandMixin, CogMixin, ABC):
_supports_prefixed_commands = False

# TODO I think
def __init__(self, description=None, *args, **options):
# super(Client, self).__init__(*args, **kwargs)
# I replaced ^ with v and it worked
super().__init__(*args, **options)
self.extra_events = {} # TYPE: Dict[str, List[CoroFunc]]
self.__cogs = {} # TYPE: Dict[str, Cog]
Expand Down Expand Up @@ -1048,7 +1047,7 @@ async def on_application_command_error(self, context: ApplicationContext, except

The default command error handler provided by the bot.

By default this prints to :data:`sys.stderr` however it could be
By default, this prints to :data:`sys.stderr` however it could be
overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.
Expand All @@ -1072,7 +1071,7 @@ async def on_application_command_error(self, context: ApplicationContext, except

def check(self, func):
"""A decorator that adds a global check to the bot. A global check is similar to a :func:`.check` that is
applied on a per command basis except it is run before any command checks have been verified and applies to
applied on a per-command basis except it is run before any command checks have been verified and applies to
every command the bot has.

.. note::
Expand Down Expand Up @@ -1126,10 +1125,10 @@ def remove_check(self, func, *, call_once: bool = False) -> None:
the :meth:`.Bot.add_check` call or using :meth:`.check_once`.

"""
l = self._check_once if call_once else self._checks
checks = self._check_once if call_once else self._checks

try:
l.remove(func)
checks.remove(func)
except ValueError:
pass

Expand Down Expand Up @@ -1374,7 +1373,7 @@ class Bot(BotBase, Client):
anything that you can do with a :class:`discord.Client` you can do with
this bot.

This class also subclasses :class:`.ApplicationCommandMixin` to provide the functionality
This class also subclasses ``ApplicationCommandMixin`` to provide the functionality
Lulalaby marked this conversation as resolved.
Show resolved Hide resolved
to manage commands.

.. versionadded:: 2.0
Expand All @@ -1401,7 +1400,7 @@ class Bot(BotBase, Client):

.. versionadded:: 2.0
auto_sync_commands: :class:`bool`
Whether or not to automatically sync slash commands. This will call sync_commands in on_connect, and in
Whether to automatically sync slash commands. This will call sync_commands in on_connect, and in
:attr:`.process_application_commands` if the command is not found. Defaults to ``True``.

.. versionadded:: 2.0
Expand Down
Loading