fix(dingtalk): handle multi-backtick inline code spans (#8469)

* fix(dingtalk): handle multi-backtick inline code spans

* fix(dingtalk): normalize inline code span padding

Signed-off-by: Willem Jiang <willem.jiang@gmail.com>

---------

Signed-off-by: Willem Jiang <willem.jiang@gmail.com>
Co-authored-by: ZcWang <200940025+hajicheng@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
hajicheng 2026-11-22 17:01:31 +08:00 committed by GitHub
parent e9d481e9f5
commit 53e6042c29
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 33 additions and 8 deletions

View File

@ -113,7 +113,8 @@ def _extract_text_from_rich_text(rich_text_list: list) -> str:
_FENCED_CODE_BLOCK_RE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
_INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")
# Match complete backtick runs of equal length so shorter runs stay inside the code.
_INLINE_CODE_RE = re.compile(r"(?<!`)(?P<delimiter>`+)(?!`)(?P<code>[^\n]+?)(?<!`)(?P=delimiter)(?!`)")
_HORIZONTAL_RULE_RE = re.compile(r"^-{3,}$", re.MULTILINE)
_TABLE_SEPARATOR_RE = re.compile(r"^\|[-:| ]+\|$", re.MULTILINE)
@ -169,8 +170,15 @@ def _adapt_markdown_for_dingtalk(text: str) -> str:
quoted_lines = "\n".join(f"> {line}" for line in code.split("\n"))
return f"{prefix}{quoted_lines}\n"
def _inline_code_to_bold(match: re.Match) -> str:
code = match.group("code")
# CommonMark drops one padding space from each end of a nonblank span.
if code.startswith(" ") and code.endswith(" ") and code.strip(" "):
code = code[1:-1]
return f"**{code}**"
text = _FENCED_CODE_BLOCK_RE.sub(_code_block_to_quote, text)
text = _INLINE_CODE_RE.sub(r"**\1**", text)
text = _INLINE_CODE_RE.sub(_inline_code_to_bold, text)
text = _convert_markdown_table(text)
text = _HORIZONTAL_RULE_RE.sub("───────────", text)
return text

View File

@ -1209,11 +1209,12 @@ class TestGroupMessageMarkdownFormat:
return FakeResponse()
with patch("app.channels.dingtalk.httpx.AsyncClient", return_value=FakeClient()):
await channel._send_group_message("bot", "conv1", "hello")
await channel._send_group_message("bot", "conv1", "Use `` `--flag` ``.")
assert len(captured_json) == 1
payload = captured_json[0]
assert payload["msgKey"] == "sampleMarkdown"
assert json.loads(payload["msgParam"])["text"] == "Use **`--flag`**."
_run(go())
@ -1233,10 +1234,22 @@ class TestAdaptMarkdownForDingtalk:
assert "```" not in result
assert "> plain code" in result
def test_inline_code_to_bold(self):
text = "Use `pip install` to install"
result = _adapt_markdown_for_dingtalk(text)
assert result == "Use **pip install** to install"
@pytest.mark.parametrize(
("text", "expected"),
[
("Use `pip install` to install", "Use **pip install** to install"),
("Use ``a`b`` and `pwd`.", "Use **a`b** and **pwd**."),
("Use ```a``b```.", "Use **a``b**."),
("Use `` cmd ``.", "Use **cmd**."),
("Use `` `--flag` ``.", "Use **`--flag`**."),
("Keep ` cmd `.", "Keep ** cmd **."),
("Keep ` cmd` and ` `.", "Keep ** cmd** and ** **."),
("Keep ``unfinished and use `pwd`.", "Keep ``unfinished and use **pwd**."),
("Keep ``one\ntwo`` across lines.", "Keep ``one\ntwo`` across lines."),
],
)
def test_inline_code_to_bold(self, text, expected):
assert _adapt_markdown_for_dingtalk(text) == expected
def test_horizontal_rule_to_unicode(self):
text = "Above\n---\nBelow"

View File

@ -266,7 +266,11 @@ Scheduled-task result and lifecycle notices can also be pushed to a bound Feishu
3. Copy the `Client ID` and `Client Secret`, set `DINGTALK_CLIENT_ID` and `DINGTALK_CLIENT_SECRET` in `.env`, and enable the channel in `config.yaml`.
4. *(Optional)* To enable streaming AI Card replies (typewriter effect), create an **AI Card** template on the [DingTalk Card Platform](https://open.dingtalk.com/document/dingstart/typewriter-effect-streaming-ai-card), then set `card_template_id` in `config.yaml` to the template ID. You also need to apply for the `Card.Streaming.Write` and `Card.Instance.Write` permissions.
DingTalk's Markdown fallback displays tables as labeled blockquotes, preserving escaped pipes (`\|`) within cells and empty leading or trailing cells so values stay under the correct column labels.
DingTalk's Markdown fallback converts same-line code spans with equal-length
backtick delimiters to bold. For spans with non-space content, it removes one
ASCII space from each end when both ends are padded. Tables display as labeled
blockquotes, preserving escaped pipes (`\|`) within cells and empty leading or
trailing cells so values stay under the correct column labels.
DingTalk token caching uses a two-hour fallback when the provider's token lifetime is invalid or no longer than the five-minute refresh margin, avoiding a refresh on every request.