Skip to content

Commit

Permalink
Revert "Merge branch 'code-refactorings' into master"
Browse files Browse the repository at this point in the history
This reverts commit a2dd302, reversing
changes made to 8a4a416.
  • Loading branch information
Dorukyum committed Jun 13, 2022
1 parent e441641 commit 912bd8f
Show file tree
Hide file tree
Showing 24 changed files with 213 additions and 158 deletions.
16 changes: 8 additions & 8 deletions discord/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,13 @@


def show_version() -> None:
version_info = discord.version_info
entries = [
"- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info),
"- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info),
]
entries = ["- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info)]

version_info = discord.version_info
entries.append("- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info))
if version_info.releaselevel != "final":
if pkg := pkg_resources.get_distribution("py-cord"):
pkg = pkg_resources.get_distribution("py-cord")
if pkg:
entries.append(f" - py-cord pkg_resources: v{pkg.version}")

entries.append(f"- aiohttp v{aiohttp.__version__}")
Expand Down Expand Up @@ -174,7 +173,7 @@ async def cog_after_invoke(self, ctx):
}

# NUL (0) and 1-31 are disallowed
_base_table |= ((chr(i), None) for i in range(32))
_base_table.update((chr(i), None) for i in range(32))

_translation_table = str.maketrans(_base_table)

Expand Down Expand Up @@ -244,10 +243,11 @@ def newbot(parser, args) -> None:

try:
with open(str(new_directory / "bot.py"), "w", encoding="utf-8") as fp:
base = "AutoShardedBot" if args.sharded else "Bot"
base = "Bot" if not args.sharded else "AutoShardedBot"
fp.write(_bot_template.format(base=base, prefix=args.prefix))
except OSError as exc:
parser.error(f"could not create bot file ({exc})")

if not args.no_git:
try:
with open(str(new_directory / ".gitignore"), "w", encoding="utf-8") as fp:
Expand Down
17 changes: 10 additions & 7 deletions discord/abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,13 +422,15 @@ async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optiona
except KeyError:
if parent_id is not _undefined:
if lock_permissions:
if category := self.guild.get_channel(parent_id):
category = self.guild.get_channel(parent_id)
if category:
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
options["parent_id"] = parent_id
elif lock_permissions and self.category_id is not None:
# if we're syncing permissions on a pre-existing channel category without changing it
# we need to update the permissions to point to the pre-existing category
if category := self.guild.get_channel(self.category_id):
category = self.guild.get_channel(self.category_id)
if category:
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
else:
await self._move(
Expand Down Expand Up @@ -489,7 +491,8 @@ def _fill_overwrites(self, data: GuildChannelPayload) -> None:
everyone_index = index

# do the swap
if tmp := self._overwrites:
tmp = self._overwrites
if tmp:
tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index]

@property
Expand Down Expand Up @@ -876,8 +879,8 @@ async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **
raise InvalidArgument("No overwrite provided.")
try:
overwrite = PermissionOverwrite(**permissions)
except (ValueError, TypeError) as e:
raise InvalidArgument("Invalid permissions given to keyword arguments.") from e
except (ValueError, TypeError):
raise InvalidArgument("Invalid permissions given to keyword arguments.")
elif len(permissions) > 0:
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")

Expand Down Expand Up @@ -1671,8 +1674,8 @@ def can_send(self, *objects) -> bool:
if obj.guild_id == channel.guild.id:
continue

except (KeyError, AttributeError) as e:
raise TypeError(f"The object {obj} is of an invalid type.") from e
except (KeyError, AttributeError):
raise TypeError(f"The object {obj} is of an invalid type.")

if not getattr(channel.permissions_for(channel.guild.me), permission):
return False
Expand Down
6 changes: 4 additions & 2 deletions discord/activity.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,8 +841,10 @@ def create_activity(data: Optional[ActivityPayload]) -> Optional[ActivityTypes]:
# we removed the name key from data already
return CustomActivity(name=name, **data) # type: ignore
elif game_type is ActivityType.streaming:
# the url won't be None here
return Streaming(**data) if "url" in data else Activity(**data)
if "url" in data:
# the url won't be None here
return Streaming(**data) # type: ignore
return Activity(**data)
elif game_type is ActivityType.listening and "sync_id" in data and "session_id" in data:
return Spotify(**data)
return Activity(**data)
36 changes: 19 additions & 17 deletions discord/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,21 +174,21 @@ def _from_default_avatar(cls, state, index: int) -> Asset:
@classmethod
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
fmt = "gif" if animated else "png"
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{fmt}?size=1024",
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)

@classmethod
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
animated = avatar.startswith("a_")
fmt = "gif" if animated else "png"
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{fmt}?size=1024",
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
key=avatar,
animated=animated,
)
Expand All @@ -214,25 +214,25 @@ def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asse
@classmethod
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
animated = False
fmt = "png"
format = "png"
if path == "banners":
animated = image.startswith("a_")
fmt = "gif" if animated else "png"
format = "gif" if animated else "png"

return cls(
state,
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{fmt}?size=1024",
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
key=image,
animated=animated,
)

