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

如何使用Google Workspace开发者预览计划JS/TS库创建Chat空间

使用无委托服务账号创建Google Chat空间(TypeScript/JavaScript)

前置配置

  • 确保你的服务账号已在Google Admin控制台被授予Google Chat API管理员权限(需分配chat.spaces.create权限范围)
  • 已下载服务账号的JSON密钥文件,保存为service-account-key.json
  • 已在Google Cloud控制台启用Google Chat API(预览版需先启用基础API)

安装依赖

在项目中安装官方Google APIs客户端库及TypeScript相关依赖:

npm install googleapis typescript @types/node --save-dev

核心代码实现

创建create-chat-space.ts文件,内容如下:

import { google } from 'googleapis';
import fs from 'fs';

async function createChatSpace() {
  // 加载服务账号密钥
  const key = JSON.parse(fs.readFileSync('./service-account-key.json', 'utf8'));

  // 初始化无委托JWT客户端(无subject参数,以服务账号自身身份操作)
  const auth = new google.auth.JWT({
    email: key.client_email,
    key: key.private_key,
    scopes: ['https://www.googleapis.com/auth/chat.create'],
  });

  // 初始化Chat API客户端
  const chat = google.chat({
    version: 'v1',
    auth,
  });

  try {
    // 调用创建空间接口
    const response = await chat.spaces.create({
      requestBody: {
        displayName: '服务账号测试空间',
        spaceType: 'GROUP_CHAT', // 可选值:GROUP_CHAT(群聊)/ SPACE(命名空间)
      },
    });

    console.log('空间创建成功,ID:', response.data.name);
    console.log('空间访问链接:', `https://chat.google.com/u/0/${response.data.name.split('/')[1]}`);
  } catch (err) {
    console.error('创建失败:', err);
  }
}

createChatSpace();

运行代码

编译并执行TypeScript文件:

tsc create-chat-space.ts && node create-chat-space.js

关键注意事项

  • 无委托模式下,服务账号创建的空间默认仅自身为成员,若需添加域内用户,需额外申请chat.members.create权限并调用成员添加接口
  • 预览版API可能存在功能调整,若遇报错,需核对Chat API预览版文档确认参数是否更新
  • 服务账号密钥文件需妥善保管,建议添加到.gitignore避免泄露

内容的提问来源于stack exchange,提问作者Patrick M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:01:08