创建 Google Chat 聊天室并添加成员

本指南介绍了如何使用 Google Chat API 的 Space 资源中的 setUp() 方法创建 Chat 聊天室,并向其中添加成员。

Space 资源表示用户和 Chat 应用可以在其中发送消息、共享文件和协作处理事务。聊天室有多种类型:

  • 私信 (DM) 是两位用户之间或用户与 Chat 应用之间的对话。
  • 群聊是指三位或更多用户与聊天应用之间的对话。
  • 命名聊天室是持久存在的聊天室,用户可以在其中发送消息、分享文件和协作。

您可以使用 setUp() 方法执行以下任一操作:

  • 创建具有初始成员的命名空间。
  • 创建两人之间的私信 (DM)。
  • 设置多人群聊。

设置聊天室时,请考虑以下事项:

  • 系统会自动将调用(已通过身份验证)用户添加到聊天室,因此您无需在请求中指定用户的成员身份。
  • 创建私信 (DM) 时,如果两个用户之间存在 DM,则返回该 DM。否则,系统会创建一条私信。
  • 创建群聊时,如果请求中提供的任何成员资格都未成功添加到群聊中(例如,权限问题),则可能会创建一个空群聊(仅包含发起通话的用户)。
  • 您无法设置包含串联回复的聊天室,也无法添加 Google Workspace 组织以外的人员。
  • 系统会过滤掉请求中提供的重复会员资格(包括调用用户),而不是导致请求错误。
  • 当 Google Workspace 管理员为其整个 Google Workspace 组织安装 Chat 应用时,Google Chat 会在已安装的 Chat 应用与组织中的每个用户之间创建私信,因此无需以编程方式设置私信。您应改为列出聊天室以返回所有私信,或查找私信以获取有关特定私信的详细信息。

前提条件

Node.js

Python

Java

Apps 脚本

设置聊天室

如需设置空间,请在请求中传递以下内容:

  • 指定 chat.spaces.createchat.spaces 授权范围。
  • 调用 SetUpSpace() 方法。
  • 传递 space 作为 Space 的实例,其中包含所有必需的字段,例如 displayNamespaceType
  • memberships 作为 Membership 实例的数组传递。对于每个实例,执行以下操作:
    • 指定 users/{user} 可将人类用户添加为空间成员,其中 {user} 是 People API 中 person{person_id},或者是 Directory API 中 user 的 ID。例如,如果 People API person resourceNamepeople/123456789,您可以通过添加以 users/123456789 作为 member.name 的成员资格,将用户添加到空间。
    • 指定 groups/{group} 可将群组添加为聊天室成员,其中 {group} 是您要为其创建成员资格的群组 ID。可以使用 Cloud Identity API 检索群组的 ID。 例如,如果 Cloud Identity API 返回的群组名称为 groups/123456789,则将 membership.groupMember.name 设置为 groups/123456789。Google 群组无法添加到群聊或私信中,只能添加到已命名的聊天室中。

如需在调用用户与另一人类用户之间创建私信,请在请求中指定人类用户的会员身份。

如需在调用用户和调用应用之间创建私信,请将 space.singleUserBotDm 设置为 true,并且不指定任何会员。您只能使用此方法设置与通话应用的私信。如需将通话应用添加为会议室或两个人类用户之间现有私信的成员,请参阅创建会员

以下示例会创建一个命名空间,并为两名人类用户(经过身份验证的用户和另一名用户)创建该空间的一项成员资格。

Node.js

chat/client-libraries/cloud/set-up-space-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.create'];  // This sample shows how to set up a named space with one initial member // with user credential async function main() {   // Create a client   const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);    // Initialize request argument(s)   const request = {     space: {       spaceType: 'SPACE',       // Replace DISPLAY_NAME here.       displayName: 'DISPLAY_NAME'     },     memberships: [{       member: {         // Replace USER_NAME here.         name: 'users/USER_NAME',         type: 'HUMAN'       }     }]   };    // Make the request   const response = await chatClient.setUpSpace(request);    // Handle the response   console.log(response); }  main().catch(console.error);

Python

chat/client-libraries/cloud/set_up_space_user_cred.py
from authentication_utils import create_client_with_user_credentials from google.apps import chat_v1 as google_chat  SCOPES = ["https://www.googleapis.com/auth/chat.spaces.create"]  def set_up_space_with_user_cred():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.SetUpSpaceRequest(         space = {             "space_type": 'SPACE',             # Replace DISPLAY_NAME here.             "display_name": 'DISPLAY_NAME'         },         memberships = [{             "member": {                 # Replace USER_NAME here.                 "name": 'users/USER_NAME',                 "type_": 'HUMAN'             }         }]     )      # Make the request     response = client.set_up_space(request)      # Handle the response     print(response)  set_up_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.Membership; import com.google.chat.v1.SetUpSpaceRequest; import com.google.chat.v1.Space; import com.google.chat.v1.User;  // This sample shows how to set up a named space with one initial member with // user credential. public class SetUpSpaceUserCred {    private static final String SCOPE =     "https://www.googleapis.com/auth/chat.spaces.create";    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithUserCredentials(           ImmutableList.of(SCOPE))) {       SetUpSpaceRequest.Builder request = SetUpSpaceRequest.newBuilder()         .setSpace(Space.newBuilder()           .setSpaceType(Space.SpaceType.SPACE)           // Replace DISPLAY_NAME here.           .setDisplayName("DISPLAY_NAME"))         .addAllMemberships(ImmutableList.of(Membership.newBuilder()           .setMember(User.newBuilder()             // Replace USER_NAME here.             .setName("users/USER_NAME")             .setType(User.Type.HUMAN)).build()));       Space response = chatServiceClient.setUpSpace(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps 脚本

chat/advanced-service/Main.gs
/**  * This sample shows how to set up a named space with one initial member with  * user credential.  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.create'  * referenced in the manifest file (appsscript.json).  */ function setUpSpaceUserCred() {   // Initialize request argument(s)   const space = {     spaceType: 'SPACE',     // TODO(developer): Replace DISPLAY_NAME here     displayName: 'DISPLAY_NAME'   };   const memberships = [{     member: {       // TODO(developer): Replace USER_NAME here       name: 'users/USER_NAME',       // User type for the membership       type: 'HUMAN'     }   }];    // Make the request   const response = Chat.Spaces.setup({ space: space, memberships: memberships });    // Handle the response   console.log(response); }

如需运行示例,请替换以下内容:

  • DISPLAY_NAME:新空间的显示名称。
  • USER_NAME:要为其添加会员资格的其他用户的 ID。

如需前往相应聊天室,请使用该聊天室的资源 ID 构建相应聊天室的网址。 您可以从 Google Chat 响应正文中的聊天室 name 获取资源 ID。例如,如果您的空间的 namespaces/1234567,您可以使用以下网址前往该空间:https://mail.google.com/chat/u/0/#chat/space/1234567