Skip to content

Commit a2dd302

Browse files
authored
Merge branch 'code-refactorings' into master
2 parents 8a4a416 + aaf2ddf commit a2dd302

File tree

24 files changed

+158
-213
lines changed

24 files changed

+158
-213
lines changed

discord/__main__.py

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

3737

3838
def show_version() -> None:
39-
entries = ["- Python v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(sys.version_info)]
40-
4139
version_info = discord.version_info
42-
entries.append("- py-cord v{0.major}.{0.minor}.{0.micro}-{0.releaselevel}".format(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+
]
44+
4345
if version_info.releaselevel != "final":
44-
pkg = pkg_resources.get_distribution("py-cord")
45-
if pkg:
46+
if pkg := pkg_resources.get_distribution("py-cord"):
4647
entries.append(f" - py-cord pkg_resources: v{pkg.version}")
4748

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

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

178179
_translation_table = str.maketrans(_base_table)
179180

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

244245
try:
245246
with open(str(new_directory / "bot.py"), "w", encoding="utf-8") as fp:
246-
base = "Bot" if not args.sharded else "AutoShardedBot"
247+
base = "AutoShardedBot" if args.sharded else "Bot"
247248
fp.write(_bot_template.format(base=base, prefix=args.prefix))
248249
except OSError as exc:
249250
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: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -422,15 +422,13 @@ 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-
category = self.guild.get_channel(parent_id)
426-
if category:
425+
if category := self.guild.get_channel(parent_id):
427426
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
428427
options["parent_id"] = parent_id
429428
elif lock_permissions and self.category_id is not None:
430429
# if we're syncing permissions on a pre-existing channel category without changing it
431430
# we need to update the permissions to point to the pre-existing category
432-
category = self.guild.get_channel(self.category_id)
433-
if category:
431+
if category := self.guild.get_channel(self.category_id):
434432
options["permission_overwrites"] = [c._asdict() for c in category._overwrites]
435433
else:
436434
await self._move(
@@ -491,8 +489,7 @@ def _fill_overwrites(self, data: GuildChannelPayload) -> None:
491489
everyone_index = index
492490

493491
# do the swap
494-
tmp = self._overwrites
495-
if tmp:
492+
if tmp := self._overwrites:
496493
tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index]
497494

498495
@property
@@ -879,8 +876,8 @@ async def set_permissions(self, target, *, overwrite=_undefined, reason=None, **
879876
raise InvalidArgument("No overwrite provided.")
880877
try:
881878
overwrite = PermissionOverwrite(**permissions)
882-
except (ValueError, TypeError):
883-
raise InvalidArgument("Invalid permissions given to keyword arguments.")
879+
except (ValueError, TypeError) as e:
880+
raise InvalidArgument("Invalid permissions given to keyword arguments.") from e
884881
elif len(permissions) > 0:
885882
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")
886883

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

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

16801677
if not getattr(channel.permissions_for(channel.guild.me), permission):
16811678
return False

discord/activity.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -841,10 +841,8 @@ 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-
if "url" in data:
845-
# the url won't be None here
846-
return Streaming(**data) # type: ignore
847-
return Activity(**data)
844+
# the url won't be None here
845+
return Streaming(**data) if "url" in data else Activity(**data)
848846
elif game_type is ActivityType.listening and "sync_id" in data and "session_id" in data:
849847
return Spotify(**data)
850848
return Activity(**data)

discord/asset.py

Lines changed: 17 additions & 19 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-
format = "gif" if animated else "png"
177+
fmt = "gif" if animated else "png"
178178
return cls(
179179
state,
180-
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{format}?size=1024",
180+
url=f"{cls.BASE}/avatars/{user_id}/{avatar}.{fmt}?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-
format = "gif" if animated else "png"
188+
fmt = "gif" if animated else "png"
189189
return cls(
190190
state,
191-
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024",
191+
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{fmt}?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-
format = "png"
217+
fmt = "png"
218218
if path == "banners":
219219
animated = image.startswith("a_")
220-
format = "gif" if animated else "png"
220+
fmt = "gif" if animated else "png"
221221

222222
return cls(
223223
state,
224-
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{format}?size=1024",
224+
url=f"{cls.BASE}/{path}/{guild_id}/{image}.{fmt}?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-
format = "gif" if animated else "png"
232+
fmt = "gif" if animated else "png"
233233
return cls(
234234
state,
235-
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{format}?size=1024",
235+
url=f"{cls.BASE}/icons/{guild_id}/{icon_hash}.{fmt}?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-
format = "gif" if animated else "png"
252+
fmt = "gif" if animated else "png"
253253
return cls(
254254
state,
255-
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{format}?size=512",
255+
url=f"{cls.BASE}/banners/{user_id}/{banner_hash}.{fmt}?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 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:
347+
if size == MISSING:
352348
url = url.with_query(url.raw_query_string)
353349

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

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

discord/audit_logs.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,15 +95,11 @@ 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-
if data is None:
99-
return None
100-
return entry._get_member(int(data))
98+
return None if data is None else entry._get_member(int(data))
10199

102100

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

108104

109105
def _transform_overwrites(

discord/bot.py

Lines changed: 9 additions & 8 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 i, subcommand in enumerate(cmd.subcommands):
248+
for subcommand in 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]] = [],
574-
delete_existing: bool = True,
573+
check_guilds: Optional[List[int]] = None,
574+
delete_exiting: bool = True,
575575
) -> None:
576576
"""|coro|
577577
@@ -615,6 +615,8 @@ 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 = []
618620
check_guilds = list(set((check_guilds or []) + (self.debug_guilds or [])))
619621

620622
if commands is None:
@@ -647,13 +649,12 @@ async def sync_commands(
647649
global_permissions: List = []
648650

649651
for i in registered_commands:
650-
cmd = get(
652+
if cmd := get(
651653
self.pending_application_commands,
652654
name=i["name"],
653655
guild_ids=None,
654656
type=i["type"],
655-
)
656-
if cmd:
657+
):
657658
cmd.id = i["id"]
658659
self._application_commands[cmd.id] = cmd
659660

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

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

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

12211222
if name in self.extra_events:
12221223
try:

discord/channel.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -563,7 +563,8 @@ 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=str(name), avatar=avatar, reason=reason)
566+
data = await self._state.http.create_webhook(self.id, name=name, avatar=avatar, reason=reason)
567+
567568
return Webhook.from_state(data, state=self._state)
568569

569570
async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook:
@@ -731,7 +732,7 @@ async def create_thread(
731732
name: str,
732733
message: Optional[Snowflake] = None,
733734
auto_archive_duration: ThreadArchiveDuration = MISSING,
734-
type: Optional[ChannelType] = None,
735+
channel_type: Optional[ChannelType] = None,
735736
reason: Optional[str] = None,
736737
) -> Thread:
737738
"""|coro|
@@ -754,7 +755,7 @@ async def create_thread(
754755
auto_archive_duration: :class:`int`
755756
The duration in minutes before a thread is automatically archived for inactivity.
756757
If not provided, the channel's default auto archive duration is used.
757-
type: Optional[:class:`ChannelType`]
758+
channel_type: Optional[:class:`ChannelType`]
758759
The type of thread to create. If a ``message`` is passed then this parameter
759760
is ignored, as a thread created with a message is always a public thread.
760761
By default this creates a private thread if this is ``None``.
@@ -774,15 +775,15 @@ async def create_thread(
774775
The created thread
775776
"""
776777

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

780781
if message is None:
781782
data = await self._state.http.start_thread_without_message(
782783
self.id,
783784
name=name,
784785
auto_archive_duration=auto_archive_duration or self.default_auto_archive_duration,
785-
type=type.value,
786+
type=channel_type.value,
786787
reason=reason,
787788
)
788789
else:
@@ -1409,7 +1410,8 @@ async def create_webhook(
14091410
if avatar is not None:
14101411
avatar = utils._bytes_to_base64_data(avatar) # type: ignore
14111412

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

14151417
@property

0 commit comments

Comments
 (0)