Skip to content

Commit 6421496

Browse files
refactor: Auto code audit
Tools used: Sorcery Ruff Black
1 parent 316388b commit 6421496

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+274
-431
lines changed

interactions/api/events/discord.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -534,9 +534,7 @@ class MessageReactionAdd(BaseEvent):
534534
@property
535535
def reaction_count(self) -> int:
536536
"""Times the emoji in the event has been used to react"""
537-
if self.reaction is None:
538-
return 0
539-
return self.reaction.count
537+
return 0 if self.reaction is None else self.reaction.count
540538

541539

542540
@attrs.define(eq=False, order=False, hash=False, kw_only=False)

interactions/api/events/internal.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -236,9 +236,7 @@ class ExtensionLoad(BaseEvent):
236236
@property
237237
def metadata(self) -> "Type[Extension.Metadata] | None":
238238
"""The metadata of the extension, if it has any."""
239-
if self.extension.Metadata:
240-
return self.extension.Metadata
241-
return None
239+
return self.extension.Metadata or None
242240

243241

244242
@attrs.define(eq=False, order=False, hash=False, kw_only=True)

interactions/api/events/processors/guild_events.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,7 @@ async def _on_raw_guild_create(self, event: "RawGatewayEvent") -> None:
3333
event: raw guild create event
3434
3535
"""
36-
new_guild: bool = True
37-
if self.cache.get_guild(event.data["id"]):
38-
# guild already cached, most likely an unavailable guild coming back online
39-
new_guild = False
40-
36+
new_guild = not self.cache.get_guild(event.data["id"])
4137
guild = self.cache.place_guild_data(event.data)
4238

4339
self._user._guild_ids.add(to_snowflake(event.data.get("id")))

interactions/api/http/http_requests/channels.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,7 @@ async def create_tag(
575575
payload: PAYLOAD_TYPE = {
576576
"name": name,
577577
"emoji_id": int(emoji_id) if emoji_id else None,
578-
"emoji_name": emoji_name if emoji_name else None,
578+
"emoji_name": emoji_name or None,
579579
}
580580
payload = dict_filter_none(payload)
581581

interactions/api/http/http_requests/members.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ async def modify_current_member(
138138
reason: An optional reason for the audit log
139139
140140
"""
141-
payload: PAYLOAD_TYPE = {"nick": nickname if not isinstance(nickname, Missing) else None}
141+
payload: PAYLOAD_TYPE = {"nick": None if isinstance(nickname, Missing) else nickname}
142142
await self.request(
143143
Route("PATCH", f"/guilds/{int(guild_id)}/members/@me"),
144144
payload=payload,

interactions/api/voice/audio.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,7 @@ def _max_buffer_size(self) -> int:
220220
@property
221221
def audio_complete(self) -> bool:
222222
"""Uses the state of the subprocess to determine if more audio is coming"""
223-
if self.process:
224-
if self.process.poll() is None:
225-
return False
226-
return True
223+
return not self.process or self.process.poll() is not None
227224

228225
def _create_process(self, *, block: bool = True) -> None:
229226
before = (

interactions/api/voice/recorder.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,7 @@ def run(self) -> None:
170170
# purge any data that is already in the socket
171171
readable, _, _ = select.select([sock], [], [], 0)
172172
log.debug("Purging socket buffer")
173-
while readable:
174-
if not sock.recv(4096):
175-
break
173+
while readable and sock.recv(4096):
176174
readable, _, _ = select.select([sock], [], [], 0)
177175
log.debug("Socket buffer purged, starting recording")
178176

interactions/api/voice/voice_gateway.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,7 @@ async def run(self) -> None:
9292

9393
op = msg.get("op")
9494
data = msg.get("d")
95-
seq = msg.get("s")
96-
97-
if seq:
95+
if seq := msg.get("s"):
9896
self.sequence = seq
9997

10098
# This may try to reconnect the connection so it is best to wait

interactions/client/auto_shard_client.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,7 @@ class AutoShardedClient(Client):
3131
"""
3232

3333
def __init__(self, *args, **kwargs) -> None:
34-
if "total_shards" not in kwargs:
35-
self.auto_sharding = True
36-
else:
37-
self.auto_sharding = False
38-
34+
self.auto_sharding = "total_shards" not in kwargs
3935
super().__init__(*args, **kwargs)
4036

4137
self._connection_state = None

interactions/client/client.py

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -560,9 +560,12 @@ def _sanity_check(self) -> None:
560560
def _queue_task(self, coro: Listener, event: BaseEvent, *args, **kwargs) -> asyncio.Task:
561561
async def _async_wrap(_coro: Listener, _event: BaseEvent, *_args, **_kwargs) -> None:
562562
try:
563-
if not isinstance(_event, (events.Error, events.RawGatewayEvent)):
564-
if coro.delay_until_ready and not self.is_ready:
565-
await self.wait_until_ready()
563+
if (
564+
not isinstance(_event, (events.Error, events.RawGatewayEvent))
565+
and coro.delay_until_ready
566+
and not self.is_ready
567+
):
568+
await self.wait_until_ready()
566569

567570
if len(_event.__attrs_attrs__) == 2 and coro.event != "event":
568571
# override_name & bot & logging
@@ -1046,11 +1049,7 @@ async def wait_for_modal(
10461049
def predicate(event) -> bool:
10471050
if modal.custom_id != event.ctx.custom_id:
10481051
return False
1049-
if not author:
1050-
return True
1051-
if author != to_snowflake(event.ctx.author):
1052-
return False
1053-
return True
1052+
return author == to_snowflake(event.ctx.author) if author else True
10541053

10551054
resp = await self.wait_for("modal_completion", predicate, timeout)
10561055
return resp.ctx
@@ -1085,7 +1084,7 @@ async def wait_for_component(
10851084
asyncio.TimeoutError: if timed out
10861085
10871086
"""
1088-
if not (messages or components):
1087+
if not messages and not components:
10891088
raise ValueError("You must specify messages or components (or both)")
10901089

10911090
message_ids = (
@@ -1105,9 +1104,7 @@ def _check(event: events.Component) -> bool:
11051104
)
11061105
wanted_component = not custom_ids or ctx.custom_id in custom_ids
11071106
if wanted_message and wanted_component:
1108-
if check is None or check(event):
1109-
return True
1110-
return False
1107+
return bool(check is None or check(event))
11111108
return False
11121109

11131110
return await self.wait_for("component", checks=_check, timeout=timeout)
@@ -1242,7 +1239,7 @@ def add_interaction(self, command: InteractionCommand) -> bool:
12421239

12431240
if group is None or isinstance(command, ContextMenu):
12441241
self.interaction_tree[scope][command.resolved_name] = command
1245-
elif group is not None:
1242+
else:
12461243
if not (current := self.interaction_tree[scope].get(base)) or isinstance(current, SlashCommand):
12471244
self.interaction_tree[scope][base] = {}
12481245
if sub is None:
@@ -1754,9 +1751,7 @@ def get_ext(self, name: str) -> Extension | None:
17541751
Returns:
17551752
A extension, if found
17561753
"""
1757-
if ext := self.get_extensions(name):
1758-
return ext[0]
1759-
return None
1754+
return ext[0] if (ext := self.get_extensions(name)) else None
17601755

17611756
def __load_module(self, module, module_name, **load_kwargs) -> None:
17621757
"""Internal method that handles loading a module."""

interactions/client/const.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -121,10 +121,10 @@ def get_logger() -> logging.Logger:
121121
class Singleton(type):
122122
_instances = {}
123123

124-
def __call__(cls, *args, **kwargs) -> "Singleton":
125-
if cls not in cls._instances:
126-
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
127-
return cls._instances[cls]
124+
def __call__(self, *args, **kwargs) -> "Singleton":
125+
if self not in self._instances:
126+
self._instances[self] = super(Singleton, self).__call__(*args, **kwargs)
127+
return self._instances[self]
128128

129129

130130
class Sentinel(metaclass=Singleton):

interactions/client/smart_cache.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -553,9 +553,7 @@ def get_dm_channel(self, user_id: Optional["Snowflake_Type"]) -> Optional["DM"]:
553553
"""
554554
user_id = to_optional_snowflake(user_id)
555555
channel_id = self.dm_channels.get(user_id)
556-
if channel_id is None:
557-
return None
558-
return self.get_channel(channel_id)
556+
return None if channel_id is None else self.get_channel(channel_id)
559557

560558
def delete_channel(self, channel_id: "Snowflake_Type") -> None:
561559
"""

interactions/client/utils/attr_converters.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,7 @@ def optional(converter: typing.Callable) -> typing.Any:
5555
"""
5656

5757
def optional_converter(val) -> typing.Any:
58-
if val is None or val is MISSING:
59-
return val
60-
return converter(val)
58+
return val if val is None or val is MISSING else converter(val)
6159

6260
sig = None
6361
try:

interactions/client/utils/cache.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,9 +152,7 @@ class _CacheItemsView(ItemsView):
152152
def __contains__(self, item) -> bool:
153153
key, value = item
154154
v = self._mapping.get(key, default=attrs.NOTHING, reset_expiration=False)
155-
if v is attrs.NOTHING:
156-
return False
157-
return v is value or v == value
155+
return False if v is attrs.NOTHING else v is value or v == value
158156

159157
def __iter__(self) -> Iterator[Tuple[Any, Any]]:
160158
for key in self._mapping:

interactions/client/utils/serializer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,6 @@ def get_file_mimetype(file_data: bytes) -> str:
179179
return "image/png"
180180
if file_data.startswith(b"\xff\xd8\xff"):
181181
return "image/jpeg"
182-
if file_data[0:4] == b"RIFF" and file_data[8:12] == b"WEBP":
182+
if file_data[:4] == b"RIFF" and file_data[8:12] == b"WEBP":
183183
return "image/webp"
184184
return "application/octet-stream"

interactions/ext/debug_extension/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ async def debug_info(self, ctx: InteractionContext) -> None:
7070

7171
e.add_field("Start Time", f"{uptime.format(TimestampStyles.RelativeTime)}")
7272

73-
privileged_intents = [i.name for i in self.bot.intents if i in Intents.PRIVILEGED]
74-
if privileged_intents:
73+
if privileged_intents := [i.name for i in self.bot.intents if i in Intents.PRIVILEGED]:
7574
e.add_field("Privileged Intents", " | ".join(privileged_intents))
7675

7776
e.add_field("Loaded Exts", ", ".join(self.bot.ext))

interactions/ext/debug_extension/debug_application_cmd.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,13 @@ async def app_cmd(self, ctx: InteractionContext) -> None:
4141
await ctx.defer()
4242
e = debug_embed("Application-Commands Cache")
4343

44-
cmds = 0
45-
for v in self.bot.interactions.values():
46-
cmds += len(v.keys())
47-
44+
cmds = sum(len(v.keys()) for v in self.bot.interactions.values())
4845
e.add_field("Local application cmds (incld. Subcommands)", str(cmds))
4946
e.add_field("Component callbacks", str(len(self.bot._component_callbacks)))
5047
e.add_field("Prefixed commands", str(len(self.bot.prefixed_commands)))
5148
e.add_field(
5249
"Tracked Scopes",
53-
str(len(Counter(scope for scope in self.bot._interaction_scopes.values()).keys())),
50+
str(len(Counter(iter(self.bot._interaction_scopes.values())).keys())),
5451
)
5552

5653
await ctx.send(embeds=[e])

interactions/ext/debug_extension/debug_exec.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ async def handle_exec_result(self, ctx: ModalContext, result: Any, value: Any, b
120120

121121
if hasattr(result, "__iter__"):
122122
l_result = list(result)
123-
if all([isinstance(r, Embed) for r in result]):
123+
if all(isinstance(r, Embed) for r in result):
124124
paginator = Paginator.create_from_embeds(self.bot, *l_result)
125125
return await paginator.send(ctx)
126126

interactions/ext/debug_extension/utils.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,7 @@ def strf_delta(time_delta: datetime.timedelta, show_seconds: bool = True) -> str
7979
return f"{days_fmt} and {hours_fmt}"
8080
if hours >= 1:
8181
return f"{hours_fmt} and {minutes_fmt}"
82-
if show_seconds:
83-
return f"{minutes_fmt} and {seconds_fmt}"
84-
return f"{minutes_fmt}"
82+
return f"{minutes_fmt} and {seconds_fmt}" if show_seconds else f"{minutes_fmt}"
8583

8684

8785
def _make_solid_line(
@@ -166,7 +164,6 @@ def make_table(rows: list[list[Any]], labels: Optional[list[Any]] = None, center
166164
if labels is not None:
167165
lines.append(_make_data_line(column_widths, labels, data_left, data_middle, data_right, align))
168166
lines.append(_make_solid_line(column_widths, "├", "┼", "┤"))
169-
for row in rows:
170-
lines.append(_make_data_line(column_widths, row, data_left, data_middle, data_right, align))
167+
lines.extend(_make_data_line(column_widths, row, data_left, data_middle, data_right, align) for row in rows)
171168
lines.append(_make_solid_line(column_widths, "╰", "┴", "╯"))
172169
return "\n".join(lines)

0 commit comments

Comments
 (0)