You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python SDK框架在Microsoft Teams中发送代码片段?

在Microsoft Teams中通过Python SDK发送原生代码片段

要发送Teams支持的原生代码片段(带复制功能的那种),不能只用纯文本的反引号语法,需要使用**自适应卡片(Adaptive Card)**来实现——Teams的原生代码片段是通过自适应卡片里的TextBlock配合code样式来渲染的。

解决步骤:

  • 导入Bot Framework SDK中自适应卡片相关依赖
  • 构建包含代码片段的自适应卡片JSON结构,核心是给TextBlock设置style: "code"
  • 将卡片作为附件添加到消息活动中发送

完整代码示例:

from botbuilder.core import TurnContext, ActivityTypes
from botbuilder.schema import Attachment

def create_code_snippet_card(code_content: str, language: str = "python") -> Attachment:
    # 构建自适应卡片,使用code样式渲染代码片段
    adaptive_card = {
        "type": "AdaptiveCard",
        "version": "1.4",
        "body": [
            {
                "type": "TextBlock",
                "text": f"```{language}\n{code_content}\n```",
                "wrap": True,
                "style": "code"
            }
        ]
    }
    return Attachment(
        content_type="application/vnd.microsoft.card.adaptive",
        content=adaptive_card
    )

# 调用示例
async def send_code_message(turn_context: TurnContext, code_output: str):
    code_attachment = create_code_snippet_card(code_output)
    message_activity = Activity(
        type=ActivityTypes.message,
        attachments=[code_attachment]
    )
    await turn_context.send_activity(message_activity)

关键说明:

  • style": "code"是实现原生代码片段的核心配置,Teams会识别这个样式并渲染出带复制按钮的代码块
  • 自适应卡片版本需指定为1.4或更高,确保code样式被支持
  • 可以通过调整TextBlock的size、fontType等属性,自定义代码片段的显示样式

内容的提问来源于stack exchange,提问作者Eduard Grosu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:31:15