I am trying to add code block formatting to a card sent as a notification via Google Chat cardsV2 API. However, the code block formatting is completely ignored and fails to render properly.
I have tried building the card using both the API directly and the official UI Kit builder provided by Google (https://addons.gsuite.google.com/uikit/builder ), but the code block tags such as <code> and <pre> get rendered as normal text without formatting.
The code used for creating the card:
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"):
exception_text = f"<pre>{context['exception']}</pre>"
details = [
f"• <b>Task ID:</b> <code>{task_instance.get('task_id')}</code>",
f"• <b>State:</b> {state_str}",
f"• <b>Try Number:</b> <code>{task_instance.get('try_number')}</code>",
f"• <b>Execution Date:</b> <code>{context.get('execution_date', 'N/A')}</code>",
]
if exception_text:
details.append(f"• <b>Error Details:</b><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()
The screenshot from the CardBuilder: https://i.sstatic.net/GO4MpqQE.png
Despite including <code> for inline code snippets and <pre> for multiline blocks, the rendered card ignores these tags and displays them as normal text.
Is there a known way to render properly formatted code blocks in Google Chat cards via the cardsV2 API? Or are code block styles unsupported currently?
Any advice or pointers on achieving this would be greatly appreciated.
<code>and<pre>are part of the Google Workspace Developer Preview Program. Did you join?