如何用AppScript提取Google Space成员列表?求技术指导
获取Google Chat空间成员信息的实现方案
你提到的spaces.members/list接口确实可以获取Google Chat空间的成员信息,以下是具体实现步骤和代码示例:
前提条件
- 已在Google Cloud控制台启用Google Chat API
- 创建了OAuth 2.0凭据(用户凭据或服务账号凭据)
- 发起请求的账号拥有目标空间的访问权限(成员或管理员身份)
核心权限说明
需要申请以下OAuth权限之一:
chat.memberships.readonly:只读获取成员信息(推荐)chat.memberships:读写成员信息(如果需要修改成员)
Python代码示例
from google.oauth2.credentials import Credentials from googleapiclient.discovery import build # 替换为你的凭据文件路径和目标空间ID CREDENTIALS_FILE = "your-credentials.json" SPACE_ID = "spaces/xxx123abc" # 空间ID格式为spaces/[空间标识] # 定义所需权限 SCOPES = ["https://www.googleapis.com/auth/chat.memberships.readonly"] def fetch_space_members(): # 加载用户凭据 creds = Credentials.from_authorized_user_file(CREDENTIALS_FILE, SCOPES) # 创建Chat API客户端 chat_service = build("chat", "v1", credentials=creds) try: # 调用成员列表接口 response = chat_service.spaces().members().list(parent=SPACE_ID).execute() memberships = response.get("memberships", []) if not memberships: print("当前空间没有成员") else: print("空间成员列表:") for member in memberships: user_info = member.get("member", {}).get("user", {}) print(f"姓名: {user_info.get('displayName')}, 邮箱: {user_info.get('email')}, 用户ID: {user_info.get('name')}") except Exception as e: print(f"请求失败: {str(e)}") if __name__ == "__main__": fetch_space_members()
Node.js代码示例
const { google } = require("googleapis"); const fs = require("fs"); // 替换为你的凭据路径和空间ID const CREDENTIALS_PATH = "./your-credentials.json"; const TOKEN_PATH = "./token.json"; // 授权后生成的令牌文件 const SPACE_ID = "spaces/xxx123abc"; const SCOPES = ["https://www.googleapis.com/auth/chat.memberships.readonly"]; async function getSpaceMembers() { // 加载OAuth客户端配置 const credentials = JSON.parse(fs.readFileSync(CREDENTIALS_PATH)); const { client_id, client_secret, redirect_uris } = credentials.installed; const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]); // 加载已获取的访问令牌 const token = JSON.parse(fs.readFileSync(TOKEN_PATH)); oAuth2Client.setCredentials(token); // 创建Chat API服务实例 const chat = google.chat({ version: "v1", auth: oAuth2Client }); try { const response = await chat.spaces.members.list({ parent: SPACE_ID }); const memberships = response.data.memberships || []; if (memberships.length === 0) { console.log("当前空间没有成员"); return; } console.log("空间成员列表:"); memberships.forEach(member => { const user = member.member?.user; console.log(`姓名: ${user?.displayName}, 邮箱: ${user?.email}, 用户ID: ${user?.name}`); }); } catch (err) { console.error("请求失败:", err.message); } } getSpaceMembers();
关键注意事项
- 空间ID获取:打开目标Google Chat空间,URL中的
space/后面的字符串即为空间标识,拼接成spaces/[标识]作为接口的parent参数。 - 权限验证:如果返回
403 Forbidden,说明账号无访问权限或未正确申请OAuth权限;返回404 Not Found说明空间不存在或账号无权访问该空间。 - 服务账号使用:针对Google Workspace账号,可给服务账号配置域范围委派,模拟域内用户发起请求,无需手动授权。
内容的提问来源于stack exchange,提问作者Gitz
相关产品推荐
相关产品推荐

