refactor: remove redundant comments and docstrings (#6527)

* refactor: remove redundant comments and docstrings

* fix(signal): annotate async context manager as a generator
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-30 13:07:03 +08:00
1 parent cb3ba45317
commit a4d2430140
922 files changed
+406 -7738

No files matched your search

-1
View File
@@ -1 +0,0 @@
"""Discord channel package."""
-2
View File
@@ -1,5 +1,3 @@
"""Discord management contract."""
from nanobot.channels._manifest import DIRECT_GROUP_POLICIES, field, required
from nanobot.channels.contracts import ChannelSetupSpec
from nanobot.channels.discord.validation import validate
+2 -23
View File
@@ -1,4 +1,3 @@
"""Discord channel implementation using discord.py."""
# pyright: reportPrivateUsage=false, reportUnusedFunction=false
from __future__ import annotations
@@ -36,7 +35,7 @@ if DISCORD_AVAILABLE:
from discord import app_commands
from discord.abc import Messageable
MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB
MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
MAX_MESSAGE_LEN = 2000 # Discord message character limit
TYPING_INTERVAL_S = 8
@@ -110,7 +109,6 @@ if DISCORD_AVAILABLE:
self._channel._remember_channel(after)
async def _reply_ephemeral(self, interaction: discord.Interaction, text: str) -> bool:
"""Send an ephemeral interaction response and report success."""
try:
await interaction.response.send_message(text, ephemeral=True)
return True
@@ -323,7 +321,6 @@ if DISCORD_AVAILABLE:
)
async def _edit_compaction_notice(self, notice: discord.Message, content: str) -> bool:
"""Replace a start notice's text with the outcome; False when Discord refused."""
if not content:
return False
try:
@@ -341,7 +338,6 @@ if DISCORD_AVAILABLE:
reference: discord.MessageReference | None,
mention_settings: discord.AllowedMentions,
) -> bool:
"""Send a file attachment via discord.py."""
path = Path(file_path)
if not path.is_file():
self._channel.logger.warning("file not found, skipping: {}", file_path)
@@ -415,7 +411,6 @@ class DiscordChannel(BaseChannel):
*,
explicit: str | None = None,
) -> str | None:
"""Choose an explicit reply target, or the triggering message when enabled."""
if explicit:
return explicit
if not self.config.reply_to_message or not metadata:
@@ -430,7 +425,6 @@ class DiscordChannel(BaseChannel):
*,
fail_if_not_exists: bool,
) -> tuple[discord.MessageReference | None, discord.AllowedMentions]:
"""Build a native Discord reply without pinging the replied-to user."""
mention_settings = discord.AllowedMentions(replied_user=False)
if not reply_to:
return None, mention_settings
@@ -454,7 +448,7 @@ class DiscordChannel(BaseChannel):
self._client: DiscordBotClient | None = None
self._typing_tasks: dict[str, asyncio.Task[None]] = {}
self._bot_user_id: str | None = None
self._pending_reactions: dict[str, Any] = {} # chat_id -> message object
self._pending_reactions: dict[str, Any] = {}
self._compaction_notices: dict[tuple[str, str], discord.Message] = {}
self._working_emoji_tasks: dict[str, set[asyncio.Task[None]]] = {}
self._inbound_tasks: set[asyncio.Task[Any]] = set()
@@ -516,7 +510,6 @@ class DiscordChannel(BaseChannel):
compaction_id: str,
message: discord.Message,
) -> None:
"""Keep a start notice until its matching outcome consumes it."""
self._compaction_notices[(chat_id, compaction_id)] = message
async def send(self, msg: OutboundMessage) -> None:
@@ -616,7 +609,6 @@ class DiscordChannel(BaseChannel):
raise
async def _handle_discord_message(self, message: discord.Message) -> None:
"""Own in-flight callbacks until they finish or runtime reset drains them."""
task = asyncio.current_task()
if task is not None:
self._inbound_tasks.add(task)
@@ -661,7 +653,6 @@ class DiscordChannel(BaseChannel):
await self._start_typing(message.channel)
# Add read receipt reaction immediately, working emoji after delay
try:
await message.add_reaction(self.config.read_receipt_emoji)
self._pending_reactions[channel_id] = message
@@ -706,7 +697,6 @@ class DiscordChannel(BaseChannel):
await self._handle_discord_message(message)
async def _resolve_channel(self, chat_id: str) -> Any | None:
"""Resolve a Discord channel from cache first, then network fetch."""
client = self._client
if client is None or not client.is_ready():
return None
@@ -729,7 +719,6 @@ class DiscordChannel(BaseChannel):
buf: _StreamBuf,
message: discord.Message,
) -> None:
"""Commit the final streamed content and flush overflow chunks."""
chunks = DiscordBotClient._build_chunks(buf.text, [], False)
if not chunks:
self._stream_bufs.pop(chat_id, None)
@@ -756,12 +745,10 @@ class DiscordChannel(BaseChannel):
sender_id: str,
content: str,
) -> bool:
"""Check if inbound Discord message should be processed."""
# Reject unauthorized guild messages before any side effects, but let DMs
# reach BaseChannel._handle_message so it can issue a pairing code.
if message.guild is not None and not self.is_allowed(sender_id):
return False
# Channel-based filtering: only respond in allowed channels
allow_channels = self.config.allow_channels
if allow_channels:
channel_ids = self._channel_allow_keys(message.channel)
@@ -775,7 +762,6 @@ class DiscordChannel(BaseChannel):
self,
attachments: list[discord.Attachment],
) -> tuple[list[str], list[str]]:
"""Download supported attachments and return paths + display markers."""
media_paths: list[str] = []
markers: list[str] = []
media_dir = get_media_dir("discord")
@@ -826,7 +812,6 @@ class DiscordChannel(BaseChannel):
}
def _should_respond_in_group(self, message: discord.Message, content: str) -> bool:
"""Check if the bot should respond in a guild channel based on policy."""
if self.config.group_policy == "open":
return True
@@ -867,7 +852,6 @@ class DiscordChannel(BaseChannel):
return str(getattr(author, "id", "")) == bot_user_id
async def _start_typing(self, channel: Messageable) -> None:
"""Start periodic typing indicator for a channel."""
channel_id = self._channel_key(channel)
await self._stop_typing(channel_id)
@@ -885,7 +869,6 @@ class DiscordChannel(BaseChannel):
self._typing_tasks[channel_id] = asyncio.create_task(typing_loop())
async def _stop_typing(self, channel_id: str) -> None:
"""Stop typing indicator for a channel."""
task = self._typing_tasks.pop(self._channel_key(channel_id), None)
if task is None:
return
@@ -894,7 +877,6 @@ class DiscordChannel(BaseChannel):
await task
async def _clear_reactions(self, chat_id: str) -> None:
"""Remove all pending reactions after bot replies."""
# Keep tasks owned until done, so a concurrent reset can drain them too.
tasks = tuple(self._working_emoji_tasks.get(chat_id, ()))
# Snapshot before yielding; a newer receipt must survive this cleanup.
@@ -912,13 +894,11 @@ class DiscordChannel(BaseChannel):
await msg_obj.remove_reaction(emoji, bot_user)
async def _cancel_all_typing(self) -> None:
"""Stop all typing tasks."""
channel_ids = list(self._typing_tasks)
for channel_id in channel_ids:
await self._stop_typing(channel_id)
async def _cancel_all_reactions(self) -> None:
"""Stop delayed reactions and release their retained messages."""
tasks = tuple(task for group in self._working_emoji_tasks.values() for task in group)
self._pending_reactions.clear()
for task in tasks:
@@ -928,7 +908,6 @@ class DiscordChannel(BaseChannel):
self._working_emoji_tasks.clear()
async def _reset_runtime_state(self, close_client: bool) -> None:
"""Reset client and transient runtime state."""
self._running = False
# Drain callbacks before clearing the state they can still create after an await.
current = asyncio.current_task()
@@ -1 +0,0 @@
"""Tests for the Discord channel package."""
@@ -25,7 +25,6 @@ from nanobot.command.builtin import build_help_text
from nanobot.config.network import NetworkConfig
# Minimal Discord client test double used to control startup/readiness behavior.
class _FakeDiscordClient:
instances: list["_FakeDiscordClient"] = []
start_error: Exception | None = None
@@ -66,7 +65,6 @@ class _FakeDiscordClient:
class _FakeAttachment:
# Attachment double that can simulate successful or failing save() calls.
def __init__(
self, attachment_id: int, filename: str, *, size: int = 1, fail: bool = False
) -> None:
@@ -82,7 +80,6 @@ class _FakeAttachment:
class _FakePartialMessage:
# Lightweight stand-in for Discord partial message references used in replies.
def __init__(self, message_id: int, channel_id: int) -> None:
self.id = message_id
self.channel_id = channel_id
@@ -96,7 +93,6 @@ class _FakePartialMessage:
class _FakeSentMessage:
# Sent-message double supporting edit() for streaming tests.
def __init__(self, channel, content: str) -> None:
self.channel = channel
self.content = content
@@ -109,7 +105,6 @@ class _FakeSentMessage:
class _FakeChannel:
# Channel double that records outbound payloads and typing activity.
def __init__(
self,
channel_id: int = 123,
@@ -194,7 +189,6 @@ def _make_message(
reply_author_id: int | None = None,
message_type=None,
):
# Factory for incoming Discord message objects with optional guild/reply/attachments.
guild = SimpleNamespace(id=guild_id) if guild_id is not None else None
referenced_message = (
SimpleNamespace(author=SimpleNamespace(id=reply_author_id))
@@ -222,7 +216,6 @@ def _make_message(
@pytest.mark.asyncio
async def test_start_returns_when_token_missing() -> None:
# If no token is configured, startup should no-op and leave channel stopped.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
await channel.start()
@@ -247,7 +240,6 @@ async def test_start_returns_when_discord_dependency_missing(monkeypatch) -> Non
@pytest.mark.asyncio
async def test_start_handles_client_construction_failure(monkeypatch) -> None:
# Construction errors from the Discord client should be swallowed and keep state clean.
channel = DiscordChannel(
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
MessageBus(),
@@ -266,7 +258,6 @@ async def test_start_handles_client_construction_failure(monkeypatch) -> None:
@pytest.mark.asyncio
async def test_start_handles_client_start_failure(monkeypatch) -> None:
# If client.start fails, the partially created client should be closed and detached.
channel = DiscordChannel(
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
MessageBus(),
@@ -288,7 +279,6 @@ async def test_start_handles_client_start_failure(monkeypatch) -> None:
@pytest.mark.asyncio
async def test_stop_is_safe_after_partial_start(monkeypatch) -> None:
# stop() should close/discard the client even when startup was only partially completed.
channel = DiscordChannel(
DiscordConfig(enabled=True, token="token", allow_from=["*"]),
MessageBus(),
@@ -383,7 +373,6 @@ async def test_stop_drains_inflight_message_before_reaction_cleanup(blocked_stag
assert not channel._working_emoji_tasks
assert not channel._pending_reactions
channel._handle_message.assert_not_awaited()
# A queued event from the closed client must not run, even after a new runtime starts.
channel._client = DiscordBotClient(channel, intents=discord.Intents.default())
channel._running = True
await client.on_message(_make_message())
@@ -554,7 +543,7 @@ async def test_stop_waits_for_reaction_already_draining(monkeypatch, cleanup_kin
async def test_on_message_ignores_self_messages() -> None:
# Self-loop guard: messages from this bot's own account must be dropped (#3217).
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
channel._bot_user_id = "999" # simulate bot identity populated in on_ready()
channel._bot_user_id = "999"
handled: list[dict] = []
channel._handle_message = lambda **kwargs: handled.append(kwargs) # type: ignore[method-assign]
@@ -583,7 +572,6 @@ async def test_on_message_accepts_messages_from_other_bots() -> None:
@pytest.mark.asyncio
async def test_on_message_stops_typing_on_handle_exception() -> None:
# If inbound handling raises, typing should be stopped for that channel.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
async def fail_handle(**kwargs) -> None:
@@ -599,7 +587,6 @@ async def test_on_message_stops_typing_on_handle_exception() -> None:
@pytest.mark.asyncio
async def test_on_message_accepts_allowlisted_dm() -> None:
# Allowed direct messages should be forwarded with normalized metadata.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["123"]), MessageBus())
handled: list[dict] = []
@@ -637,7 +624,6 @@ async def test_on_message_unauthorized_dm_sends_pairing_code(monkeypatch) -> Non
@pytest.mark.asyncio
async def test_on_message_accepts_when_channel_in_allow_channels() -> None:
# When allow_channels is set, messages from listed channels should be forwarded.
channel = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], allow_channels=["456"]),
MessageBus(),
@@ -798,7 +784,6 @@ async def test_on_message_drops_thread_when_neither_thread_nor_parent_allowed()
@pytest.mark.asyncio
async def test_on_message_drops_when_channel_not_in_allow_channels() -> None:
# When allow_channels is set and incoming channel is not listed, drop silently.
channel = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], allow_channels=["999"]),
MessageBus(),
@@ -817,7 +802,6 @@ async def test_on_message_drops_when_channel_not_in_allow_channels() -> None:
@pytest.mark.asyncio
async def test_on_message_ignores_unmentioned_guild_message() -> None:
# With mention-only group policy, guild messages without a bot mention are dropped.
channel = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], group_policy="mention"),
MessageBus(),
@@ -837,7 +821,6 @@ async def test_on_message_ignores_unmentioned_guild_message() -> None:
@pytest.mark.asyncio
async def test_on_message_accepts_mentioned_guild_message() -> None:
# Mentioned guild messages should be accepted and preserve reply threading metadata.
channel = DiscordChannel(
DiscordConfig(enabled=True, allow_from=["*"], group_policy="mention"),
MessageBus(),
@@ -865,7 +848,6 @@ async def test_on_message_accepts_mentioned_guild_message() -> None:
@pytest.mark.asyncio
async def test_on_message_downloads_attachments(tmp_path, monkeypatch) -> None:
# Attachment downloads should be saved and referenced in forwarded content/media.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
handled: list[dict] = []
@@ -889,7 +871,6 @@ async def test_on_message_downloads_attachments(tmp_path, monkeypatch) -> None:
@pytest.mark.asyncio
async def test_on_message_marks_failed_attachment_download(tmp_path, monkeypatch) -> None:
# Failed attachment downloads should emit a readable placeholder and no media path.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
handled: list[dict] = []
@@ -913,7 +894,6 @@ async def test_on_message_marks_failed_attachment_download(tmp_path, monkeypatch
@pytest.mark.asyncio
async def test_send_raises_when_client_not_ready() -> None:
# The manager must be able to retry while Discord is still connecting.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
with pytest.raises(RuntimeError, match="client is not ready"):
@@ -924,7 +904,6 @@ async def test_send_raises_when_client_not_ready() -> None:
@pytest.mark.asyncio
async def test_send_raises_when_channel_cannot_be_resolved() -> None:
# The manager must be able to retry transient channel-resolution failures.
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = DiscordBotClient(owner, intents=discord.Intents.none())
fetch_calls: list[int] = []
@@ -1339,7 +1318,6 @@ async def test_thread_delete_and_archive_remove_known_channel() -> None:
@pytest.mark.asyncio
async def test_client_send_outbound_chunks_text_replies_and_uploads_files(tmp_path) -> None:
# Outbound payloads should upload files, attach reply references, and chunk long text.
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = DiscordBotClient(owner, intents=discord.Intents.none())
target = _FakeChannel(channel_id=123)
@@ -1444,7 +1422,6 @@ async def test_client_send_outbound_replies_on_first_successful_attachment(tmp_p
@pytest.mark.asyncio
async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_path) -> None:
# If all attachment sends fail and no text exists, emit a failure placeholder message.
owner = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = DiscordBotClient(owner, intents=discord.Intents.none())
target = _FakeChannel(channel_id=123)
@@ -1466,7 +1443,6 @@ async def test_client_send_outbound_reports_failed_attachments_when_no_text(tmp_
@pytest.mark.asyncio
async def test_send_stops_typing_after_send() -> None:
# Active typing indicators should be cancelled/cleared after a successful send.
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = _FakeDiscordClient(channel, intents=None)
channel._client = client
@@ -1491,7 +1467,6 @@ async def test_send_stops_typing_after_send() -> None:
assert channel._typing_tasks == {}
# Progress messages should keep typing active until a final (non-progress) send.
start = asyncio.Event()
release = asyncio.Event()
@@ -1546,7 +1521,6 @@ async def test_start_typing_uses_typing_context_when_trigger_typing_missing() ->
async def _waiter():
await release.wait()
# Hold the loop so task remains active until explicitly stopped.
class _Ctx(_TypingCtx):
async def __aenter__(self):
await super().__aenter__()
@@ -1670,13 +1644,8 @@ def test_proxy_opt_in_without_shared_address_fails_before_start() -> None:
)
# ---------------------------------------------------------------------------
# Tests for the send() exception propagation fix
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_send_re_raises_network_error() -> None:
"""Network errors during send must propagate so ChannelManager can retry."""
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = _FakeDiscordClient(channel, intents=None)
channel._client = client
@@ -1693,7 +1662,6 @@ async def test_send_re_raises_network_error() -> None:
@pytest.mark.asyncio
async def test_send_re_raises_generic_exception() -> None:
"""Any exception from send_outbound must propagate, not be swallowed."""
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = _FakeDiscordClient(channel, intents=None)
channel._client = client
@@ -1710,13 +1678,11 @@ async def test_send_re_raises_generic_exception() -> None:
@pytest.mark.asyncio
async def test_send_still_stops_typing_on_error() -> None:
"""Typing cleanup must still run in the finally block even when send raises."""
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = _FakeDiscordClient(channel, intents=None)
channel._client = client
channel._running = True
# Start a typing task so we can verify it gets cleaned up
start = asyncio.Event()
release = asyncio.Event()
@@ -1740,13 +1706,11 @@ async def test_send_still_stops_typing_on_error() -> None:
release.set()
await asyncio.sleep(0)
# Typing should have been cleaned up by the finally block
assert channel._typing_tasks == {}
@pytest.mark.asyncio
async def test_send_succeeds_normally() -> None:
"""Successful sends should work without raising."""
channel = DiscordChannel(DiscordConfig(enabled=True, allow_from=["*"]), MessageBus())
client = _FakeDiscordClient(channel, intents=None)
channel._client = client
@@ -1829,7 +1793,6 @@ async def test_automatic_compaction_is_received_but_not_sent() -> None:
@pytest.mark.asyncio
async def test_compaction_outcome_without_a_start_notice_is_sent() -> None:
# After a restart (or when the edit is refused) the outcome still arrives.
target = _FakeChannel(channel_id=123)
owner, client = _client_with_channel(target)
-2
View File
@@ -1,5 +1,3 @@
"""Discord setup validation owned by the channel package."""
from typing import Any
import httpx