@classmethod
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
animated = icon_hash.startswith("a_")
fmt = "gif" if animated else "png"
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{fmt}?size=1024",
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
key=icon_hash,
animated=animated,
)
Expand All @@ -249,10 +249,10 @@ def _from_sticker_banner(cls, state, banner: int) -> Asset:
@classmethod
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
animated = banner_hash.startswith("a_")
fmt = "gif" if animated else "png"
format = "gif" if animated else "png"
return cls(
state,
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{fmt}?size=512",
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
key=banner_hash,
animated=animated,
)
Expand Down Expand Up @@ -344,13 +344,13 @@ def replace(
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
url = url.with_path(f"{path}.{static_format}")

if size == MISSING:
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")
url = url.with_query(size=size)
else:
url = url.with_query(url.raw_query_string)

elif not utils.valid_icon_size(size):
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
else:
url = url.with_query(size=size)
url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated)

Expand Down Expand Up @@ -430,4 +430,6 @@ def with_static_format(self, format: ValidStaticFormatTypes, /) -> Asset:
The new updated asset.
"""

return self if self._animated else self.with_format(format)
if self._animated:
return self
return self.with_format(format)
8 changes: 6 additions & 2 deletions discord/audit_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,15 @@ def _transform_channel(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optio


def _transform_member_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Union[Member, User, None]:
return None if data is None else entry._get_member(int(data))
if data is None:
return None
return entry._get_member(int(data))


def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Guild]:
return None if data is None else entry._state._get_guild(data)
if data is None:
return None
return entry._state._get_guild(data)


def _transform_overwrites(
Expand Down
17 changes: 8 additions & 9 deletions discord/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def _check_command(cmd: ApplicationCommand, match: Dict) -> bool:
if isinstance(cmd, SlashCommandGroup):
if len(cmd.subcommands) != len(match.get("options", [])):
return True
for subcommand in cmd.subcommands:
for i, subcommand in enumerate(cmd.subcommands):
match_ = next(
(data for data in match["options"] if data["name"] == subcommand.name),
MISSING,
Expand Down Expand Up @@ -570,8 +570,8 @@ async def sync_commands(
force: bool = False,
guild_ids: Optional[List[int]] = None,
register_guild_commands: bool = True,
check_guilds: Optional[List[int]] = None,
delete_exiting: bool = True,
check_guilds: Optional[List[int]] = [],
delete_existing: bool = True,
) -> None:
"""|coro|
Expand Down Expand Up @@ -615,8 +615,6 @@ async def sync_commands(
Whether to delete existing commands that are not in the list of commands to register. Defaults to True.
"""

if check_guilds is None:
check_guilds = []
check_guilds = list(set((check_guilds or []) + (self.debug_guilds or [])))

if commands is None:
Expand Down Expand Up @@ -649,12 +647,13 @@ async def sync_commands(
global_permissions: List = []

for i in registered_commands:
if cmd := get(
cmd = get(
self.pending_application_commands,
name=i["name"],
guild_ids=None,
type=i["type"],
):
)
if cmd:
cmd.id = i["id"]
self._application_commands[cmd.id] = cmd

Expand Down Expand Up @@ -1195,7 +1194,7 @@ async def my_message(message): pass
bot.add_listener(on_ready)
bot.add_listener(my_message, 'on_message')
"""
name = func.__name__ if name == MISSING else name
name = func.__name__ if name is MISSING else name

if not asyncio.iscoroutinefunction(func):
raise TypeError("Listeners must be coroutines")
Expand All @@ -1217,7 +1216,7 @@ def remove_listener(self, func: CoroFunc, name: str = MISSING) -> None:
``func.__name__``.
"""

name = func.__name__ if name == MISSING else name
name = func.__name__ if name is MISSING else name

if name in self.extra_events:
try:
Expand Down
16 changes: 7 additions & 9 deletions discord/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,8 +563,7 @@ async def create_webhook(
if avatar is not None:
avatar = utils._bytes_to_base64_data(avatar) # type: ignore

data = await self._state.http.create_webhook(self.id, name=name, avatar=avatar, reason=reason)

data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
return Webhook.from_state(data, state=self._state)

async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook:
Expand Down Expand Up @@ -732,7 +731,7 @@ async def create_thread(
name: str,
message: Optional[Snowflake] = None,
auto_archive_duration: ThreadArchiveDuration = MISSING,
channel_type: Optional[ChannelType] = None,
type: Optional[ChannelType] = None,
reason: Optional[str] = None,
) -> Thread:
"""|coro|
Expand All @@ -755,7 +754,7 @@ async def create_thread(
auto_archive_duration: :class:`int`
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
channel_type: Optional[:class:`ChannelType`]
type: Optional[:class:`ChannelType`]
The type of thread to create. If a ``message`` is passed then this parameter
is ignored, as a thread created with a message is always a public thread.
By default this creates a private thread if this is ``None``.
Expand All @@ -775,15 +774,15 @@ async def create_thread(
The created thread
"""

if channel_type is None:
channel_type = ChannelType.private_thread
if type is None:
type = ChannelType.private_thread

if message is None:
data = await self._state.http.start_thread_without_message(
self.id,
name=name,
auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration,
type=channel_type.value,
type=type.value,
reason=reason,
)
else:
Expand Down Expand Up @@ -1410,8 +1409,7 @@ async def create_webhook(
if avatar is not None:
avatar = utils._bytes_to_base64_data(avatar) # type: ignore

data = await self._state.http.create_webhook(self.id, name=name, avatar=avatar, reason=reason)

data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
return Webhook.from_state(data, state=self._state)

@property
Expand Down
Loading

0 comments on commit 912bd8f

Please sign in to comment.