Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat(zulip): 支持Bot自动订阅频道以接收话题中的@mention消息

iwedo9f6ebe91ba93
diff --git a/deeptutor/tutorbot/channels/zulip.py b/deeptutor/tutorbot/channels/zulip.py
index 6c820e3d2..893040fd5 100644
--- a/deeptutor/tutorbot/channels/zulip.py
+++ b/deeptutor/tutorbot/channels/zulip.py
@@ -49,6 +49,7 @@ class ZulipConfig(Base):
api_key: str = Field(default="", repr=False)
allow_from: list[str] = Field(default_factory=list)
group_policy: Literal["mention", "open"] = "mention"
+ subscribe_streams: list[str] = Field(default_factory=list)
timeout: float = Field(default=60.0)
@@ -68,6 +69,7 @@ class ZulipChannel(BaseChannel):
self._client: Any = None
self._bot_email: str = ""
self._bot_user_id: int | None = None
+ self._bot_full_name: str = ""
self._queue_id: str | None = None
self._last_event_id: int = -1
self._max_message_id: int = 0
@@ -118,12 +120,15 @@ class ZulipChannel(BaseChannel):
self._bot_email = profile.get("email", self.config.email)
self._bot_user_id = profile.get("user_id")
+ self._bot_full_name = profile.get("full_name", "")
logger.info(
"Zulip bot connected: {} (user_id={})",
self._bot_email,
self._bot_user_id,
)
+ self._subscribe_to_streams()
+
self._listener_thread = threading.Thread(
target=self._run_listener, daemon=True, name="zulip-listener"
)
@@ -248,6 +253,54 @@ class ZulipChannel(BaseChannel):
logger.info("Zulip listener stopped")
+ def _subscribe_to_streams(self) -> None:
+ streams = self.config.subscribe_streams
+ if not streams:
+ logger.info("No subscribe_streams configured, skipping auto-subscribe")
+ return
+
+ stream_names: list[str]
+ if "*" in streams:
+ try:
+ result = self._call_with_retry(self._client.get_streams, include_all=True)
+ except Exception as e:
+ logger.error("Zulip get_streams failed during auto-subscribe: {}", e)
+ return
+ if result.get("result") != "success":
+ logger.error("Failed to fetch streams for auto-subscribe: {}", result.get("msg"))
+ return
+ fetched = {s["name"] for s in result.get("streams", [])}
+ extra = {s for s in streams if s != "*"}
+ stream_names = list(fetched | extra)
+ else:
+ stream_names = list(streams)
+
+ if not stream_names:
+ logger.info("No streams to subscribe to")
+ return
+
+ subscriptions = [{"name": name} for name in stream_names]
+ try:
+ result = self._call_with_retry(
+ self._client.add_subscriptions, streams=subscriptions
+ )
+ except Exception as e:
+ logger.error("Zulip auto-subscribe failed: {}", e)
+ return
+ if result.get("result") == "success":
+ already_subscribed_names: set[str] = set()
+ for names in result.get("already_subscribed", {}).values():
+ already_subscribed_names.update(names)
+ new_count = len(stream_names) - len(already_subscribed_names)
+ logger.info(
+ "Zulip bot subscribed to {} streams ({} new, {} already subscribed)",
+ len(stream_names),
+ new_count,
+ len(stream_names) - new_count,
+ )
+ else:
+ logger.warning("Zulip auto-subscribe partial failure: {}", result.get("msg", "unknown"))
+
def _register_queue(self) -> None:
try:
result = self._call_with_retry(
@@ -298,6 +351,14 @@ class ZulipChannel(BaseChannel):
msg_type = message.get("type", "")
content = message.get("content", "")
+ flags = message.get("flags", [])
+ logger.debug(
+ "Zulip message: type={}, flags={}, sender={}, subject={}",
+ msg_type,
+ flags,
+ message.get("sender_email", "?"),
+ message.get("subject", ""),
+ )
content_type = message.get("content_type", "text/x-markdown")
if content_type == "text/x-markdown":
content = self._convert_zulip_latex_to_standard(content)
@@ -317,6 +378,11 @@ class ZulipChannel(BaseChannel):
chat_id = self._stream_chat_id(stream_name, topic)
if self.config.group_policy == "mention":
if not self._is_mentioned(message):
+ logger.debug(
+ "Zulip stream message ignored (not mentioned): stream={}, topic={}",
+ stream_name,
+ topic,
+ )
return
content = f"**[{stream_name} > {topic}]** {content}"
elif msg_type == "private":
diff --git a/tests/services/tutorbot/test_zulip_channel.py b/tests/services/tutorbot/test_zulip_channel.py
index 3ef3b5259..4471da342 100644
--- a/tests/services/tutorbot/test_zulip_channel.py
+++ b/tests/services/tutorbot/test_zulip_channel.py
@@ -41,6 +41,7 @@ class TestZulipConfig:
assert cfg.api_key == ""
assert cfg.allow_from == []
assert cfg.group_policy == "mention"
+ assert cfg.subscribe_streams == []
assert cfg.timeout == 60.0
def test_api_key_repr_false(self):
@@ -239,7 +240,7 @@ class TestExtractUploadLinks:
class TestDownloadAttachments:
- def test_extracts_from_markdown_content(self):
+ def test_extracts_from_markdown_content(self, tmp_path: Path):
ch = _make_channel()
message = {
"content": "Check ![img.png](/user_uploads/2/ce/abc/img.png)",
@@ -249,22 +250,24 @@ class TestDownloadAttachments:
ch,
"_extract_upload_links",
return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
- ):
- with patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
- mock_resp = MagicMock()
- mock_resp.raise_for_status = MagicMock()
- mock_resp.content = b"fake-image-data"
- mock_get.return_value = mock_resp
- with patch.object(Path, "exists", return_value=False):
- with patch.object(Path, "write_bytes"):
- paths = ch._download_attachments(message)
- assert len(paths) == 1
- mock_get.assert_called_once()
- call_url = mock_get.call_args[0][0]
- assert (
- call_url
- == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
- )
+ ), patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
+ ), patch("deeptutor.tutorbot.channels.zulip.requests.get") as mock_get:
+ mock_resp = MagicMock()
+ mock_resp.raise_for_status = MagicMock()
+ mock_resp.content = b"fake-image-data"
+ mock_get.return_value = mock_resp
+ with patch.object(Path, "exists", return_value=False):
+ with patch.object(Path, "write_bytes"):
+ paths = ch._download_attachments(message)
+ assert len(paths) == 1
+ mock_get.assert_called_once()
+ call_url = mock_get.call_args[0][0]
+ assert (
+ call_url
+ == "https://example.zulipchat.com/user_uploads/2/ce/abc/img.png"
+ )
def test_no_uploads_returns_empty(self):
ch = _make_channel()
@@ -273,7 +276,7 @@ class TestDownloadAttachments:
paths = ch._download_attachments(message)
assert paths == []
- def test_caches_existing_file(self):
+ def test_caches_existing_file(self, tmp_path: Path):
ch = _make_channel()
message = {
"content": "![img.png](/user_uploads/2/ce/abc/img.png)",
@@ -283,9 +286,11 @@ class TestDownloadAttachments:
ch,
"_extract_upload_links",
return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")],
+ ), patch(
+ "deeptutor.tutorbot.channels.zulip.get_media_dir",
+ return_value=tmp_path,
):
from pathlib import Path as RealPath
- from unittest.mock import mock_open
with patch.object(RealPath, "exists", return_value=True):
paths = ch._download_attachments(message)
@@ -747,8 +752,13 @@ class TestUploadAndSend:
{"msg_type": "private", "recipient_user_id": "42"},
)
- call_kwargs = mock_client.call_endpoint.call_args.kwargs
- files_arg = call_kwargs["files"]
+ upload_calls = [
+ c
+ for c in mock_client.call_endpoint.call_args_list
+ if c.kwargs.get("url") == "user_uploads"
+ ]
+ assert len(upload_calls) == 1
+ files_arg = upload_calls[0].kwargs["files"]
assert len(files_arg) == 1
f = files_arg[0]
assert hasattr(f, "name")
@@ -962,6 +972,85 @@ class TestStop:
assert len(ch._typing_tasks) == 0
+class TestSubscribeStreams:
+ def test_no_streams_configured_skips(self):
+ ch = _make_channel(subscribe_streams=[])
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_not_called()
+ mock_client.get_streams.assert_not_called()
+
+ def test_explicit_stream_names(self):
+ ch = _make_channel(subscribe_streams=["general", "dev"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_called_once()
+ call_kwargs = mock_client.add_subscriptions.call_args
+ streams_arg = call_kwargs.kwargs["streams"]
+ names = [s["name"] for s in streams_arg]
+ assert "general" in names
+ assert "dev" in names
+
+ def test_wildcard_subscribes_all_public_streams(self):
+ ch = _make_channel(subscribe_streams=["*"])
+ mock_client = MagicMock()
+ mock_client.get_streams.return_value = {
+ "result": "success",
+ "streams": [
+ {"name": "general"},
+ {"name": "dev"},
+ {"name": "announce"},
+ ],
+ }
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.get_streams.assert_called_once_with(include_all=True)
+ call_kwargs = mock_client.add_subscriptions.call_args
+ streams_arg = call_kwargs.kwargs["streams"]
+ names = {s["name"] for s in streams_arg}
+ assert names == {"general", "dev", "announce"}
+
+ def test_wildcard_fetch_failure_skips_subscribe(self):
+ ch = _make_channel(subscribe_streams=["*"])
+ mock_client = MagicMock()
+ mock_client.get_streams.return_value = {"result": "error", "msg": "forbidden"}
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_not_called()
+
+ def test_subscribe_partial_failure_logs_warning(self):
+ ch = _make_channel(subscribe_streams=["general"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "error",
+ "msg": "some error",
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_called_once()
+
+ def test_subscribe_logs_already_subscribed(self):
+ ch = _make_channel(subscribe_streams=["general", "dev"])
+ mock_client = MagicMock()
+ mock_client.add_subscriptions.return_value = {
+ "result": "success",
+ "already_subscribed": {"[email protected]": ["general"]},
+ }
+ ch._client = mock_client
+ ch._subscribe_to_streams()
+ mock_client.add_subscriptions.assert_called_once()
+
+
class TestRegisterQueue:
def test_register_success(self):
ch = _make_channel()