Skip to content

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

feat(tutorbot): add Zulip channel support

WeDonedccc7fc08b40
diff --git a/deeptutor/tutorbot/channels/zulip.py b/deeptutor/tutorbot/channels/zulip.py
new file mode 100644
index 000000000..b53f51709
--- /dev/null
+++ b/deeptutor/tutorbot/channels/zulip.py
@@ -0,0 +1,585 @@
+"""Zulip channel implementation using event queue API."""
+
+from __future__ import annotations
+
+import asyncio
+import re
+import threading
+import time
+from collections import deque
+from pathlib import Path
+from typing import Any, Literal
+from urllib.parse import unquote
+
+import requests
+from loguru import logger
+from pydantic import Field
+
+from deeptutor.tutorbot.bus.events import OutboundMessage
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.base import BaseChannel
+from deeptutor.tutorbot.config.paths import get_media_dir
+from deeptutor.tutorbot.config.schema import Base
+from deeptutor.tutorbot.utils.helpers import split_message
+
+_UPLOAD_LINK_RE = re.compile(
+ r"\[([^\]]*)\]\((/user_uploads/[^)\s]+)\)"
+ r"|!\[([^\]]*)\]\((/user_uploads/[^)\s]+)\)",
+)
+
+_DISPLAY_MATH_RE = re.compile(
+ r"^\s*\$\$(.+?)\$\$\s*$",
+ re.MULTILINE | re.DOTALL,
+)
+_INLINE_MATH_RE = re.compile(
+ r"(?<!\$)\$(?!\$)(.+?)(?<!\$)\$(?!\$)",
+)
+_CODE_BLOCK_RE = re.compile(
+ r"(```(?!math)[\s\S]*?```|`[^`\n]+`)",
+)
+
+ZULIP_MAX_MESSAGE_LEN = 10000
+
+
+class ZulipConfig(Base):
+ enabled: bool = False
+ site: str = ""
+ email: str = ""
+ api_key: str = Field(default="", repr=False)
+ allow_from: list[str] = Field(default_factory=list)
+ group_policy: Literal["mention", "open"] = "mention"
+ timeout: float = Field(default=60.0)
+
+
+class ZulipChannel(BaseChannel):
+ name = "zulip"
+ display_name = "Zulip"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return ZulipConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = ZulipConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: ZulipConfig = config
+ self._client: Any = None
+ self._bot_email: str = ""
+ self._bot_user_id: int | None = None
+ self._queue_id: str | None = None
+ self._last_event_id: int = -1
+ self._max_message_id: int = 0
+ self._seen_ids: deque[int] = deque(maxlen=5000)
+ self._listener_thread: threading.Thread | None = None
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._typing_tasks: dict[str, asyncio.Task] = {}
+ self._recipient_map: dict[str, dict] = {}
+
+ def is_allowed(self, sender_id: str) -> bool:
+ if super().is_allowed(sender_id):
+ return True
+ allow_list = getattr(self.config, "allow_from", [])
+ if not allow_list or "*" in allow_list:
+ return False
+ sender_str = str(sender_id)
+ if sender_str.count("|") != 1:
+ return False
+ sid, email = sender_str.split("|", 1)
+ return sid in allow_list or email in allow_list
+
+ async def start(self) -> None:
+ if not self.config.site or not self.config.email or not self.config.api_key:
+ logger.error("Zulip site/email/apiKey not configured")
+ return
+
+ self._running = True
+ self._loop = asyncio.get_running_loop()
+
+ try:
+ import zulip
+
+ self._client = zulip.Client(
+ email=self.config.email,
+ api_key=self.config.api_key,
+ site=self.config.site,
+ )
+ except Exception as e:
+ logger.error("Failed to create Zulip client: {}", e)
+ self._running = False
+ return
+
+ profile = self._call_with_retry(self._client.get_profile)
+ if not profile or profile.get("result") != "success":
+ logger.error("Failed to get Zulip bot profile")
+ self._running = False
+ return
+
+ self._bot_email = profile.get("email", self.config.email)
+ self._bot_user_id = profile.get("user_id")
+ logger.info(
+ "Zulip bot connected: {} (user_id={})",
+ self._bot_email,
+ self._bot_user_id,
+ )
+
+ self._listener_thread = threading.Thread(
+ target=self._run_listener, daemon=True, name="zulip-listener"
+ )
+ self._listener_thread.start()
+
+ while self._running:
+ await asyncio.sleep(1)
+
+ async def stop(self) -> None:
+ self._running = False
+
+ for chat_id in list(self._typing_tasks):
+ self._stop_typing(chat_id)
+
+ if self._queue_id and self._client:
+ try:
+ self._client.deregister(self._queue_id)
+ except Exception:
+ pass
+
+ self._queue_id = None
+ self._client = None
+
+ if self._listener_thread and self._listener_thread.is_alive():
+ self._listener_thread.join(timeout=5)
+
+ self._listener_thread = None
+
+ async def send(self, msg: OutboundMessage) -> None:
+ if not self._client:
+ logger.warning("Zulip client not running")
+ return
+
+ if not msg.metadata.get("_progress", False):
+ self._stop_typing(msg.chat_id)
+
+ try:
+ for media_path in msg.media or []:
+ await self._upload_and_send(msg.chat_id, media_path, msg.metadata)
+
+ if msg.content and msg.content != "[empty message]":
+ converted = self._convert_latex_to_zulip(msg.content)
+ for chunk in split_message(converted, ZULIP_MAX_MESSAGE_LEN):
+ await self._send_text(msg.chat_id, chunk, msg.metadata)
+ except Exception as e:
+ logger.error("Zulip send error: {}", e)
+
+ def _call_with_retry(self, fn, *args, max_retries=3, **kwargs):
+ for attempt in range(max_retries):
+ try:
+ return fn(*args, **kwargs)
+ except Exception as e:
+ if attempt < max_retries - 1:
+ delay = 2**attempt
+ logger.warning(
+ "Zulip API call failed (attempt {}): {}, retrying in {}s",
+ attempt + 1,
+ e,
+ delay,
+ )
+ time.sleep(delay)
+ else:
+ logger.error("Zulip API call failed after {} retries: {}", max_retries, e)
+ raise
+
+ def _run_listener(self) -> None:
+ while self._running:
+ try:
+ self._register_queue()
+ if not self._queue_id:
+ logger.error("Failed to register Zulip event queue, retrying in 10s...")
+ time.sleep(10)
+ continue
+
+ while self._running:
+ try:
+ result = self._client.get_events(
+ queue_id=self._queue_id,
+ last_event_id=self._last_event_id,
+ )
+ except Exception as e:
+ logger.warning("Zulip get_events error: {}", e)
+ time.sleep(2)
+ break
+
+ if result.get("result") == "http-error":
+ logger.warning("Zulip HTTP error, retrying...")
+ time.sleep(2)
+ break
+
+ if result.get("code") == "BAD_EVENT_QUEUE_ID":
+ logger.warning("Zulip event queue expired, re-registering...")
+ self._queue_id = None
+ break
+
+ if result.get("result") != "success":
+ logger.warning(
+ "Zulip get_events unexpected result: {}",
+ result.get("msg", result.get("result")),
+ )
+ time.sleep(2)
+ continue
+
+ for event in result.get("events", []):
+ self._last_event_id = max(
+ self._last_event_id, event.get("id", self._last_event_id)
+ )
+ if event.get("type") == "message":
+ self._on_message(event.get("message", {}))
+
+ except Exception as e:
+ logger.error("Zulip listener error: {}", e)
+ time.sleep(5)
+
+ logger.info("Zulip listener stopped")
+
+ def _register_queue(self) -> None:
+ try:
+ result = self._call_with_retry(
+ self._client.register,
+ event_types=["message"],
+ )
+ if result.get("result") == "success":
+ self._queue_id = result["queue_id"]
+ self._last_event_id = result.get("last_event_id", -1)
+ self._max_message_id = result.get("max_message_id", 0)
+ logger.info(
+ "Zulip event queue registered: queue_id={}, max_message_id={}",
+ self._queue_id,
+ self._max_message_id,
+ )
+ else:
+ logger.error("Zulip register failed: {}", result.get("msg", "unknown"))
+ self._queue_id = None
+ except Exception as e:
+ logger.error("Zulip register exception: {}", e)
+ self._queue_id = None
+
+ def _is_own_message(self, message: dict) -> bool:
+ sender_email = message.get("sender_email", "")
+ sender_id = message.get("sender_id")
+ if sender_email and sender_email == self._bot_email:
+ return True
+ if self._bot_user_id is not None and sender_id == self._bot_user_id:
+ return True
+ return False
+
+ def _is_duplicate(self, message: dict) -> bool:
+ msg_id = message.get("id")
+ if msg_id is None:
+ return False
+ if msg_id <= self._max_message_id:
+ return True
+ if msg_id in self._seen_ids:
+ return True
+ self._seen_ids.append(msg_id)
+ return False
+
+ def _on_message(self, message: dict) -> None:
+ if self._is_own_message(message):
+ return
+ if self._is_duplicate(message):
+ return
+
+ msg_type = message.get("type", "")
+ content = message.get("content", "")
+ content_type = message.get("content_type", "text/x-markdown")
+ if content_type == "text/x-markdown":
+ content = self._convert_zulip_latex_to_standard(content)
+ sender_id = message.get("sender_id", "")
+ sender_email = message.get("sender_email", "")
+ display_recipient = message.get("display_recipient", "")
+ subject = message.get("subject", "")
+
+ composite_sender = f"{sender_id}|{sender_email}" if sender_email else str(sender_id)
+
+ if msg_type == "stream":
+ if isinstance(display_recipient, dict):
+ stream_name = display_recipient.get("name", str(display_recipient))
+ else:
+ stream_name = str(display_recipient)
+ chat_id = f"stream:{stream_name}"
+ if self.config.group_policy == "mention":
+ if not self._is_mentioned(message):
+ return
+ content = f"**[{stream_name} > {subject}]** {content}"
+ elif msg_type == "private":
+ chat_id = f"pm:{sender_id}"
+ else:
+ return
+
+ metadata = {
+ "message_id": message.get("id"),
+ "msg_type": msg_type,
+ "sender_email": sender_email,
+ "sender_full_name": message.get("sender_full_name", ""),
+ "display_recipient": display_recipient,
+ "subject": subject,
+ }
+
+ if msg_type == "stream":
+ if isinstance(display_recipient, dict):
+ metadata["stream"] = display_recipient.get("name", str(display_recipient))
+ else:
+ metadata["stream"] = display_recipient
+ metadata["topic"] = subject
+ else:
+ metadata["recipient_user_id"] = sender_id
+
+ self._recipient_map[chat_id] = metadata
+
+ media_paths = self._download_attachments(message)
+
+ if self._loop and not self._loop.is_closed():
+ asyncio.run_coroutine_threadsafe(
+ self._start_typing_async(chat_id), self._loop
+ )
+ asyncio.run_coroutine_threadsafe(
+ self._handle_message(
+ sender_id=composite_sender,
+ chat_id=chat_id,
+ content=content,
+ media=media_paths,
+ metadata=metadata,
+ ),
+ self._loop,
+ )
+
+ def _is_mentioned(self, message: dict) -> bool:
+ if self._bot_user_id is None:
+ return False
+ for flag in message.get("flags", []):
+ if isinstance(flag, str) and flag == "mentioned":
+ return True
+ return False
+
+ def _download_attachments(self, message: dict) -> list[str]:
+ paths: list[str] = []
+ content = message.get("content", "")
+ content_type = message.get("content_type", "text/x-markdown")
+
+ upload_links = self._extract_upload_links(content, content_type)
+ if not upload_links:
+ return paths
+
+ media_dir = get_media_dir("zulip")
+
+ for name, path_id in upload_links:
+ url = f"{self.config.site}{path_id}"
+ safe_name = re.sub(r'[^\w.\-]', '_', unquote(name)) if name else f"attachment_{len(paths)}"
+ dest = media_dir / safe_name
+
+ if dest.exists():
+ paths.append(str(dest))
+ continue
+
+ try:
+ resp = requests.get(
+ url,
+ auth=(self.config.email, self.config.api_key),
+ timeout=self.config.timeout,
+ )
+ resp.raise_for_status()
+ dest.write_bytes(resp.content)
+ paths.append(str(dest))
+ logger.debug("Downloaded Zulip attachment: {}", name or path_id)
+ except Exception as e:
+ logger.warning("Failed to download Zulip attachment {}: {}", name or path_id, e)
+
+ return paths
+
+ @staticmethod
+ def _extract_upload_links(content: str, content_type: str = "text/x-markdown") -> list[tuple[str, str]]:
+ links: list[tuple[str, str]] = []
+ seen: set[str] = set()
+
+ if content_type == "text/html":
+ for match in re.finditer(r'href="(/user_uploads/[^"]+)"', content):
+ path_id = match.group(1)
+ if path_id not in seen:
+ seen.add(path_id)
+ name = Path(unquote(path_id)).name
+ links.append((name, path_id))
+ for match in re.finditer(r'src="(/user_uploads/[^"]+)"', content):
+ path_id = match.group(1)
+ if path_id not in seen:
+ seen.add(path_id)
+ name = Path(unquote(path_id)).name
+ links.append((name, path_id))
+ else:
+ for match in _UPLOAD_LINK_RE.finditer(content):
+ md_name = match.group(1) or match.group(3) or ""
+ path_id = match.group(2) or match.group(4) or ""
+ if path_id and path_id not in seen:
+ seen.add(path_id)
+ name = md_name if md_name else Path(unquote(path_id)).name
+ links.append((name, path_id))
+
+ return links
+
+ @staticmethod
+ def _convert_latex_to_zulip(text: str) -> str:
+ placeholders: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ placeholders.append(m.group(0))
+ return f"\x00CODE{len(placeholders) - 1}\x00"
+
+ text = _CODE_BLOCK_RE.sub(_save_code, text)
+
+ def _display_math(m: re.Match) -> str:
+ body = m.group(1).strip()
+ return f"```math\n{body}\n```"
+
+ text = _DISPLAY_MATH_RE.sub(_display_math, text)
+
+ def _inline_math(m: re.Match) -> str:
+ body = m.group(1)
+ return f"$${body}$$"
+
+ text = _INLINE_MATH_RE.sub(_inline_math, text)
+
+ for i, code in enumerate(placeholders):
+ text = text.replace(f"\x00CODE{i}\x00", code)
+
+ return text
+
+ @staticmethod
+ def _convert_zulip_latex_to_standard(text: str) -> str:
+ placeholders: list[str] = []
+
+ def _save_code(m: re.Match) -> str:
+ placeholders.append(m.group(0))
+ return f"\x00CODE{len(placeholders) - 1}\x00"
+
+ text = _CODE_BLOCK_RE.sub(_save_code, text)
+
+ text = re.sub(
+ r"```math\s*\n(.*?)\n\s*```",
+ lambda m: f"$$\n{m.group(1).strip()}\n$$",
+ text,
+ flags=re.DOTALL,
+ )
+
+ text = re.sub(
+ r"(?<!\$)\$\$(?!\$)(.+?)(?<!\$)\$\$(?!\$)",
+ lambda m: f"${m.group(1)}$",
+ text,
+ )
+
+ for i, code in enumerate(placeholders):
+ text = text.replace(f"\x00CODE{i}\x00", code)
+
+ return text
+
+ async def _send_text(self, chat_id: str, text: str, metadata: dict) -> None:
+ client = self._client
+ if not client:
+ return
+ request = self._build_send_request(chat_id, text, metadata)
+ loop = asyncio.get_running_loop()
+ result = await loop.run_in_executor(
+ None,
+ lambda: self._call_with_retry(
+ client.call_endpoint,
+ url="messages",
+ request=request,
+ timeout=self.config.timeout,
+ ),
+ )
+ if result.get("result") != "success":
+ logger.error("Zulip send failed: {}", result.get("msg", "unknown"))
+
+ async def _upload_and_send(self, chat_id: str, media_path: str, metadata: dict) -> None:
+ client = self._client
+ if not client:
+ return
+ loop = asyncio.get_running_loop()
+ result = await loop.run_in_executor(
+ None,
+ lambda: self._call_with_retry(
+ client.call_endpoint,
+ url="user_uploads",
+ files=[media_path],
+ timeout=self.config.timeout,
+ ),
+ )
+ if result.get("result") != "success":
+ logger.error("Zulip upload failed: {}", result.get("msg", "unknown"))
+ return
+
+ uri = result.get("uri", "")
+ filename = Path(media_path).name
+ content = f"[{filename}]({self.config.site}{uri})"
+ await self._send_text(chat_id, content, metadata)
+
+ def _build_send_request(self, chat_id: str, content: str, metadata: dict) -> dict:
+ msg_type = metadata.get("msg_type", "private")
+
+ if msg_type == "stream":
+ stream = metadata.get("stream", metadata.get("display_recipient", ""))
+ topic = metadata.get("topic", metadata.get("subject", ""))
+ return {
+ "type": "stream",
+ "to": stream,
+ "subject": topic or "(no topic)",
+ "content": content,
+ }
+ else:
+ recipient = metadata.get("recipient_user_id") or metadata.get("sender_email", "")
+ return {
+ "type": "private",
+ "to": [recipient] if recipient else [],
+ "content": content,
+ }
+
+ async def _start_typing_async(self, chat_id: str) -> None:
+ self._start_typing(chat_id)
+
+ def _start_typing(self, chat_id: str) -> None:
+ self._stop_typing(chat_id)
+ self._typing_tasks[chat_id] = asyncio.create_task(self._typing_loop(chat_id))
+
+ def _stop_typing(self, chat_id: str) -> None:
+ task = self._typing_tasks.pop(chat_id, None)
+ if task and not task.done():
+ task.cancel()
+
+ async def _typing_loop(self, chat_id: str) -> None:
+ if not self._client or not self._bot_user_id:
+ return
+
+ if not chat_id.startswith("pm:"):
+ return
+
+ recipient_user_id = chat_id[3:]
+ if not recipient_user_id.isdigit():
+ return
+
+ try:
+ while self._running and self._client:
+ try:
+ self._client.set_typing_status({
+ "op": "start",
+ "to": [int(recipient_user_id)],
+ })
+ except Exception as e:
+ logger.debug("Zulip typing status error: {}", e)
+ await asyncio.sleep(4)
+ except asyncio.CancelledError:
+ pass
+ finally:
+ if self._client:
+ try:
+ self._client.set_typing_status({
+ "op": "stop",
+ "to": [int(recipient_user_id)],
+ })
+ except Exception:
+ pass
diff --git a/pyproject.toml b/pyproject.toml
index 607a89f23..1eb5ac1a5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -89,6 +89,7 @@ tutorbot = [
"python-socks[asyncio]>=2.8.0,<3.0.0",
"socksio>=1.0.0,<2.0.0",
"websocket-client>=1.9.0,<2.0.0",
+ "zulip>=0.8.0,<1.0.0",
]
# Matrix (Element) channel for TutorBot. Mirrors requirements/matrix.txt.
diff --git a/requirements/tutorbot.txt b/requirements/tutorbot.txt
index 01acc7a7f..cc97f913f 100644
--- a/requirements/tutorbot.txt
+++ b/requirements/tutorbot.txt
@@ -31,3 +31,4 @@ msgpack>=1.1.0,<2.0.0
python-socks[asyncio]>=2.8.0,<3.0.0
socksio>=1.0.0,<2.0.0
websocket-client>=1.9.0,<2.0.0
+zulip>=0.8.0,<1.0.0
diff --git a/tests/services/tutorbot/test_zulip_channel.py b/tests/services/tutorbot/test_zulip_channel.py
new file mode 100644
index 000000000..cffcc9f8c
--- /dev/null
+++ b/tests/services/tutorbot/test_zulip_channel.py
@@ -0,0 +1,780 @@
+"""Unit tests for the Zulip channel implementation."""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from deeptutor.tutorbot.bus.queue import MessageBus
+from deeptutor.tutorbot.channels.zulip import ZulipChannel, ZulipConfig
+
+
+def _make_channel(**overrides) -> ZulipChannel:
+ defaults = {
+ "enabled": True,
+ "site": "https://example.zulipchat.com",
+ "email": "[email protected]",
+ "api_key": "secret-key-123",
+ "allow_from": ["*"],
+ "group_policy": "mention",
+ "timeout": 60.0,
+ }
+ defaults.update(overrides)
+ config = ZulipConfig.model_validate(defaults)
+ bus = MagicMock(spec=MessageBus)
+ bus.publish_inbound = AsyncMock()
+ return ZulipChannel(config, bus)
+
+
+class TestZulipConfig:
+ def test_default_values(self):
+ cfg = ZulipConfig()
+ assert cfg.enabled is False
+ assert cfg.site == ""
+ assert cfg.email == ""
+ assert cfg.api_key == ""
+ assert cfg.allow_from == []
+ assert cfg.group_policy == "mention"
+ assert cfg.timeout == 60.0
+
+ def test_api_key_repr_false(self):
+ cfg = ZulipConfig(api_key="super-secret")
+ dumped = cfg.model_dump()
+ assert dumped["api_key"] == "super-secret"
+ r = repr(cfg)
+ assert "super-secret" not in r
+
+ def test_camel_case_alias(self):
+ cfg = ZulipConfig(site="https://example.zulipchat.com", api_key="k")
+ d = cfg.model_dump(by_alias=True)
+ assert "apiKey" in d
+ assert "groupPolicy" in d
+
+ def test_from_camel_case_dict(self):
+ d = {
+ "enabled": True,
+ "site": "https://example.zulipchat.com",
+ "email": "[email protected]",
+ "apiKey": "secret",
+ "allowFrom": ["*"],
+ "groupPolicy": "open",
+ }
+ cfg = ZulipConfig.model_validate(d)
+ assert cfg.api_key == "secret"
+ assert cfg.group_policy == "open"
+ assert cfg.allow_from == ["*"]
+
+
+class TestDefaultConfig:
+ def test_default_config_returns_dict(self):
+ cfg = ZulipChannel.default_config()
+ assert isinstance(cfg, dict)
+ assert cfg["enabled"] is False
+ assert "site" in cfg
+ assert "apiKey" in cfg
+
+
+class TestIsAllowed:
+ def test_wildcard_allows_all(self):
+ ch = _make_channel(allow_from=["*"])
+ assert ch.is_allowed("42") is True
+
+ def test_empty_list_denies_all(self):
+ ch = _make_channel(allow_from=[])
+ assert ch.is_allowed("42") is False
+
+ def test_sender_id_match(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42") is True
+ assert ch.is_allowed("99") is False
+
+ def test_composite_sender_id_email_match(self):
+ ch = _make_channel(allow_from=["[email protected]"])
+ assert ch.is_allowed("42|[email protected]") is True
+ assert ch.is_allowed("42|[email protected]") is False
+
+ def test_composite_sender_id_numeric_match(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42|[email protected]") is True
+
+ def test_composite_sender_id_no_pipe(self):
+ ch = _make_channel(allow_from=["42"])
+ assert ch.is_allowed("42") is True
+
+
+class TestIsOwnMessage:
+ def test_matches_by_email(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 200}) is True
+
+ def test_matches_by_user_id(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 100}) is True
+
+ def test_not_own_message(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ assert ch._is_own_message({"sender_email": "[email protected]", "sender_id": 200}) is False
+
+
+class TestIsDuplicate:
+ def test_skips_messages_below_max_message_id(self):
+ ch = _make_channel()
+ ch._max_message_id = 100
+ assert ch._is_duplicate({"id": 50}) is True
+
+ def test_allows_new_messages(self):
+ ch = _make_channel()
+ ch._max_message_id = 100
+ assert ch._is_duplicate({"id": 101}) is False
+
+ def test_detects_duplicate_in_seen_ids(self):
+ ch = _make_channel()
+ ch._max_message_id = 0
+ ch._seen_ids = deque([101, 102, 103], maxlen=5000)
+ assert ch._is_duplicate({"id": 102}) is True
+
+ def test_adds_new_id_to_seen(self):
+ ch = _make_channel()
+ ch._max_message_id = 0
+ ch._is_duplicate({"id": 200})
+ assert 200 in ch._seen_ids
+
+ def test_none_id_not_duplicate(self):
+ ch = _make_channel()
+ assert ch._is_duplicate({}) is False
+
+
+class TestIsMentioned:
+ def test_mentioned_flag(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["mentioned"]}) is True
+
+ def test_no_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": []}) is False
+
+ def test_other_flags(self):
+ ch = _make_channel()
+ ch._bot_user_id = 100
+ assert ch._is_mentioned({"flags": ["has_alert_word"]}) is False
+
+ def test_no_bot_user_id(self):
+ ch = _make_channel()
+ ch._bot_user_id = None
+ assert ch._is_mentioned({"flags": ["mentioned"]}) is False
+
+
+class TestExtractUploadLinks:
+ def test_markdown_image(self):
+ content = "Check this: ![photo.png](/user_uploads/2/ce/abc123/photo.png)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "photo.png"
+ assert links[0][1] == "/user_uploads/2/ce/abc123/photo.png"
+
+ def test_markdown_file_link(self):
+ content = "Here is [report.pdf](/user_uploads/2/ce/def456/report.pdf)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "report.pdf"
+ assert links[0][1] == "/user_uploads/2/ce/def456/report.pdf"
+
+ def test_html_img_src(self):
+ content = '<p><img src="/user_uploads/2/ce/abc123/photo.png"></p>'
+ links = ZulipChannel._extract_upload_links(content, content_type="text/html")
+ assert len(links) == 1
+ assert links[0][1] == "/user_uploads/2/ce/abc123/photo.png"
+
+ def test_html_a_href(self):
+ content = '<a href="/user_uploads/2/ce/def456/report.pdf">report.pdf</a>'
+ links = ZulipChannel._extract_upload_links(content, content_type="text/html")
+ assert len(links) == 1
+ assert links[0][1] == "/user_uploads/2/ce/def456/report.pdf"
+
+ def test_multiple_links(self):
+ content = (
+ "See ![img.png](/user_uploads/2/ce/aaa/img.png) "
+ "and [doc.pdf](/user_uploads/2/ce/bbb/doc.pdf)"
+ )
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 2
+
+ def test_dedup_same_path(self):
+ content = (
+ "![img.png](/user_uploads/2/ce/aaa/img.png) "
+ "again [img.png](/user_uploads/2/ce/aaa/img.png)"
+ )
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+
+ def test_no_uploads(self):
+ content = "Just a plain message with no attachments"
+ links = ZulipChannel._extract_upload_links(content)
+ assert links == []
+
+ def test_non_upload_link_ignored(self):
+ content = "[Zulip](https://zulip.com) and [docs](/help/)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert links == []
+
+ def test_empty_name_uses_path(self):
+ content = "![](/user_uploads/2/ce/abc123/photo.png)"
+ links = ZulipChannel._extract_upload_links(content)
+ assert len(links) == 1
+ assert links[0][0] == "photo.png"
+
+
+class TestDownloadAttachments:
+ def test_extracts_from_markdown_content(self):
+ ch = _make_channel()
+ message = {
+ "content": "Check ![img.png](/user_uploads/2/ce/abc/img.png)",
+ "content_type": "text/x-markdown",
+ }
+ with patch.object(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"
+
+ def test_no_uploads_returns_empty(self):
+ ch = _make_channel()
+ message = {"content": "No attachments here", "content_type": "text/x-markdown"}
+ with patch.object(ch, "_extract_upload_links", return_value=[]):
+ paths = ch._download_attachments(message)
+ assert paths == []
+
+ def test_caches_existing_file(self):
+ ch = _make_channel()
+ message = {
+ "content": "![img.png](/user_uploads/2/ce/abc/img.png)",
+ "content_type": "text/x-markdown",
+ }
+ with patch.object(ch, "_extract_upload_links", return_value=[("img.png", "/user_uploads/2/ce/abc/img.png")]):
+ from unittest.mock import mock_open
+ from pathlib import Path as RealPath
+ with patch.object(RealPath, "exists", return_value=True):
+ paths = ch._download_attachments(message)
+ assert len(paths) == 1
+
+
+class TestConvertLatexToZulip:
+ def test_inline_math(self):
+ result = ZulipChannel._convert_latex_to_zulip("The value $x^2$ is positive")
+ assert result == "The value $$x^2$$ is positive"
+
+ def test_display_math(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$\n\\int_a^b f(x) dx\n$$")
+ assert "```math" in result
+ assert "\\int_a^b f(x) dx" in result
+ assert "$$" not in result
+
+ def test_display_math_single_line(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$E = mc^2$$")
+ assert "```math" in result
+ assert "E = mc^2" in result
+
+ def test_mixed_inline_and_display(self):
+ result = ZulipChannel._convert_latex_to_zulip(
+ "Inline $a+b$ and display:\n$$c+d$$"
+ )
+ assert "$$a+b$$" in result
+ assert "```math" in result
+ assert "c+d" in result
+
+ def test_code_block_preserved(self):
+ result = ZulipChannel._convert_latex_to_zulip(
+ "```python\nx = $1 + $2\n```"
+ )
+ assert "```python" in result
+ assert "$1 + $2" in result
+
+ def test_inline_code_preserved(self):
+ result = ZulipChannel._convert_latex_to_zulip("Use `$x$` variable")
+ assert "`$x$`" in result
+
+ def test_no_math_unchanged(self):
+ text = "Just plain text without any math"
+ assert ZulipChannel._convert_latex_to_zulip(text) == text
+
+ def test_already_double_dollar_preserved_as_display(self):
+ result = ZulipChannel._convert_latex_to_zulip("$$x^2$$")
+ assert "```math" in result
+
+ def test_multiple_inline(self):
+ result = ZulipChannel._convert_latex_to_zulip("$a$ and $b$ and $c$")
+ assert result == "$$a$$ and $$b$$ and $$c$$"
+
+
+class TestConvertZulipLatexToStandard:
+ def test_inline_math(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard("The value $$x^2$$ is positive")
+ assert result == "The value $x^2$ is positive"
+
+ def test_display_math(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard(
+ "```math\n\\int_a^b f(x) dx\n```"
+ )
+ assert "$$" in result
+ assert "\\int_a^b f(x) dx" in result
+ assert "```math" not in result
+
+ def test_mixed(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard(
+ "Inline $$a+b$$ and display:\n```math\nc+d\n```"
+ )
+ assert "$a+b$" in result
+ assert "$$" in result
+ assert "c+d" in result
+
+ def test_code_block_preserved(self):
+ result = ZulipChannel._convert_zulip_latex_to_standard(
+ "```python\nx = $$1 + $$2\n```"
+ )
+ assert "```python" in result
+ assert "$$1 + $$2" in result
+
+ def test_no_math_unchanged(self):
+ text = "Just plain text"
+ assert ZulipChannel._convert_zulip_latex_to_standard(text) == text
+
+ def test_roundtrip_inline(self):
+ original = "The value $x^2$ is positive"
+ zulip_fmt = ZulipChannel._convert_latex_to_zulip(original)
+ restored = ZulipChannel._convert_zulip_latex_to_standard(zulip_fmt)
+ assert restored == original
+
+ def test_roundtrip_display(self):
+ original = "$$\n\\int_a^b f(x) dx\n$$"
+ zulip_fmt = ZulipChannel._convert_latex_to_zulip(original)
+ restored = ZulipChannel._convert_zulip_latex_to_standard(zulip_fmt)
+ assert "\\int_a^b f(x) dx" in restored
+
+
+class TestBuildSendRequest:
+ def test_stream_message(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "stream",
+ "stream": "general",
+ "topic": "hello",
+ }
+ req = ch._build_send_request("stream:general", "Hello world", metadata)
+ assert req["type"] == "stream"
+ assert req["to"] == "general"
+ assert req["subject"] == "hello"
+ assert req["content"] == "Hello world"
+
+ def test_stream_message_no_topic(self):
+ ch = _make_channel()
+ metadata = {"msg_type": "stream", "stream": "general", "topic": ""}
+ req = ch._build_send_request("stream:general", "Hi", metadata)
+ assert req["subject"] == "(no topic)"
+
+ def test_private_message(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "private",
+ "recipient_user_id": "42",
+ }
+ req = ch._build_send_request("pm:42", "Hello", metadata)
+ assert req["type"] == "private"
+ assert req["to"] == ["42"]
+
+ def test_private_message_fallback_to_email(self):
+ ch = _make_channel()
+ metadata = {
+ "msg_type": "private",
+ "sender_email": "[email protected]",
+ }
+ req = ch._build_send_request("pm:42", "Hello", metadata)
+ assert req["to"] == ["[email protected]"]
+
+
+class TestOnMessage:
+ def _make_msg(self, **overrides) -> dict:
+ base = {
+ "id": 200,
+ "type": "private",
+ "content": "Hello bot",
+ "sender_id": 42,
+ "sender_email": "[email protected]",
+ "sender_full_name": "Test User",
+ "display_recipient": [
+ {"id": 42, "email": "[email protected]"},
+ {"id": 100, "email": "[email protected]"},
+ ],
+ "subject": "",
+ "flags": [],
+ "attachments": [],
+ }
+ base.update(overrides)
+ return base
+
+ @pytest.mark.asyncio
+ async def test_private_message_dispatched(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg()
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert call_args.channel == "zulip"
+ assert call_args.sender_id == "42|[email protected]"
+ assert call_args.chat_id == "pm:42"
+ assert call_args.content == "Hello bot"
+
+ @pytest.mark.asyncio
+ async def test_own_message_filtered(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(sender_email="[email protected]", sender_id=100)
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_duplicate_message_filtered(self):
+ ch = _make_channel()
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(id=200)
+ ch._on_message(msg)
+ await asyncio.sleep(0.1)
+
+ ch.bus.publish_inbound.reset_mock()
+ ch._on_message(msg)
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_stream_mention_policy_rejects_unmentioned(self):
+ ch = _make_channel(group_policy="mention")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_stream_mention_policy_allows_mentioned(self):
+ ch = _make_channel(group_policy="mention")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=["mentioned"],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_stream_open_policy_allows_all(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ ch.bus.publish_inbound.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_stream_message_includes_prefix(self):
+ ch = _make_channel(group_policy="open")
+ ch._bot_email = "[email protected]"
+ ch._bot_user_id = 100
+ ch._max_message_id = 0
+ ch._loop = asyncio.get_running_loop()
+
+ msg = self._make_msg(
+ type="stream",
+ display_recipient="general",
+ subject="test topic",
+ content="Hello",
+ flags=[],
+ )
+ ch._on_message(msg)
+
+ await asyncio.sleep(0.1)
+ call_args = ch.bus.publish_inbound.call_args[0][0]
+ assert "**[general > test topic]**" in call_args.content
+
+
+class TestSend:
+ @pytest.mark.asyncio
+ async def test_send_text_uses_call_endpoint(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ from deeptutor.tutorbot.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={"msg_type": "private", "recipient_user_id": "42"},
+ )
+ await ch.send(msg)
+
+ mock_client.call_endpoint.assert_called_once()
+ call_kwargs = mock_client.call_endpoint.call_args
+ assert call_kwargs.kwargs["url"] == "messages"
+ assert call_kwargs.kwargs["timeout"] == 60.0
+
+ @pytest.mark.asyncio
+ async def test_send_stops_typing_on_final_response(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ typing_task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = typing_task
+
+ from deeptutor.tutorbot.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={},
+ )
+ await ch.send(msg)
+ assert "pm:42" not in ch._typing_tasks
+
+ @pytest.mark.asyncio
+ async def test_send_keeps_typing_on_progress(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.call_endpoint.return_value = {"result": "success"}
+ ch._client = mock_client
+
+ typing_task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = typing_task
+
+ from deeptutor.tutorbot.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Thinking...",
+ metadata={"_progress": True},
+ )
+ await ch.send(msg)
+ assert "pm:42" in ch._typing_tasks
+
+ @pytest.mark.asyncio
+ async def test_send_no_client_returns_early(self):
+ ch = _make_channel()
+ ch._client = None
+
+ from deeptutor.tutorbot.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="Hello",
+ metadata={},
+ )
+ await ch.send(msg)
+
+
+class TestUploadAndSend:
+ @pytest.mark.asyncio
+ async def test_upload_uses_call_endpoint(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+
+ def fake_call_endpoint(**kwargs):
+ if kwargs.get("url") == "user_uploads":
+ return {"result": "success", "uri": "/user_uploads/img.png"}
+ return {"result": "success"}
+
+ mock_client.call_endpoint.side_effect = fake_call_endpoint
+ ch._client = mock_client
+
+ from deeptutor.tutorbot.bus.events import OutboundMessage
+
+ msg = OutboundMessage(
+ channel="zulip",
+ chat_id="pm:42",
+ content="",
+ media=["/tmp/test.png"],
+ metadata={"msg_type": "private", "recipient_user_id": "42"},
+ )
+ await ch.send(msg)
+
+ 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
+ assert upload_calls[0].kwargs["timeout"] == 60.0
+
+
+class TestStop:
+ @pytest.mark.asyncio
+ async def test_stop_deregisters_queue(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._queue_id = "test-queue-123"
+ ch._running = True
+
+ saved_client = ch._client
+ await ch.stop()
+
+ saved_client.deregister.assert_called_once_with("test-queue-123")
+ assert ch._queue_id is None
+ assert ch._client is None
+ assert ch._running is False
+
+ @pytest.mark.asyncio
+ async def test_stop_cancels_typing_tasks(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ ch._client = mock_client
+ ch._running = True
+
+ task = asyncio.create_task(asyncio.sleep(100))
+ ch._typing_tasks["pm:42"] = task
+
+ await ch.stop()
+ await asyncio.sleep(0)
+ assert task.cancelled() or task.done()
+ assert len(ch._typing_tasks) == 0
+
+
+class TestRegisterQueue:
+ def test_register_success(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.register.return_value = {
+ "result": "success",
+ "queue_id": "q-123",
+ "last_event_id": 10,
+ "max_message_id": 500,
+ }
+ ch._client = mock_client
+
+ ch._register_queue()
+ assert ch._queue_id == "q-123"
+ assert ch._last_event_id == 10
+ assert ch._max_message_id == 500
+
+ def test_register_failure(self):
+ ch = _make_channel()
+ mock_client = MagicMock()
+ mock_client.register.return_value = {
+ "result": "error",
+ "msg": "bad request",
+ }
+ ch._client = mock_client
+
+ ch._register_queue()
+ assert ch._queue_id is None
+
+
+class TestCallWithRetry:
+ def test_succeeds_on_first_attempt(self):
+ ch = _make_channel()
+ fn = MagicMock(return_value={"result": "success"})
+ result = ch._call_with_retry(fn)
+ assert result == {"result": "success"}
+ assert fn.call_count == 1
+
+ def test_retries_on_failure(self):
+ ch = _make_channel()
+ fn = MagicMock(side_effect=[Exception("fail"), Exception("fail again"), {"result": "success"}])
+ with patch("time.sleep"):
+ result = ch._call_with_retry(fn)
+ assert result == {"result": "success"}
+ assert fn.call_count == 3
+
+ def test_raises_after_max_retries(self):
+ ch = _make_channel()
+ fn = MagicMock(side_effect=Exception("persistent failure"))
+ with patch("time.sleep"):
+ with pytest.raises(Exception, match="persistent failure"):
+ ch._call_with_retry(fn)
+ assert fn.call_count == 3
+
+
+class TestStart:
+ @pytest.mark.asyncio
+ async def test_start_without_config_returns_early(self):
+ ch = _make_channel(site="", email="", api_key="")
+ await ch.start()
+ assert ch._running is False
+
+ @pytest.mark.asyncio
+ async def test_start_profile_failure(self):
+ ch = _make_channel()
+ with patch("deeptutor.tutorbot.channels.zulip.ZulipChannel._call_with_retry") as mock_retry:
+ mock_retry.return_value = {"result": "error"}
+ with patch("zulip.Client"):
+ await ch.start()
+
+ assert ch._running is False