如何在Google Chat CardsV2 API通知中正确渲染格式化代码块?
如何在Google Chat CardsV2 API通知中正确渲染格式化代码块?
我之前也踩过这个坑!Google Chat的CardsV2 API对textParagraph组件支持的HTML标签有严格限制,<code>和<pre>确实不在官方允许的标签列表里,这就是为什么你的这些标签会被直接当成纯文本渲染的原因。
目前的可行替代方案
因为没有原生的代码块支持,我们只能通过视觉模拟来实现类似效果,主要思路是用等宽字体还原代码的排版风格:
- 行内代码模拟:用
<font face="monospace">标签替代<code>,文本会以等宽字体显示,视觉上和原生代码效果一致。 - 多行代码/异常信息模拟:对于多行内容,先把换行符
\n替换成HTML换行标签<br>,再用等宽字体包裹,就能保留多行结构。
修改你的代码示例
针对你提供的代码,我们可以这样调整:
import json import requests def build_card_payload(context: dict) -> str: """Construct the Google Chat card payload from task context.""" task_instance = context.get("task_instance") state = task_instance.get("state") if state == "success": state_str = '<font color="#1E8449">Success</font>' icon = "" title_state = "Succeeded" else: state_str = '<font color="#E74C3C">Failed</font>' icon = "" title_state = "Failed" title = f"{icon} Task {title_state}" exception_text = None if context.get("exception"): # 替换换行为<br>,用等宽字体包裹多行异常信息 formatted_exception = context['exception'].replace('\n', '<br>') exception_text = f"<font face='monospace'>{formatted_exception}</font>" details = [ f"• <b>Task ID:</b> <font face='monospace'>{task_instance.get('task_id')}</font>", f"• <b>State:</b> {state_str}", f"• <b>Try Number:</b> <font face='monospace'>{task_instance.get('try_number')}</font>", f"• <b>Execution Date:</b> <font face='monospace'>{context.get('execution_date', 'N/A')}</font>", ] if exception_text: # 增加空行提升代码区块可读性 details.append(f"• <b>Error Details:</b><br><br>{exception_text}") widgets = [{"textParagraph": {"text": "<br>".join(details)}}] sections = [{ "header": "Task Details", "widgets": widgets, }] card = { "cardsV2": [ { "cardId": "task-notification", "card": { "header": {"title": title}, "sections": sections, } } ] } return json.dumps(card) # 后续发送逻辑不变 payload = build_card_payload(context) headers = {"Content-Type": "application/json"} response = requests.post(webhook_url, headers=headers, data=payload) response.raise_for_status()
额外提醒
- 你可以在Google Chat官方文档里确认支持的HTML标签列表,目前支持的包括
<b>、<i>、<font>、<br>、<a>等,但确实不包含<code>、<pre>这类代码相关标签。 - 如果想让代码区块更突出,还可以在异常信息前后多插几个
<br>增加间距,或者用<hr>标签(需测试兼容性)添加分隔线,进一步区分内容区块。
内容来源于stack exchange
相关产品推荐
相关产品推荐

