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 -25
View File
@@ -1,5 +1,4 @@
# pyright: reportConstantRedefinition=false, reportMissingTypeStubs=false, reportPrivateUsage=false
"""DingTalk/DingDing channel implementation using Stream Mode."""
import asyncio
import json
@@ -32,7 +31,6 @@ _DINGTALK_SENDER_NAME_MAX_CHARS = 80
def _escape_markdown_sender_name(value: str) -> str:
"""Render an untrusted display name as one bounded Markdown-safe line."""
normalized = " ".join(value.split())[:_DINGTALK_SENDER_NAME_MAX_CHARS]
return "".join(
f"\\{char}" if char in _DINGTALK_MARKDOWN_INLINE_SPECIALS else char
@@ -76,11 +74,9 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
async def process(self, message: Any) -> tuple[Any, str]:
"""Process incoming stream message."""
try:
# Parse using SDK's ChatbotMessage for robust handling
chatbot_msg: Any = ChatbotMessage.from_dict(message.data)
message_data = cast(dict[str, Any], message.data)
# Extract text content; fall back to raw dict if SDK object is empty
content = ""
if chatbot_msg.text:
content = cast(str, chatbot_msg.text.content).strip()
@@ -90,7 +86,6 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
text_data = cast(dict[str, Any], message_data.get("text", {}))
content = cast(str, text_data.get("content", "")).strip()
# Handle file/image messages
file_paths: list[str] = []
if chatbot_msg.message_type == "picture" and chatbot_msg.image_content:
download_code = chatbot_msg.image_content.download_code
@@ -194,7 +189,6 @@ class NanobotDingTalkHandler(_CallbackHandlerBase):
"Received DingTalk message from {} ({})", sender_name, sender_id
)
# Forward to Nanobot via _on_message (non-blocking).
# Store reference to prevent GC before task completes.
task = asyncio.create_task(
self.channel._on_message(
@@ -260,7 +254,6 @@ class DingTalkChannel(BaseChannel):
self._http: httpx.AsyncClient | None = None
self._start_task: asyncio.Task[Any] | None = None
# Access Token management for sending messages
self._access_token: str | None = None
self._token_expiry: float = 0
@@ -306,13 +299,11 @@ class DingTalkChannel(BaseChannel):
credential = Credential(self.config.client_id, self.config.client_secret)
self._client = DingTalkStreamClient(credential)
# Register standard handler
handler = NanobotDingTalkHandler(self)
self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)
self.logger.info("bot started with Stream Mode")
# Reconnect loop: restart stream if SDK exits or crashes
while self._running:
try:
await self._client.start()
@@ -344,11 +335,9 @@ class DingTalkChannel(BaseChannel):
await start_task
self._client = None
# Close the shared HTTP client
if self._http:
await self._http.aclose()
self._http = None
# Cancel outstanding background tasks
background_tasks = tuple(self._background_tasks)
for task in background_tasks:
task.cancel()
@@ -374,7 +363,6 @@ class DingTalkChannel(BaseChannel):
self.logger.opt(exception=True).debug("DingTalk stream client close failed")
async def _get_access_token(self) -> str | None:
"""Get or refresh Access Token."""
if self._access_token and time.time() < self._token_expiry:
return self._access_token
@@ -483,7 +471,6 @@ class DingTalkChannel(BaseChannel):
self,
media_ref: str,
) -> tuple[bytes | None, str | None]:
"""Fetch a remote media URL with SSRF, redirect, and size checks."""
if not self._http:
return None, None
@@ -626,16 +613,14 @@ class DingTalkChannel(BaseChannel):
headers = {"x-acs-dingtalk-access-token": token}
if chat_id.startswith("group:"):
# Group chat
url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
payload = {
"robotCode": self.config.client_id,
"openConversationId": chat_id[6:], # Remove "group:" prefix,
"openConversationId": chat_id[6:],
"msgKey": msg_key,
"msgParam": json.dumps(msg_param, ensure_ascii=False),
}
else:
# Private chat
url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"
payload = {
"robotCode": self.config.client_id,
@@ -783,11 +768,6 @@ class DingTalkChannel(BaseChannel):
conversation_type: str | None = None,
conversation_id: str | None = None,
) -> None:
"""Handle incoming message (called by NanobotDingTalkHandler).
Delegates to BaseChannel._handle_message() which enforces allow_from
permission checks before publishing to the bus.
"""
try:
if not sender_id:
self.logger.warning("dropping DingTalk message without a sender ID")
@@ -833,7 +813,6 @@ class DingTalkChannel(BaseChannel):
filename: str,
sender_id: str,
) -> str | None:
"""Download a DingTalk file to the media directory, return local path."""
from nanobot.config.paths import get_media_dir
try:
@@ -842,7 +821,6 @@ class DingTalkChannel(BaseChannel):
self.logger.error("file download: no token or http client")
return None
# Step 1: Exchange downloadCode for a temporary download URL
api_url = "https://api.dingtalk.com/v1.0/robot/messageFiles/download"
headers = {"x-acs-dingtalk-access-token": token, "Content-Type": "application/json"}
payload = {"downloadCode": download_code, "robotCode": self.config.client_id}
@@ -857,13 +835,11 @@ class DingTalkChannel(BaseChannel):
self.logger.error("download URL not found in response: {}", result)
return None
# Step 2: Download the file content
file_resp = await self._http.get(download_url, follow_redirects=True)
if file_resp.status_code != 200:
self.logger.error("file download failed: status={}", file_resp.status_code)
return None
# Save to media directory (accessible under workspace)
download_dir = get_media_dir("dingtalk") / sender_id
download_dir.mkdir(parents=True, exist_ok=True)
file_path = download_dir / filename