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

如何通过Bot向Teams指定频道发送自适应卡片?报错求助

解决Teams Bot发送自适应卡片到指定频道的错误问题

错误原因

Unable to extract ConnectorClient from turn context. 这个错误是因为Messaging Extension提交动作的上下文(TurnContext)和普通对话上下文不同,无法直接通过context.sendActivity获取有效的Connector客户端。同时你修改conversationReference的方式也不正确,无法直接切换到目标频道。

解决方案

要向指定频道发送自适应卡片,需要直接使用ConnectorClient来构造并发送消息,步骤如下:

  • 确保Bot已安装到目标频道所在的团队,且拥有发送消息的权限
  • 使用Bot的凭据创建ConnectorClient实例
  • 构建包含自适应卡片的Activity对象
  • 指定目标频道的会话ID,通过ConnectorClient发送消息

修改后的代码示例

import { TurnContext, MessagingExtensionAction, MessagingExtensionActionResponse, ConnectorClient, Activity, CardFactory } from 'botbuilder';
import { Configuration } from 'botbuilder-core';

public async handleTeamsMessagingExtensionSubmitAction(
  context: TurnContext,
  action: MessagingExtensionAction
): Promise<MessagingExtensionActionResponse> {
  // 其他代码...

  // 注意:频道ID格式应为 "19:xxxxxx@thread.tacv2",需替换为真实频道ID
  const channelConversationId = "19:abc123@thread.tacv2";
  const serviceUrl = context.activity.serviceUrl;
  
  // 从配置获取Bot凭据(建议从环境变量或配置文件读取)
  const config = new Configuration();
  const botAppId = config.get<string>('MicrosoftAppId');
  const botAppPassword = config.get<string>('MicrosoftAppPassword');

  // 创建ConnectorClient实例
  const connectorClient = new ConnectorClient(
    { appId: botAppId, appPassword: botAppPassword },
    { baseUri: serviceUrl }
  );

  // 构建包含自适应卡片的消息Activity
  const adaptiveCard = {
    type: "AdaptiveCard",
    version: "1.0",
    body: [
      { type: "TextBlock", text: "这是通过Bot发送的自适应卡片" }
    ]
  };

  const sendActivity: Partial<Activity> = {
    type: "message",
    conversation: { id: channelConversationId },
    attachments: [CardFactory.adaptiveCard(adaptiveCard)]
  };

  // 发送消息到指定频道
  await connectorClient.conversations.sendToConversation(channelConversationId, sendActivity as Activity);

  return {};
}

关键注意事项

  • 频道ID必须是Teams团队中频道的完整会话ID,格式为19:xxxx@thread.tacv2,你可以通过团队设置或Graph API获取正确的ID
  • Bot必须已安装到目标团队,否则会因权限不足发送失败
  • 凭据(MicrosoftAppId和MicrosoftAppPassword)要确保正确,且Bot拥有对应团队的消息发送权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:27:19