Skip to content

Commit 7c81b2f

Browse files
committed
😡Ruff it up x4
1 parent 5a23cc2 commit 7c81b2f

File tree

7 files changed

+52
-20
lines changed

7 files changed

+52
-20
lines changed

ext/custom_commands.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ async def event_message(self, message: twitchio.ChatMessage) -> None:
7777
@commands.is_moderator()
7878
@commands.group(invoke_fallback=True)
7979
async def cmd(self, ctx: commands.Context) -> None:
80-
"""Group command to define cmd"""
80+
"""Group command to define cmd."""
8181
await ctx.send('You need to use this with subcommands, i.e. "cmd add/delete/edit/list"')
8282

8383
@commands.is_moderator()
@@ -93,7 +93,7 @@ async def add(self, ctx: commands.Context, cmd_name: str, *, text: str) -> None:
9393
await self.bot.pool.execute(query, ctx.broadcaster.id, cmd_name, text)
9494
except asyncpg.UniqueViolationError:
9595
msg = "There already exists a command with such name."
96-
raise errors.BadArgumentError(msg)
96+
raise errors.BadArgumentError(msg) from None
9797

9898
self.command_cache.setdefault(ctx.broadcaster.id, {})[cmd_name] = text
9999
await ctx.send(f"Added the command {cmd_name}.")
@@ -139,7 +139,7 @@ async def cmd_list(self, ctx: commands.Context) -> None:
139139
"""Get commands list."""
140140
cache_list = [f"!{name}" for v in self.command_cache.values() for name in v]
141141
# bot_cmds = [
142-
# f"!{v.full_name}" for v in self.bot.commands.values() if not v._checks and not isinstance(v, commands.Group)
142+
# f"!{v.full_name}" for v in self.bot.commands.values() if not v._checks and not isinstance(v, commands.Group)
143143
# ]
144144
await ctx.send(", ".join(cache_list))
145145

ext/dev.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,9 @@ async def maintenance(self, ctx: commands.Context) -> None:
3636
await ctx.send("Shutting down the bot in 3 2 1")
3737
await asyncio.sleep(3)
3838
try:
39-
# non systemctl users - sorry
40-
os.system("sudo systemctl stop luebot")
41-
except Exception as error:
42-
log.error(error, stack_info=True)
39+
await asyncio.create_subprocess_shell("sudo systemctl stop luebot") # `os.system`
40+
except Exception:
41+
log.exception("Failed to Stop the bot's process", stack_info=True)
4342
# it might not go off
4443
await ctx.send("Something went wrong.")
4544

ext/logs_via_webhook.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ async def send_log_record(self, record: logging.LogRecord) -> None:
9797

9898
emoji = attributes.get(record.levelname, "\N{WHITE QUESTION MARK ORNAMENT}")
9999
dt = datetime.datetime.fromtimestamp(record.created, datetime.UTC)
100-
msg = textwrap.shorten(f"{emoji} {discord.utils.format_dt(dt, style="T")} {record.message}", width=1995)
100+
msg = textwrap.shorten(f"{emoji} {discord.utils.format_dt(dt, style='T')} {record.message}", width=1995)
101101
avatar_url = self.AVATAR_MAPPING.get(record.name, discord.utils.MISSING)
102102
username = record.name.replace("discord", "disсοrd") # cSpell: ignore disсοrd # noqa: RUF003
103103
await self.bot.logger_webhook.send(msg, username=username, avatar_url=avatar_url)

ext/misc_commands.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,9 @@ async def erdoc(self, ctx: commands.Context) -> None:
2929
async def run(self, ctx: commands.Context) -> None:
3030
"""Explanation of my first Sekiro hitless run."""
3131
msg = (
32-
"All Memories & Unique MiniBosses (so no repetitions). "
32+
"All Memories & Unique MiniBosses (so no repetitions) & save-file for Inner+Shura. "
3333
"The idea: I have to learn and practice all boss move-sets. "
34-
"Even load Inner Father, Fire Isshin and Emma save-file. "
35-
"Almost Charmless (take it back pre-demon). Mostly Sword+Shuriken (~29/37 boss fights). "
34+
"Almost Charmless (take it back pre-demon). Mostly Sword+Shuriken (~31/39 boss fights). "
3635
"Somewhat loop-less. For more look !notes."
3736
)
3837
await ctx.send(msg)

