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

fix: Overall type-hinting improvements #2457

Merged
merged 21 commits into from
Jun 5, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ These changes are available on the `master` branch, but have not yet been releas
([#2448](https://github.com/Pycord-Development/pycord/pull/2448))
- Fixed missing `application_id` in `Entitlement.delete`.
([#2458](https://github.com/Pycord-Development/pycord/pull/2458))
- Fixed the incorrect type of `RawMemberRemoveEvent.user`.
yoggys marked this conversation as resolved.
Show resolved Hide resolved
([#2457](https://github.com/Pycord-Development/pycord/pull/2457))

### Changed

Expand Down
12 changes: 6 additions & 6 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async def _single_delete_strategy(


async def _purge_messages_helper(
channel: TextChannel | Thread | VoiceChannel,
channel: TextChannel | StageChannel | Thread | VoiceChannel,
*,
limit: int | None = 100,
check: Callable[[Message], bool] = MISSING,
Expand Down Expand Up @@ -1345,7 +1345,7 @@ async def send(
file: File = ...,
stickers: Sequence[GuildSticker | StickerItem] = ...,
delete_after: float = ...,
nonce: str | int = ...,
nonce: int | str = ...,
enforce_nonce: bool = ...,
allowed_mentions: AllowedMentions = ...,
reference: Message | MessageReference | PartialMessage = ...,
Expand All @@ -1365,7 +1365,7 @@ async def send(
files: list[File] = ...,
stickers: Sequence[GuildSticker | StickerItem] = ...,
delete_after: float = ...,
nonce: str | int = ...,
nonce: int | str = ...,
enforce_nonce: bool = ...,
allowed_mentions: AllowedMentions = ...,
reference: Message | MessageReference | PartialMessage = ...,
Expand All @@ -1385,7 +1385,7 @@ async def send(
file: File = ...,
stickers: Sequence[GuildSticker | StickerItem] = ...,
delete_after: float = ...,
nonce: str | int = ...,
nonce: int | str = ...,
enforce_nonce: bool = ...,
allowed_mentions: AllowedMentions = ...,
reference: Message | MessageReference | PartialMessage = ...,
Expand All @@ -1405,7 +1405,7 @@ async def send(
files: list[File] = ...,
stickers: Sequence[GuildSticker | StickerItem] = ...,
delete_after: float = ...,
nonce: str | int = ...,
nonce: int | str = ...,
enforce_nonce: bool = ...,
allowed_mentions: AllowedMentions = ...,
reference: Message | MessageReference | PartialMessage = ...,
Expand Down Expand Up @@ -1465,7 +1465,7 @@ async def send(
The file to upload.
files: List[:class:`~discord.File`]
A list of files to upload. Must be a maximum of 10.
nonce: :class:`int`
nonce: Union[:class:`str`, :class:`int`]
The nonce to use for sending this message. If the message was successfully sent,
then the message will have a nonce with this value.
enforce_nonce: Optional[:class:`bool`]
Expand Down
10 changes: 5 additions & 5 deletions discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,16 +193,16 @@ def _transform_type(

def _transform_actions(
entry: AuditLogEntry, data: list[AutoModActionPayload] | None
) -> AutoModAction | None:
) -> list[AutoModAction] | None:
if data is None:
return None
else:
return [AutoModAction.from_dict(d) for d in data]


def _transform_trigger_metadata(
entry: AuditLogEntry, data: list[AutoModActionPayload] | None
) -> AutoModAction | None:
entry: AuditLogEntry, data: AutoModTriggerMetadataPayload | None
) -> AutoModTriggerMetadata | None:
if data is None:
return None
else:
Expand Down Expand Up @@ -309,7 +309,7 @@ def __init__(
"$add_allow_list",
]:
self._handle_trigger_metadata(
self.before, self.after, entry, elem["new_value"], attr
self.before, self.after, entry, elem["new_value"], attr # type: ignore
)
continue
elif attr in [
Expand All @@ -318,7 +318,7 @@ def __init__(
"$remove_allow_list",
]:
self._handle_trigger_metadata(
self.after, self.before, entry, elem["new_value"], attr
self.after, self.before, entry, elem["new_value"], attr # type: ignore
yoggys marked this conversation as resolved.
Show resolved Hide resolved
)
continue

Expand Down
2 changes: 1 addition & 1 deletion discord/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -1218,7 +1218,7 @@ async def create_thread(
A list of stickers to upload. Must be a maximum of 3.
delete_message_after: :class:`int`
The time to wait before deleting the thread.
nonce: :class:`int`
nonce: Union[:class:`str`, :class:`int`]
The nonce to use for sending this message. If the message was successfully sent,
then the message will have a nonce with this value.
allowed_mentions: :class:`~discord.AllowedMentions`
Expand Down
4 changes: 2 additions & 2 deletions discord/commands/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
import discord
from .. import Bot
from ..state import ConnectionState
from ..voice_client import VoiceProtocol
from ..voice_client import VoiceClient

from .core import ApplicationCommand, Option
from ..interactions import InteractionChannel
Expand Down Expand Up @@ -211,7 +211,7 @@ def user(self) -> Member | User:
author: Member | User = user

@property
def voice_client(self) -> VoiceProtocol | None:
def voice_client(self) -> VoiceClient | None:
"""Returns the voice client associated with this context's command.
Shorthand for :attr:`Interaction.guild.voice_client<~discord.Guild.voice_client>`, if applicable.
"""
Expand Down
6 changes: 3 additions & 3 deletions discord/commands/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def is_on_cooldown(self, ctx: ApplicationContext) -> bool:
if not self._buckets.valid:
return False

bucket = self._buckets.get_bucket(ctx)
bucket = self._buckets.get_bucket(ctx) # type: ignore
current = utcnow().timestamp()
return bucket.get_tokens(current) == 0

Expand Down Expand Up @@ -363,7 +363,7 @@ def get_cooldown_retry_after(self, ctx: ApplicationContext) -> float:
If this is ``0.0`` then the command isn't on cooldown.
"""
if self._buckets.valid:
bucket = self._buckets.get_bucket(ctx)
bucket = self._buckets.get_bucket(ctx) # type: ignore
yoggys marked this conversation as resolved.
Show resolved Hide resolved
current = utcnow().timestamp()
return bucket.get_retry_after(current)

Expand Down Expand Up @@ -1245,7 +1245,7 @@ def to_dict(self) -> dict:

return as_dict

def add_command(self, command: SlashCommand) -> None:
def add_command(self, command: SlashCommand | SlashCommandGroup) -> None:
if command.cog is None and self.cog is not None:
command.cog = self.cog

Expand Down
2 changes: 1 addition & 1 deletion discord/context_managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
__all__ = ("Typing",)


def _typing_done_callback(fut: asyncio.Future) -> None:
def _typing_done_callback(fut: asyncio.Task) -> None:
# just retrieve any exception and call it a day
try:
fut.exception()
Expand Down
4 changes: 2 additions & 2 deletions discord/ext/commands/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1166,7 +1166,7 @@ async def _actual_conversion(


async def run_converters(
ctx: Context, converter, argument: str, param: inspect.Parameter
ctx: Context, converter, argument: str | None, param: inspect.Parameter
):
"""|coro|

Expand All @@ -1182,7 +1182,7 @@ async def run_converters(
The invocation context to run the converters under.
converter: Any
The converter to run, this corresponds to the annotation in the function.
argument: :class:`str`
argument: Optional[:class:`str`]
The argument to convert to.
param: :class:`inspect.Parameter`
The parameter being converted. This is mainly for error reporting.
Expand Down
8 changes: 7 additions & 1 deletion discord/ext/commands/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,13 @@ class Paginator:
.. versionadded:: 1.7
"""

def __init__(self, prefix="```", suffix="```", max_size=2000, linesep="\n"):
def __init__(
self,
prefix: str | None = "```",
suffix: str | None = "```",
max_size: int = 2000,
linesep: str = "\n",
):
self.prefix = prefix
self.suffix = suffix
self.max_size = max_size
Expand Down
10 changes: 5 additions & 5 deletions discord/guild.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@
from .types.member import Member as MemberPayload
from .types.threads import Thread as ThreadPayload
from .types.voice import GuildVoiceState
from .voice_client import VoiceProtocol
from .voice_client import VoiceClient
from .webhook import Webhook

VocalGuildChannel = Union[VoiceChannel, StageChannel]
Expand Down Expand Up @@ -647,8 +647,8 @@ def me(self) -> Member:
return self.get_member(self_id) # type: ignore

@property
def voice_client(self) -> VoiceProtocol | None:
"""Returns the :class:`VoiceProtocol` associated with this guild, if any."""
def voice_client(self) -> VoiceClient | None:
"""Returns the :class:`VoiceClient` associated with this guild, if any."""
return self._state._get_voice_client(self.id)

@property
Expand Down Expand Up @@ -3121,7 +3121,7 @@ async def bulk_ban(
*users: Snowflake,
delete_message_seconds: int | None = None,
reason: str | None = None,
) -> list[list[Snowflake], list[Snowflake]]:
) -> tuple[list[Snowflake], list[Snowflake]]:
yoggys marked this conversation as resolved.
Show resolved Hide resolved
r"""|coro|

Bulk ban users from the guild.
Expand Down Expand Up @@ -3152,7 +3152,7 @@ async def bulk_ban(

Returns
-------
List[List[:class:`abc.Snowflake`], List[:class:`abc.Snowflake`]]
Tuple[List[:class:`abc.Snowflake`], List[:class:`abc.Snowflake`]]
Returns two lists: the first contains members that were successfully banned, while the second is members that could not be banned.

Raises
Expand Down
12 changes: 6 additions & 6 deletions discord/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,7 @@ def send_message(
tts: bool = False,
embed: embed.Embed | None = None,
embeds: list[embed.Embed] | None = None,
nonce: str | None = None,
nonce: int | str | None = None,
enforce_nonce: bool | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
Expand Down Expand Up @@ -524,7 +524,7 @@ def send_multipart_helper(
tts: bool = False,
embed: embed.Embed | None = None,
embeds: Iterable[embed.Embed | None] | None = None,
nonce: str | None = None,
nonce: int | str | None = None,
enforce_nonce: bool | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
Expand Down Expand Up @@ -587,7 +587,7 @@ def send_files(
tts: bool = False,
embed: embed.Embed | None = None,
embeds: list[embed.Embed] | None = None,
nonce: str | None = None,
nonce: int | str | None = None,
enforce_nonce: bool | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
Expand Down Expand Up @@ -1203,7 +1203,7 @@ def start_forum_thread(
files: Sequence[File] | None = None,
embed: embed.Embed | None = None,
embeds: list[embed.Embed] | None = None,
nonce: str | None = None,
nonce: int | str | None = None,
allowed_mentions: message.AllowedMentions | None = None,
stickers: list[sticker.StickerItem] | None = None,
components: list[components.Component] | None = None,
Expand Down Expand Up @@ -2151,8 +2151,8 @@ def edit_channel_permissions(
self,
channel_id: Snowflake,
target: Snowflake,
allow: str,
deny: str,
allow: int | str,
deny: int | str,
type: channel.OverwriteType,
*,
reason: str | None = None,
Expand Down
2 changes: 1 addition & 1 deletion discord/interactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,7 +1221,7 @@ async def premium_required(self) -> Interaction:
self._responded = True
return self._parent

async def _locked_response(self, coro: Coroutine[Any]):
async def _locked_response(self, coro: Coroutine[Any, Any, Any]) -> None:
"""|coro|

Wraps a response and makes sure that it's locked while executing.
Expand Down
3 changes: 2 additions & 1 deletion discord/invite.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
from .types.invite import GatewayInvite as GatewayInvitePayload
from .types.invite import Invite as InvitePayload
from .types.invite import InviteGuild as InviteGuildPayload
from .types.invite import VanityInvite as VanityInvitePayload
from .types.scheduled_events import ScheduledEvent as ScheduledEventPayload
from .user import User

Expand Down Expand Up @@ -353,7 +354,7 @@ def __init__(
self,
*,
state: ConnectionState,
data: InvitePayload,
data: InvitePayload | VanityInvitePayload,
guild: PartialInviteGuild | Guild | None = None,
channel: PartialInviteChannel | GuildChannel | None = None,
):
Expand Down
12 changes: 10 additions & 2 deletions discord/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
from .types.member import MemberWithUser as MemberWithUserPayload
from .types.member import UserWithMember as UserWithMemberPayload
from .types.user import User as UserPayload
from .types.voice import GuildVoiceState as GuildVoiceStatePayload
from .types.voice import VoiceState as VoiceStatePayload

VocalGuildChannel = Union[VoiceChannel, StageChannel]
Expand Down Expand Up @@ -125,12 +126,19 @@ class VoiceState:
)

def __init__(
self, *, data: VoiceStatePayload, channel: VocalGuildChannel | None = None
self,
*,
data: VoiceStatePayload | GuildVoiceStatePayload,
channel: VocalGuildChannel | None = None,
):
self.session_id: str = data.get("session_id")
self._update(data, channel)

def _update(self, data: VoiceStatePayload, channel: VocalGuildChannel | None):
def _update(
self,
data: VoiceStatePayload | GuildVoiceStatePayload,
channel: VocalGuildChannel | None,
):
self.self_mute: bool = data.get("self_mute", False)
self.self_deaf: bool = data.get("self_deaf", False)
self.self_stream: bool = data.get("self_stream", False)
Expand Down
4 changes: 2 additions & 2 deletions discord/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,14 +240,14 @@ def __init__(self, *, data: AttachmentPayload, state: ConnectionState):
setattr(self, attr, value)

@property
def expires_at(self) -> datetime.datetime:
def expires_at(self) -> datetime.datetime | None:
"""This attachment URL's expiry time in UTC."""
if not self._ex:
return None
return datetime.datetime.utcfromtimestamp(int(self._ex, 16))

@property
def issued_at(self) -> datetime.datetime:
def issued_at(self) -> datetime.datetime | None:
"""The attachment URL's issue time in UTC."""
if not self._is:
return None
Expand Down
4 changes: 3 additions & 1 deletion discord/partial_emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ class PartialEmoji(_EmojiTag, AssetMixin):
if TYPE_CHECKING:
id: int | None

def __init__(self, *, name: str, animated: bool = False, id: int | None = None):
def __init__(
self, *, name: str | None, animated: bool = False, id: int | None = None
):
self.animated = animated
self.name = name
self.id = id
Expand Down
2 changes: 1 addition & 1 deletion discord/raw_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@

from .automod import AutoModAction, AutoModTriggerType
from .enums import AuditLogAction, ChannelType, ReactionType, try_enum
from .types.user import User

if TYPE_CHECKING:
from .abc import MessageableChannel
Expand Down Expand Up @@ -58,6 +57,7 @@
TypingEvent,
VoiceChannelStatusUpdateEvent,
)
from .user import User


__all__ = (
Expand Down
2 changes: 1 addition & 1 deletion discord/reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def __init__(
self.me: bool = data.get("me")
self.burst: bool = data.get("burst")
self.me_burst: bool = data.get("me_burst")
self._burst_colours: list[Colour] = data.get("burst_colors", [])
self._burst_colours: list[str] = data.get("burst_colors", [])

@property
def burst_colours(self) -> list[Colour]:
Expand Down
Loading
Loading