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

使用Microsoft Graph向Teams发送Adaptive Card遇400错误

解决Microsoft Graph发送Teams Adaptive Card的400错误

问题根源

你遇到的400 BadRequest错误(提示“Empty Payload. JSON content expected.”)有两个核心原因:

  1. 参数传递错误:使用requests.post时,json参数要求传入Python字典,你却传入了json.dumps()生成的字符串,导致请求负载格式异常。
  2. 消息结构不符合Graph API规范:直接将Adaptive Card的顶层结构作为请求体是错误的,必须按照Teams消息的格式包裹Adaptive Card。

修正后的代码

import requests

def send_teams_message_alt(team_id, channel_id, message_id, bearer_token):
    url = f"https://graph.microsoft.com/v1.0/teams/{team_id}/channels/{channel_id}/messages/{message_id}/replies"

    headers = {
        "Authorization": f"Bearer {bearer_token}"
    }
    
    # 正确的消息结构:将Adaptive Card放在attachments中
    message_payload = {
        "body": {
            "contentType": "html",
            "content": "这是一条包含Adaptive Card的消息"  # 可选,可留空
        },
        "attachments": [
            {
                "contentType": "application/vnd.microsoft.card.adaptive",
                "content": {
                    "type": "AdaptiveCard",
                    "version": "1.0",  # 必须指定Adaptive Card版本
                    "body": [
                        {
                            "type": "TextBlock",
                            "text": "Hello world!",
                            "size": "large",
                            "weight": "bolder"
                        },
                        {
                            "type": "TextBlock",
                            "text": "This is the output message in JSON format using vnd.microsoft.card.adaptive.",
                            "wrap": True
                        }
                    ]
                }
            }
        ],
        "replyToId": message_id
    }

    response = requests.post(url, headers=headers, json=message_payload)

    if response.status_code == 201:
        print("Adaptive Card消息发送成功。")
    else:
        print("发送Adaptive Card消息失败:", response.status_code, response.text)

关键修正点

  • 移除json.dumps()包装:直接将Python字典传给requests.post的json参数,requests会自动完成序列化并设置正确的请求头。
  • 符合Graph API消息结构:
    • 用attachments数组承载Adaptive Card,指定contentType为application/vnd.microsoft.card.adaptive。
    • Adaptive Card本身必须包含version字段(如"version": "1.0"),这是Adaptive Card规范要求的。
    • 保留replyToId字段在顶层,用于指定回复的目标消息ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:05:05