Skip to content

Commit abc7b0a

Browse files
committed
Merge PR #1107: fix(slack): post-process slackify_markdown output to catch leftover artifacts
2 parents f223a4c + 96e1730 commit abc7b0a

1 file changed

Lines changed: 25 additions & 1 deletion

File tree

nanobot/channels/slack.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,14 +229,38 @@ def _strip_bot_mention(self, text: str) -> str:
229229
return re.sub(rf"<@{re.escape(self._bot_user_id)}>\s*", "", text).strip()
230230

231231
_TABLE_RE = re.compile(r"(?m)^\|.*\|$(?:\n\|[\s:|-]*\|$)(?:\n\|.*\|$)*")
232+
_CODE_FENCE_RE = re.compile(r"```[\s\S]*?```")
233+
_INLINE_CODE_RE = re.compile(r"`[^`]+`")
234+
_LEFTOVER_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
235+
_LEFTOVER_HEADER_RE = re.compile(r"^#{1,6}\s+(.+)$", re.MULTILINE)
236+
_BARE_URL_RE = re.compile(r"(?<![|<])(https?://\S+)")
232237

233238
@classmethod
234239
def _to_mrkdwn(cls, text: str) -> str:
235240
"""Convert Markdown to Slack mrkdwn, including tables."""
236241
if not text:
237242
return ""
238243
text = cls._TABLE_RE.sub(cls._convert_table, text)
239-
return slackify_markdown(text)
244+
return cls._fixup_mrkdwn(slackify_markdown(text))
245+
246+
@classmethod
247+
def _fixup_mrkdwn(cls, text: str) -> str:
248+
"""Fix markdown artifacts that slackify_markdown misses."""
249+
code_blocks: list[str] = []
250+
251+
def _save_code(m: re.Match) -> str:
252+
code_blocks.append(m.group(0))
253+
return f"\x00CB{len(code_blocks) - 1}\x00"
254+
255+
text = cls._CODE_FENCE_RE.sub(_save_code, text)
256+
text = cls._INLINE_CODE_RE.sub(_save_code, text)
257+
text = cls._LEFTOVER_BOLD_RE.sub(r"*\1*", text)
258+
text = cls._LEFTOVER_HEADER_RE.sub(r"*\1*", text)
259+
text = cls._BARE_URL_RE.sub(lambda m: m.group(0).replace("&amp;", "&"), text)
260+
261+
for i, block in enumerate(code_blocks):
262+
text = text.replace(f"\x00CB{i}\x00", block)
263+
return text
240264

241265
@staticmethod
242266
def _convert_table(match: re.Match) -> str:

0 commit comments

Comments
 (0)