Skip to content

Commit 46d73f0

Browse files
Mute HTTP logging unless warning or higher (#71)
* update pyproject for new ruff config and no-package setting * update deps * ruff updates * ignore ruff in blame * update action to use newest 1st party ruff action * enable preview rules * update ruff dep * update latest ruff ruling * add ruff related commits to blame * mute logging info on http requests
1 parent fc313aa commit 46d73f0

26 files changed

+1157
-794
lines changed

.git-blame-ignore-revs

+4
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,6 @@
11
# run ruff
22
174ab9e3d7bc643805ac97acf71a225dd9523977
3+
4+
# update ruff config
5+
e359280f0eb1ddcde18f35c21dedb429b6e0f28d
6+
48e8c3d2ea7d88ac9049d9be53086a9e77926686

.github/workflows/coverage_and_lint.yml

+1-2
Original file line numberDiff line numberDiff line change
@@ -71,5 +71,4 @@ jobs:
7171
no-comments: ${{ matrix.python-version != '3.x' }}
7272

7373
- name: Lint
74-
if: ${{ always() && steps.install-deps.outcome == 'success' }}
75-
uses: chartboost/ruff-action@v1
74+
uses: astral-sh/ruff-action@v3

constants/_meta.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,12 @@ def __new__(mcs, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> t
5151
return super().__new__(mcs, name, bases, attrs)
5252

5353
def __setattr__(self, attr: str, nv: Any) -> NoReturn:
54-
raise RuntimeError(f"Constant <{attr}> cannot be assigned to.")
54+
msg = f"Constant <{attr}> cannot be assigned to."
55+
raise RuntimeError(msg)
5556

5657
def __delattr__(self, attr: str) -> NoReturn:
57-
raise RuntimeError(f"Constant <{attr}> cannot be deleted.")
58+
msg = f"Constant <{attr}> cannot be deleted."
59+
raise RuntimeError(msg)
5860

5961

6062
class CONSTANTS(metaclass=ConstantsMeta):

constants/constants.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@
2424
from ._meta import CONSTANTS
2525

2626
__all__ = (
27-
"Roles",
28-
"Colours",
2927
"Channels",
28+
"Colours",
3029
"ForumTags",
30+
"Roles",
3131
)
3232

3333

core/bot.py

+17-14
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
import aiohttp
4848
import asyncpg
4949
import mystbin
50-
from discord.ext.commands.cog import Cog # type: ignore # stubs
50+
from discord.ext.commands.cog import Cog # pyright: ignore[reportMissingTypeStubs] # stubs
5151

5252
from .utils import LogHandler
5353

@@ -60,12 +60,12 @@ class Bot(commands.Bot):
6060
logging_queue: Queue[LogRecord]
6161

6262
__slots__ = (
63-
"session",
64-
"pool",
63+
"_previous_websocket_events",
6564
"log_handler",
66-
"mb_client",
6765
"logging_queue",
68-
"_previous_websocket_events",
66+
"mb_client",
67+
"pool",
68+
"session",
6969
)
7070

7171
def __init__(self) -> None:
@@ -77,11 +77,15 @@ def __init__(self) -> None:
7777
self._previous_websocket_events: deque[Any] = deque(maxlen=10)
7878

7979
async def get_context(
80-
self, message: discord.Message | discord.Interaction, /, *, cls: type[commands.Context[commands.Bot]] | None = None
80+
self,
81+
message: discord.Message | discord.Interaction,
82+
/,
83+
*,
84+
cls: type[commands.Context[commands.Bot]] | None = None,
8185
) -> Context:
8286
return await super().get_context(message, cls=Context)
8387

84-
async def add_cog(self, cog: Cog, /, *, override: bool = False) -> None: # type: ignore
88+
async def add_cog(self, cog: Cog, /, *, override: bool = False) -> None: # pyright: ignore[reportIncompatibleMethodOverride] # weird narrowing on Context generic
8589
# we patch this since we're a single guild bot.
8690
# it allows for guild syncing only.
8791
return await super().add_cog(cog, override=override, guild=discord.Object(id=GUILD_ID))
@@ -111,13 +115,12 @@ async def on_error(self, event_name: str, /, *args: Any, **kwargs: Any) -> None:
111115

112116
args_str = ["```py"]
113117
for index, arg in enumerate(args):
114-
args_str.append(f"[{index}]: {arg!r}")
115-
args_str.append("```")
118+
args_str.extend((f"[{index}]: {arg!r}", "```"))
116119
embed.add_field(name="Args", value="\n".join(args_str), inline=False)
117120

118121
self.log_handler.error("Event Error", extra={"embed": embed})
119122

120-
async def on_command_error(self, ctx: Context, error: commands.CommandError) -> None: # type: ignore # weird narrowing
123+
async def on_command_error(self, ctx: Context, error: commands.CommandError) -> None: # pyright: ignore[reportIncompatibleMethodOverride] # weird narrowing on Context generic
121124
assert ctx.command # wouldn't be here otherwise
122125

123126
if not isinstance(error, (commands.CommandInvokeError, commands.ConversionError)):
@@ -158,7 +161,7 @@ async def get_or_fetch_user(
158161
try:
159162
user = await guild.fetch_member(target_id)
160163
except discord.HTTPException:
161-
return
164+
return None
162165

163166
if cache:
164167
cache[target_id] = user
@@ -169,7 +172,7 @@ async def get_or_fetch_user(
169172
try:
170173
user = await self.fetch_user(target_id)
171174
except discord.HTTPException:
172-
return
175+
return None
173176

174177
if cache:
175178
cache[target_id] = user
@@ -182,11 +185,11 @@ async def start(self, token: str, *, reconnect: bool = True) -> None:
182185
finally:
183186
path = pathlib.Path("logs/prev_events.log")
184187

185-
with path.open("w+", encoding="utf-8") as f:
188+
with path.open("w+", encoding="utf-8") as f: # noqa: ASYNC230 # this is okay as we're in cleanup phase
186189
for event in self._previous_websocket_events:
187190
try:
188191
last_log = json.dumps(event, ensure_ascii=True, indent=2)
189-
except Exception:
192+
except (ValueError, TypeError):
190193
f.write(f"{event}\n")
191194
else:
192195
f.write(f"{last_log}\n")

core/checks.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
import constants
3131

3232
if TYPE_CHECKING:
33-
from discord.ext.commands._types import Check # type: ignore # why would this need stubs
33+
from discord.ext.commands._types import Check # pyright: ignore[reportMissingTypeStubs] # why would this need stubs
3434

3535
from core.context import GuildContext
3636

@@ -42,7 +42,8 @@ def predicate(ctx: GuildContext) -> bool:
4242
# This should never be a problem, but just in case...
4343
if not role:
4444
# TODO: Change this to a custom exception.
45-
raise commands.CheckFailure(f"Role with ID <{role_id}> does not exist.")
45+
msg = f"Role with ID <{role_id}> does not exist."
46+
raise commands.CheckFailure(msg)
4647

4748
ignored = (constants.Roles.NITRO_BOOSTER, constants.Roles.MUTED)
4849
roles = [r for r in ctx.author.roles if r.id not in ignored and ctx.author.top_role >= r]
@@ -51,6 +52,7 @@ def predicate(ctx: GuildContext) -> bool:
5152
return True
5253

5354
# TODO: Change this to a custom exception.
54-
raise commands.CheckFailure(f"{ctx.author} is not in or higher than role <{role.name}(ID: {role.id})>.")
55+
msg = f"{ctx.author} is not in or higher than role <{role.name}(ID: {role.id})>."
56+
raise commands.CheckFailure(msg)
5557

5658
return commands.check(predicate)

core/context.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -30,35 +30,32 @@ def replied_reference(self) -> discord.MessageReference | discord.Message:
3030
return self.message
3131

3232
@discord.utils.cached_property
33-
def replied_message(self) -> discord.Message | discord.Message:
33+
def replied_message(self) -> discord.Message:
3434
ref = self.message.reference
3535
if ref and isinstance(ref.resolved, discord.Message):
3636
return ref.resolved
3737
return self.message
3838

3939
def author_is_mod(self) -> bool:
40-
member: discord.Member
40+
member: discord.Member | None
4141

4242
if self.guild is None: # dms
4343
guild = self.bot.get_guild(GUILD_ID)
4444

4545
if not guild:
4646
return False
4747

48-
_member = guild.get_member(self.author.id)
49-
if _member is not None:
50-
member = _member
51-
52-
else:
48+
member = guild.get_member(self.author.id)
49+
if member is None:
5350
return False
5451

5552
else:
56-
member = self.author # type: ignore
53+
member = self.author # pyright: ignore[reportAssignmentType] # type lie for a shortcut
5754

58-
roles = member._roles # type: ignore # we know this won't change for a while
55+
roles = member._roles # pyright: ignore[reportPrivateUsage,reportOptionalMemberAccess] # we know this won't change for a while
5956
return roles.has(Roles.ADMIN) or roles.has(Roles.MODERATOR)
6057

6158

6259
class GuildContext(Context):
63-
guild: discord.Guild # type: ignore # type lie due to narrowing
64-
author: discord.Member # type: ignore # type lie due to narrowing
60+
guild: discord.Guild # pyright: ignore[reportIncompatibleVariableOverride] # type lie due to narrowing
61+
author: discord.Member # pyright: ignore[reportIncompatibleVariableOverride] # type lie due to narrowing

core/converters.py

+3-7
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class CodeblockConverter(commands.Converter[Codeblock]):
4343
:attr:`Codeblock.language` will be ``None`` if the input was not a complete codeblock.
4444
"""
4545

46-
async def convert(self, ctx: Context, argument: str) -> Codeblock: # type: ignore # this is something to do with the typevar
46+
async def convert(self, ctx: Context, argument: str) -> Codeblock: # pyright: ignore[reportIncompatibleMethodOverride] # generic narrowing on Context
4747
if not argument.startswith("`"):
4848
return Codeblock(None, argument)
4949

@@ -58,12 +58,8 @@ async def convert(self, ctx: Context, argument: str) -> Codeblock: # type: igno
5858
for character in argument:
5959
if character == "`" and not within_code and not within_language:
6060
backticks += 1
61-
if (
62-
previous_characters
63-
and previous_characters[-1] == "`"
64-
and character != "`"
65-
or within_code
66-
and "".join(previous_characters) != "`" * backticks
61+
if (previous_characters and previous_characters[-1] == "`" and character != "`") or (
62+
within_code and "".join(previous_characters) != "`" * backticks
6763
):
6864
within_code = True
6965
code.append(character)

core/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
)
3939

4040

41-
CONFIG: Config = toml.load("config.toml") # type: ignore # weird non-assertion
41+
CONFIG: Config = toml.load("config.toml") # pyright: ignore[reportAssignmentType] # weirdly narrow library type
4242

4343

4444
class Cog(commands.Cog):

core/utils/formatters.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,15 @@
2727
from discord.utils import escape_markdown
2828

2929
__all__ = (
30-
"to_codeblock",
3130
"random_pastel_colour",
31+
"to_codeblock",
3232
)
3333

3434

3535
def to_codeblock(
3636
content: str,
3737
language: str = "py",
38+
*,
3839
replace_existing: bool = True,
3940
escape_md: bool = True,
4041
new: str = "'''",
@@ -50,4 +51,4 @@ def to_codeblock(
5051

5152

5253
def random_pastel_colour() -> Colour:
53-
return Colour.from_hsv(random.random(), 0.28, 0.97)
54+
return Colour.from_hsv(random.random(), 0.28, 0.97) # noqa: S311 # not for crypto usage

core/utils/logging.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
from __future__ import annotations
1+
from __future__ import annotations # noqa: A005 # we access this as a namespace
22

33
import logging
44
import pathlib
55
from logging.handlers import RotatingFileHandler
6-
from typing import TYPE_CHECKING, Any
6+
from typing import TYPE_CHECKING
77

8-
from discord.utils import _ColourFormatter as ColourFormatter, stream_supports_colour # type: ignore # shh, I need it
8+
from discord.utils import (
9+
_ColourFormatter as ColourFormatter, # pyright: ignore[reportPrivateUsage] # shh, I need it # noqa: PLC2701
10+
stream_supports_colour,
11+
)
912

1013
import core
1114

@@ -46,6 +49,7 @@ def __enter__(self: Self) -> Self:
4649
logging.getLogger("discord.http").setLevel(logging.INFO)
4750
logging.getLogger("discord.state").setLevel(logging.WARNING)
4851
logging.getLogger("discord.gateway").setLevel(logging.WARNING)
52+
logging.getLogger("starlette_plus.core").setLevel(logging.WARNING)
4953

5054
self.log.setLevel(logging.INFO)
5155
handler = RotatingFileHandler(
@@ -70,10 +74,10 @@ def __enter__(self: Self) -> Self:
7074

7175
return self
7276

73-
async def __aexit__(self, *args: Any) -> None:
77+
async def __aexit__(self, *args: object) -> None:
7478
return self.__exit__(*args)
7579

76-
def __exit__(self, *args: Any) -> None:
80+
def __exit__(self, *args: object) -> None:
7781
handlers = self.log.handlers[:]
7882
for hdlr in handlers:
7983
hdlr.close()

0 commit comments

Comments
 (0)