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

BotBuilder v4.22.3中updateActivity更新自适应卡片报缺失活动类型错误求助

解决validateAndFixActivity(): missing activity type错误及Teams消息更新方案

错误修复方案

问题根源

你虽然手动设置了message.type = "message",但通过MessageFactory.attachment()创建的消息对象缺失了updateActivity必需的上下文字段(如conversation、channelId等),导致Bot Framework的验证逻辑触发错误。

代码修正

不要直接新建独立的消息对象,而是基于当前上下文的活动信息构建更新消息,确保所有必填字段完整:

try {
  await teamsBot.run(context);
  const updatedTemplate = structuredClone(onCallNotificationTemplate);
  const card2 = CardFactory.adaptiveCard(
    AdaptiveCards.declare<CardDataOnCall>(updatedTemplate).render(payload)
  );

  // 基于原活动上下文构建更新消息,继承必填字段
  const messageToUpdate = {
    ...context.activity,
    id: "xxxxxxxxx", // 目标更新消息ID
    type: "message",
    attachments: [card2], // 替换为新自适应卡片
    text: "", // 自适应卡片消息可留空text字段
  };

  await context.updateActivity(messageToUpdate);
} catch (error) {
  console.error("Error sending on-call adaptive card:", error);
}

如果坚持使用MessageFactory,需手动补充上下文字段:

const message = MessageFactory.attachment(card2);
message.id = "xxxxxxxxx";
message.type = "message";
// 补充Bot Framework验证所需的上下文字段
message.conversation = context.activity.conversation;
message.channelId = context.activity.channelId;
message.from = context.activity.from;
message.recipient = context.activity.recipient;

await context.updateActivity(message);

使用Microsoft Graph API更新Teams消息(Node.js示例)

若Bot Framework方法无法满足需求,可直接调用Graph API实现更新:

  1. 安装依赖:
npm install @microsoft/microsoft-graph-client @azure/identity
  1. 代码示例:
const { Client } = require("@microsoft/microsoft-graph-client");
const { ClientSecretCredential } = require("@azure/identity");

// 初始化Graph客户端
const credential = new ClientSecretCredential(
  "你的租户ID",
  "你的应用程序ID",
  "你的应用程序密钥"
);
const graphClient = Client.initWithMiddleware({
  authProvider: {
    getAccessToken: async () => {
      const token = await credential.getToken("https://graph.microsoft.com/.default");
      return token.token;
    },
  },
});

async function updateTeamsMessage(teamId, channelId, messageId, adaptiveCard) {
  try {
    await graphClient.api(`/teams/${teamId}/channels/${channelId}/messages/${messageId}`)
      .patch({
        body: {
          contentType: "html",
          content: JSON.stringify(adaptiveCard)
        }
      });
    console.log("消息更新成功");
  } catch (error) {
    console.error("更新消息失败:", error);
  }
}

// 调用示例
const renderedCard = AdaptiveCards.declare<CardDataOnCall>(updatedTemplate).render(payload);
updateTeamsMessage("目标团队ID", "目标频道ID", "要更新的消息ID", renderedCard);

注意:需确保应用已获得ChannelMessage.ReadWrite.All或对应场景的Graph API权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 22:33:23