Skip to content

Commit 912bd8f

Browse files
committed
Revert "Merge branch 'code-refactorings' into master"
This reverts commit a2dd302, reversing changes made to 8a4a416.
1 parent e441641 commit 912bd8f

File tree

24 files changed

+213
-158
lines changed

24 files changed

+213
-158
lines changed

discord/__main__.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,14 +36,13 @@
3636

3737

3838
def show_version() -> None:
39-
version_info = discord.version_info
40-
entries = [
41-
"- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info),
42-
"- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info),
43-
]
39+
entries = ["- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info)]
4440

41+
version_info = discord.version_info
42+
entries.append("- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(version_info))
4543
if version_info.releaselevel != "final":
46-
if pkg := pkg_resources.get_distribution("py-cord"):
44+
pkg = pkg_resources.get_distribution("py-cord")
45+
if pkg:
4746
entries.append(f" - py-cord pkg_resources: v{pkg.version}")
4847

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

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

179178
_translation_table = str.maketrans(_base_table)
180179

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

245244
try:
246245
with open(str(new_directory / "bot.py"), "w", encoding="utf-8") as fp:
247-
base = "AutoShardedBot" if args.sharded else "Bot"
246+
base = "Bot" if not args.sharded else "AutoShardedBot"
248247
fp.write(_bot_template.format(base=base, prefix=args.prefix))
249248
except OSError as exc:
250249
parser.error(f"could not create bot file ({exc})")
250+
251251
if not args.no_git:
252252
try:
253253
with open(str(new_directory / ".gitignore"), "w", encoding="utf-8") as fp:

discord/abc.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -422,13 +422,15 @@ async def _edit(self, options: Dict[str, Any], reason: Optional[str]) -> Optiona
422422
except KeyError:
423423
if parent_id is not _undefined:
424424
if lock_permissions:
425-
if category := self.guild.get_channel(parent_id):
425+
category = self.guild.get_channel(parent_id)
426+
if category:
426427
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
427428
options["parent_id"] = parent_id
428429
elif lock_permissions and self.category_id is not None:
429430
# if we're syncing permissions on a pre-existing channel category without changing it
430431
# we need to update the permissions to point to the pre-existing category
431-
if category := self.guild.get_channel(self.category_id):
432+
category = self.guild.get_channel(self.category_id)
433+
if category:
432434
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
433435
else:
434436
await self._move(
@@ -489,7 +491,8 @@ def _fill_overwrites(self, data: GuildChannelPayload) -> None:
489491
everyone_index = index
490492

491493
# do the swap
492-
if tmp := self._overwrites:
494+
tmp = self._overwrites
495+
if tmp:
493496
tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index]
494497

495498
@property
@@ -876,8 +879,8 @@ async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **
876879
raise InvalidArgument("No overwrite provided.")
877880
try:
878881
overwrite = PermissionOverwrite(**permissions)
879-
except (ValueError, TypeError) as e:
880-
raise InvalidArgument("Invalid permissions given to keyword arguments.") from e
882+
except (ValueError, TypeError):
883+
raise InvalidArgument("Invalid permissions given to keyword arguments.")
881884
elif len(permissions) > 0:
882885
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")
883886

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

1674-
except (KeyError, AttributeError) as e:
1675-
raise TypeError(f"The object {obj} is of an invalid type.") from e
1677+
except (KeyError, AttributeError):
1678+
raise TypeError(f"The object {obj} is of an invalid type.")
16761679

16771680
if not getattr(channel.permissions_for(channel.guild.me), permission):
16781681
return False

discord/activity.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -841,8 +841,10 @@ def create_activity(data: Optional[ActivityPayload]) -> Optional[ActivityTypes]:
841841
# we removed the name key from data already
842842
return CustomActivity(name=name, **data) # type: ignore
843843
elif game_type is ActivityType.streaming:
844-
# the url won't be None here
845-
return Streaming(**data) if "url" in data else Activity(**data)
844+
if "url" in data:
845+
# the url won't be None here
846+
return Streaming(**data) # type: ignore
847+
return Activity(**data)
846848
elif game_type is ActivityType.listening and "sync_id" in data and "session_id" in data:
847849
return Spotify(**data)
848850
return Activity(**data)

discord/asset.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -174,21 +174,21 @@ def _from_default_avatar(cls, state, index: int) -> Asset:
174174
@classmethod
175175
def _from_avatar(cls, state, user_id: int, avatar: str) -> Asset:
176176
animated = avatar.startswith("a_")
177-
fmt = "gif" if animated else "png"
177+
format = "gif" if animated else "png"
178178
return cls(
179179
state,
180-
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{fmt}?size=1024",
180+
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
181181
key=avatar,
182182
animated=animated,
183183
)
184184

185185
@classmethod
186186
def _from_guild_avatar(cls, state, guild_id: int, member_id: int, avatar: str) -> Asset:
187187
animated = avatar.startswith("a_")
188-
fmt = "gif" if animated else "png"
188+
format = "gif" if animated else "png"
189189
return cls(
190190
state,
191-
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{fmt}?size=1024",
191+
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
192192
key=avatar,
193193
animated=animated,
194194
)
@@ -214,25 +214,25 @@ def _from_cover_image(cls, state, object_id: int, cover_image_hash: str) -> Asse
214214
@classmethod
215215
def _from_guild_image(cls, state, guild_id: int, image: str, path: str) -> Asset:
216216
animated = False
217-
fmt = "png"
217+
format = "png"
218218
if path == "banners":
219219
animated = image.startswith("a_")
220-
fmt = "gif" if animated else "png"
220+
format = "gif" if animated else "png"
221221

222222
return cls(
223223
state,
224-
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{fmt}?size=1024",
224+
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
225225
key=image,
226226
animated=animated,
227227
)
228228

229229
@classmethod
230230
def _from_guild_icon(cls, state, guild_id: int, icon_hash: str) -> Asset:
231231
animated = icon_hash.startswith("a_")
232-
fmt = "gif" if animated else "png"
232+
format = "gif" if animated else "png"
233233
return cls(
234234
state,
235-
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{fmt}?size=1024",
235+
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
236236
key=icon_hash,
237237
animated=animated,
238238
)
@@ -249,10 +249,10 @@ def _from_sticker_banner(cls, state, banner: int) -> Asset:
249249
@classmethod
250250
def _from_user_banner(cls, state, user_id: int, banner_hash: str) -> Asset:
251251
animated = banner_hash.startswith("a_")
252-
fmt = "gif" if animated else "png"
252+
format = "gif" if animated else "png"
253253
return cls(
254254
state,
255-
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{fmt}?size=512",
255+
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
256256
key=banner_hash,
257257
animated=animated,
258258
)
@@ -344,13 +344,13 @@ def replace(
344344
raise InvalidArgument(f"static_format must be one of {VALID_STATIC_FORMATS}")
345345
url = url.with_path(f"{path}.{static_format}")
346346

347-
if size == MISSING:
347+
if size is not MISSING:
348+
if not utils.valid_icon_size(size):
349+
raise InvalidArgument("size must be a power of 2 between 16 and 4096")
350+
url = url.with_query(size=size)
351+
else:
348352
url = url.with_query(url.raw_query_string)
349353

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

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

433-
return self if self._animated else self.with_format(format)
433+
if self._animated:
434+
return self
435+
return self.with_format(format)

discord/audit_logs.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,15 @@ def _transform_channel(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optio
9595

9696

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

100102

101103
def _transform_guild_id(entry: AuditLogEntry, data: Optional[Snowflake]) -> Optional[Guild]:
102-
return None if data is None else entry._state._get_guild(data)
104+
if data is None:
105+
return None
106+
return entry._state._get_guild(data)
103107

104108

105109
def _transform_overwrites(

discord/bot.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ def _check_command(cmd: ApplicationCommand, match: Dict) -> bool:
245245
if isinstance(cmd, SlashCommandGroup):
246246
if len(cmd.subcommands) != len(match.get("options", [])):
247247
return True
248-
for subcommand in cmd.subcommands:
248+
for i, subcommand in enumerate(cmd.subcommands):
249249
match_ = next(
250250
(data for data in match["options"] if data["name"] == subcommand.name),
251251
MISSING,
@@ -570,8 +570,8 @@ async def sync_commands(
570570
force: bool = False,
571571
guild_ids: Optional[List[int]] = None,
572572
register_guild_commands: bool = True,
573-
check_guilds: Optional[List[int]] = None,
574-
delete_exiting: bool = True,
573+
check_guilds: Optional[List[int]] = [],
574+
delete_existing: bool = True,
575575
) -> None:
576576
"""|coro|
577577
@@ -615,8 +615,6 @@ async def sync_commands(
615615
Whether to delete existing commands that are not in the list of commands to register. Defaults to True.
616616
"""
617617

618-
if check_guilds is None:
619-
check_guilds = []
620618
check_guilds = list(set((check_guilds or []) + (self.debug_guilds or [])))
621619

622620
if commands is None:
@@ -649,12 +647,13 @@ async def sync_commands(
649647
global_permissions: List = []
650648

651649
for i in registered_commands:
652-
if cmd := get(
650+
cmd = get(
653651
self.pending_application_commands,
654652
name=i["name"],
655653
guild_ids=None,
656654
type=i["type"],
657-
):
655+
)
656+
if cmd:
658657
cmd.id = i["id"]
659658
self._application_commands[cmd.id] = cmd
660659

@@ -1195,7 +1194,7 @@ async def my_message(message): pass
11951194
bot.add_listener(on_ready)
11961195
bot.add_listener(my_message, 'on_message')
11971196
"""
1198-
name = func.__name__ if name == MISSING else name
1197+
name = func.__name__ if name is MISSING else name
11991198

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

1220-
name = func.__name__ if name == MISSING else name
1219+
name = func.__name__ if name is MISSING else name
12211220

12221221
if name in self.extra_events:
12231222
try:

discord/channel.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -563,8 +563,7 @@ async def create_webhook(
563563
if avatar is not None:
564564
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
565565

566-
data = await self._state.http.create_webhook(self.id, name=name, avatar=avatar, reason=reason)
567-
566+
data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
568567
return Webhook.from_state(data, state=self._state)
569568

570569
async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook:
@@ -732,7 +731,7 @@ async def create_thread(
732731
name: str,
733732
message: Optional[Snowflake] = None,
734733
auto_archive_duration: ThreadArchiveDuration = MISSING,
735-
channel_type: Optional[ChannelType] = None,
734+
type: Optional[ChannelType] = None,
736735
reason: Optional[str] = None,
737736
) -> Thread:
738737
"""|coro|
@@ -755,7 +754,7 @@ async def create_thread(
755754
auto_archive_duration: :class:`int`
756755
The duration in minutes before a thread is automatically archived for inactivity.
757756
If not provided, the channel's default auto archive duration is used.
758-
channel_type: Optional[:class:`ChannelType`]
757+
type: Optional[:class:`ChannelType`]
759758
The type of thread to create. If a ``message`` is passed then this parameter
760759
is ignored, as a thread created with a message is always a public thread.
761760
By default this creates a private thread if this is ``None``.
@@ -775,15 +774,15 @@ async def create_thread(
775774
The created thread
776775
"""
777776

778-
if channel_type is None:
779-
channel_type = ChannelType.private_thread
777+
if type is None:
778+
type = ChannelType.private_thread
780779

781780
if message is None:
782781
data = await self._state.http.start_thread_without_message(
783782
self.id,
784783
name=name,
785784
auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration,
786-
type=channel_type.value,
785+
type=type.value,
787786
reason=reason,
788787
)
789788
else:
@@ -1410,8 +1409,7 @@ async def create_webhook(
14101409
if avatar is not None:
14111410
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
14121411

1413-
data = await self._state.http.create_webhook(self.id, name=name, avatar=avatar, reason=reason)
1414-
1412+
data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
14151413
return Webhook.from_state(data, state=self._state)
14161414

14171415
@property

0 commit comments

Comments
 (0)