Skip to content

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

Merge dev into PR #1687 and preserve integrated behavior

Bingxi Zhao (Frank)58e4601b52a5
diff --cc deeptutor/partners/channels/telegram.py
index 5f240375a,ca1e7bddf..1f4ecdff1
--- a/deeptutor/partners/channels/telegram.py
+++ b/deeptutor/partners/channels/telegram.py
@@@ -48,28 -48,42 +48,64 @@@ class _StreamBuf
stream_id: str | None = None
+class TelegramChatPolicy(Base):
+ """Per-chat inbound response policy."""
+
+ chat_id: int = Field(description="Telegram chat id this rule applies to.")
+ policy: Literal["open", "mention", "topics_only"] = Field(
+ description=(
+ "open responds to every message; mention requires an explicit mention or bot reply; "
+ "topics_only responds without a mention only in allowed_topics."
+ )
+ )
+ allowed_topics: list[int] = Field(
+ default_factory=list,
+ description="Telegram message_thread_id values that may receive automatic replies.",
+ )
+
+ @model_validator(mode="after")
+ def _require_allowed_topics(self) -> "TelegramChatPolicy":
+ if self.policy == "topics_only" and not self.allowed_topics:
+ raise ValueError("topics_only policy requires at least one allowed topic")
+ return self
+
+
+ _FENCE_OPEN_RE = re.compile(r"^[ \t]*(`{3,}|~{3,})(.*)$")
+ _INLINE_FENCE_RE = re.compile(r"```[\w]*\n?([\s\S]*?)```")
+
+
+ def _replace_fenced_code(text: str, replace: Callable[[str], str]) -> str:
+ """Replace fenced code blocks with ``replace(code)``.
+
+ A block opens on a ``` or ~~~ line (a backtick fence's info string cannot
+ contain a backtick) and closes on a line holding only a run of the same
+ character that is at least as long, so tilde fences work, an info string
+ such as ``c++`` stays out of the code, and a ```` fence can show a ```
+ example. What remains (one-line ```code``` and unclosed fences) keeps the
+ previous regex handling.
+ """
+ lines = text.split("\n")
+ out: list[str] = []
+ i = 0
+ while i < len(lines):
+ match = _FENCE_OPEN_RE.match(lines[i])
+ if match and not (match.group(1)[0] == "`" and "`" in match.group(2)):
+ fence = match.group(1)
+ for j in range(i + 1, len(lines)):
+ closing = lines[j].strip()
+ if closing == fence[0] * len(closing) and len(closing) >= len(fence):
+ out.append(replace("".join(line + "\n" for line in lines[i + 1 : j])))
+ i = j + 1
+ break
+ else:
+ out.append(lines[i])
+ i += 1
+ continue
+ out.append(lines[i])
+ i += 1
+ return _INLINE_FENCE_RE.sub(lambda m: replace(m.group(1)), "\n".join(out))
+
+
def _strip_md_block(text: str) -> str:
"""Strip block-level and inline markdown for readable plain-text preview.