pyproject.toml

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -105,21 +105,32 @@ select = [
105105
"DOC" # Doc strings, kinda annoying for a bot, to be honest
106106
]
107107
ignore = [
108+
# General disagreement with Ruff
108109
"ANN401", # `Any` is the correct type in some cases
109-
"ASYNC109", # dpy commonly uses this parameter
110+
"ASYNC109", # dpy and other libraries commonly use this parameter
110111
"ASYNC116", # Long sleeps are fine
111112
"C90", # mc cabe complexity memes
112113
"F401", # unused imports
113114
"F403", # wildcard imports: `from math import *` are used in __init__.py a lot
114-
"F405", # wildcard imports
115-
"INP001", # due to how I load modules this results in annoyances
115+
"F405", # wildcard imports are not that bad
116+
"INP001", # due to how we load modules this results in annoyances
116117
"PLC0415", # ruff gets this wrong, import needs to be not at top of file in some cases
118+
"RUF001", # ambiguous characters not something I want to enforce here.
119+
"S101", # use of assert here is a known quantity, blame typing memes
120+
"S311", # Yes, standard pseudo-random generators are not suitable for cryptographic purposes so what
121+
"TRY003", # over-eager rule
122+
"TRY301", # unrealistic rule
123+
124+
# Personal problems
125+
"PLR0904", # too many public methods
117126
"PLR0912", # too many branches
118127
"PLR0913", # number of function arguments
119128
"PLR0914", # too many variables: come on
120129
"PLR0915", # too many statements: come on, not everything is solvable in <50 lines.
130+
"PLR0917", # too many positional arguments
131+
"PLR2004", # Magic value comparison, may remove later
121132
"PLR6301", # discord.py uses `self` even if I don't
122-
"S101", # use of assert here is a known quantity, blame typing memes
133+
"S608", # I use f-strings with SQL and I don't know better;
123134

124135
# OLD RULES
125136
# "F401",
@@ -133,15 +144,16 @@ ignore = [
133144
# "UP038",
134145

135146
# DOC STRINGS
136-
# 1. General doc string exceptions
147+
# general doc string exceptions
137148
"D100", # Missing docstring in module: no, module level docs aren't always needed
138149
"D105", # Missing docstring in magic method: documenting magic methods is often dumb.
139150
"D107", # Missing docstring in `__init__`: __init__ is the wrong place to doc this.
140-
"D401", # Doc should be starting with an imperative verb: dumb rule, to be honest.
141-
# 2. Exceptions for this bot because it's pointless to document *everything* in one-man project.
151+
"D401", # Doc should be starting with an imperative verb: dumb rule tbh.
152+
# doc string exceptions
153+
# for this bot because it's a bot and it's pointless to document *everything* in one-man project.
142154
"DOC201", # `return` is not documented in docstring
143155
"DOC501", # raised exception is missing from docstring
144-
156+
145157
# "D104", # Missing docstring in public package. Otherwise spams __init__.py and such.
146158
# "D417", # Missing argument description. Otherwise, it keeps asking to document interaction/context args.
147159
# "D203", # one-blank-line-before-class

utils/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +0,0 @@
1-

utils/fuzzy.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66
https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/utils/fuzzy.py
77
* Helpful article:
88
http://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/
9+
10+
Notes
11+
-----
12+
* Unfortunately, Danny didn't make doc-strings for the functions in here so I mostly cross-checked with
13+
https://github.com/seatgeek/thefuzz concepts and ideas, which are kinda the same
14+
(but in my testing that library is slower than the code here, not sure why).
915
"""
1016

1117
from __future__ import annotations
@@ -33,6 +39,7 @@ def quick_ratio(a: str, b: str) -> int:
3339

3440

3541
def partial_ratio(a: str, b: str) -> int:
42+
"""Return the ratio of the most similar substring as a number between 0 and 100."""
3643
short, long = (a, b) if len(a) <= len(b) else (b, a)
3744
m = SequenceMatcher(None, short, long)
3845

@@ -61,6 +68,7 @@ def _sort_tokens(a: str) -> str:
6168

6269

6370
def token_sort_ratio(a: str, b: str) -> int:
71+
"""Return a measure of the sequences' similarity between 0 and 100 but sorting the token before comparing."""
6472
a = _sort_tokens(a)
6573
b = _sort_tokens(b)
6674
return ratio(a, b)
@@ -73,6 +81,10 @@ def quick_token_sort_ratio(a: str, b: str) -> int:
7381

7482

7583
def partial_token_sort_ratio(a: str, b: str) -> int:
84+
"""Return the ratio of the most similar substring as a number between 0 and 100.
85+
86+
But sorting the token before comparing.
87+
"""
7688
a = _sort_tokens(a)
7789
b = _sort_tokens(b)
7890
return partial_ratio(a, b)
@@ -144,6 +156,12 @@ def extract(
144156
score_cutoff: int = 0,
145157
limit: int | None = 10,
146158
) -> list[tuple[str, int]] | list[tuple[str, int, T]]:
159+
"""Select the best match in a list or dictionary of choices.
160+
161+
Find best matches in a list or dictionary of choices, return a
162+
list of tuples containing the match and its score. If a dictionary
163+
is used, also returns the key for each match.
164+
"""
147165
it = _extraction_generator(query, choices, scorer, score_cutoff)
148166
if limit is not None:
149167
return heapq.nlargest(limit, it, key=operator.itemgetter(1)) # pyright: ignore[reportReturnType]
@@ -177,6 +195,11 @@ def extract_one(
177195
scorer: Callable[[str, str], int] = quick_ratio,
178196
score_cutoff: int = 0,
179197
) -> tuple[str, int] | tuple[str, int, T] | None:
198+
"""Find the single best match above a score in a list of choices.
199+
200+
This is a convenience method which returns the single best choice.
201+
See extract() for the full arguments list.
202+
"""
180203
it = _extraction_generator(query, choices, scorer, score_cutoff)
181204
try:
182205
return max(it, key=operator.itemgetter(1))

0 commit comments

Comments
 (0)