Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ The format follows [Keep a Changelog](https://keepachangelog.com/).
- A lost database connection is retried on the same pool. Before, each
failure opened another pool of ten connections.

### Security

- Reports about a failed command, button or form no longer show where the
bot's files are on the server.

## 1.0.2 - 2026-11-29

### Changed
Expand Down
33 changes: 28 additions & 5 deletions core/ui/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
_FENCE = "```"
# The innermost calls, where the error happened.
_CALLS = 8
_ROOT = Path(__file__).resolve().parents[2]


def print_error(heading: str, error: BaseException) -> None:
Expand All @@ -34,6 +35,29 @@ def print_error(heading: str, error: BaseException) -> None:
traceback.print_exception(error, file=sys.stderr)


def place(filename: str) -> str:
"""
Name a source file without the folders of the server.

Parameters
----------
filename : str
The path of the file.

Returns
-------
str
The path inside a library or the bot, otherwise its last two parts.
"""
path = Path(filename)
parts = path.parts
if "site-packages" in parts:
return "/".join(parts[parts.index("site-packages") + 1 :])
if path.is_relative_to(_ROOT):
return path.relative_to(_ROOT).as_posix()
return "/".join(parts[-2:])


def _cause(error: BaseException) -> str:
"""
Name an error and the calls that led to it, without its message.
Expand All @@ -44,9 +68,10 @@ def _cause(error: BaseException) -> str:
if isinstance(error, app_commands.CommandInvokeError):
error = error.original
lines = [f"{type(error).__qualname__} (the message is in the console)"]
for call in traceback.extract_tb(error.__traceback__)[-_CALLS:]:
where = "/".join(Path(call.filename).parts[-3:])
lines.append(f"{where}:{call.lineno} in {call.name}")
lines.extend(
f"{place(call.filename)}:{call.lineno} in {call.name}"
for call in traceback.extract_tb(error.__traceback__)[-_CALLS:]
)
return "\n".join(lines)


Expand Down Expand Up @@ -77,12 +102,10 @@ async def send_report(
if not isinstance(channel, discord.abc.Messageable):
_logger.warning("LOG_CHANNEL takes no messages: %s", title)
return
trace = error.__traceback__
text = (
f"{context}\nError caused by-\nAuthor Name: {interaction.user}"
f"\nAuthor ID: {interaction.user.id}\n"
f"\nError Type-\n{type(error)}\n"
f"\nError Type Description-\n{trace.tb_frame if trace else None}\n"
f"\nCause-\n{_cause(error)}"
)
title = title[:_TITLE_LIMIT]
Expand Down
33 changes: 32 additions & 1 deletion tests/test_error_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""What users and the log channel are told when a command fails."""

import logging
from pathlib import Path
from unittest.mock import MagicMock

import discord
Expand All @@ -10,8 +11,10 @@
from core import Bot
from core.config import LOG_CHANNEL
from core.extensions.error_handler import ErrorHandler
from core.ui import reports
from tests.ui_helpers import PRESSER, interaction, report, shown

ROOT = Path(__file__).resolve().parent.parent
TOKEN = "MTAx.not-a-real-token" # noqa: S105 (not a real token)
PRIVATE = f"password=hunter2 {TOKEN} the user wrote: my address is here"
APOLOGY = (
Expand Down Expand Up @@ -129,7 +132,6 @@ async def test_the_report_says_who_what_and_where() -> None:
"Author Name: someone",
f"Author ID: {PRESSER}",
"<class 'discord.app_commands.errors.CommandInvokeError'>",
"Error Type Description-\n<frame ",
"ValueError",
"test_error_handler.py",
"in _raise",
Expand All @@ -156,6 +158,35 @@ async def test_the_report_never_repeats_what_the_error_said(
assert private not in text


async def test_the_report_names_no_folder_of_the_server() -> None:
command = _command("modmail", "close")
item = interaction()
item.command = command

await _handler().on_error(item, _invoke_error(command))

text = report(item)
for folder in (str(ROOT), ROOT.as_posix(), ROOT.parent.name, "<frame "):
assert folder not in text
assert "tests/test_error_handler.py:" in text


@pytest.mark.parametrize(
("filename", "shown"),
[
(
"/home/c/.local/lib/python3.12/site-packages/discord/ui/view.py",
"discord/ui/view.py",
),
("/usr/local/lib/python3.12/asyncio/tasks.py", "asyncio/tasks.py"),
],
)
def test_a_library_is_named_without_its_folder(
filename: str, shown: str
) -> None:
assert reports.place(filename) == shown


async def test_a_long_traceback_still_fits() -> None:
def deeper(left: int) -> None:
if left:
Expand Down