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

SPFx WebPart嵌入Copilot Studio机器人至SharePoint Online首页失败,求Bot Framework WebChat示例

基于Bot Framework WebChat的SPFx WebPart集成Copilot Studio机器人示例

核心实现思路

通过SPFx WebPart嵌入Bot Framework WebChat控件,直接在SharePoint页面中渲染Copilot Studio机器人,替代原生右侧面板模式。关键是通过Entra ID获取机器人的访问令牌,实现安全认证。

步骤1:确认Entra ID应用权限

确保已注册的Entra ID应用具备以下委派权限(需管理员同意):

  • Bot Framework -> User.Read
  • Microsoft Graph -> User.Read

步骤2:SPFx WebPart组件代码实现

使用Yeoman生成React类型的SPFx WebPart后,替换WebPart的React组件代码(示例文件:BotChatWebPart.tsx):

引入依赖

import React, { useEffect, useRef, useState } from 'react';
import { AuthenticationContext } from '@microsoft/sp-http';
import styles from './BotChatWebPart.module.scss';
import { IBotChatWebPartProps } from './IBotChatWebPartProps';

核心组件逻辑

const BotChatWebPart: React.FC<IBotChatWebPartProps> = (props) => {
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [token, setToken] = useState<string | null>(null);
  
  // 替换为你的实际配置
  const BOT_DIRECTLINE_ENDPOINT = "https://directline.botframework.com/v3/directline";
  const ENTRA_APP_CLIENT_ID = "<你的Entra ID应用客户端ID>";
  const COPILOT_BOT_ID = "<你的Copilot Studio机器人ID>";

  // 获取Entra ID访问令牌
  useEffect(() => {
    const fetchAccessToken = async () => {
      const authContext = new AuthenticationContext(props.context.pageContext.web.absoluteUrl);
      try {
        const tokenRes = await authContext.acquireToken(
          "https://api.botframework.com",
          ENTRA_APP_CLIENT_ID
        );
        if (tokenRes.accessToken) setToken(tokenRes.accessToken);
      } catch (err) {
        console.error("令牌获取失败:", err);
      }
    };
    fetchAccessToken();
  }, [props.context]);

  // 初始化WebChat控件
  useEffect(() => {
    if (!token || !chatContainerRef.current) return;

    // 加载WebChat脚本
    const script = document.createElement('script');
    script.src = "https://cdn.botframework.com/botframework-webchat/latest/webchat.js";
    script.onload = () => {
      if (window.WebChat) {
        window.WebChat.renderWebChat(
          {
            directLine: window.WebChat.createDirectLine({
              token: token,
              domain: `${BOT_DIRECTLINE_ENDPOINT}/tokens/generate`
            }),
            userID: props.context.pageContext.user.loginName,
            username: props.context.pageContext.user.displayName,
            locale: 'zh-CN',
            // 可添加更多WebChat自定义配置
            styleOptions: {
              backgroundColor: '#f5f5f5',
              bubbleBackground: '#ffffff',
              botAvatarInitials: 'AI',
              userAvatarInitials: 'ME'
            }
          },
          chatContainerRef.current
        );
      }
    };
    document.body.appendChild(script);

    // 清理函数
    return () => {
      document.body.removeChild(script);
      if (chatContainerRef.current) chatContainerRef.current.innerHTML = '';
    };
  }, [token, props.context.pageContext.user]);

  return (
    <div className={styles.botChatWebPart} style={{ height: '600px', width: '100%', border: '1px solid #e0e0e0', borderRadius: '4px' }}>
      {token ? (
        <div ref={chatContainerRef} style={{ height: '100%', width: '100%' }}></div>
      ) : (
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', color: '#666' }}>
          机器人加载中...
        </div>
      )}
    </div>
  );
};

export default BotChatWebPart;

步骤3:关键配置说明

  • ENTRA_APP_CLIENT_ID:Entra ID应用注册页面获取的客户端ID
  • COPILOT_BOT_ID:Copilot Studio机器人“设置”->“配置”页面的机器人ID
  • WebChat样式:通过styleOptions可自定义聊天窗口背景、气泡样式、头像等,适配SharePoint页面风格

步骤4:构建与部署

执行常规SPFx部署流程:

  1. gulp build
  2. gulp bundle --ship
  3. gulp package-solution --ship
  4. 将生成的.sppkg文件上传至SharePoint应用目录,部署后添加到首页WebPart区域

注意事项

  • 确保Entra ID应用的重定向URI包含SharePoint网站域名(如https://<租户>.sharepoint.com/*)
  • 若需离线部署,可将WebChat脚本下载至SPFx项目的src/lib目录,修改脚本引用路径
  • 测试使用租户管理员账号,验证权限配置生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.11 19:12:38