在 Google Chat 中创建命名聊天室

本指南介绍了如何使用 Google Chat API 的 Space 资源中的 create() 方法创建命名空间。

已命名的聊天室(其中 spaceTypeSPACE)是用户发送消息、分享文件和协作的场所。 命名聊天室可以包含 Chat 应用。命名聊天室有聊天室管理员,他们可以应用管理设置、说明,以及添加或移除用户和应用。

如需创建不同类型的 Chat 聊天室(包括私信或群组消息),请使用 Space 资源中的 setUp() 方法来创建聊天室并同时添加成员。如需了解详情,请参阅设置空间

创建命名聊天室后,该聊天室的唯一成员是经过身份验证的用户。如需向聊天室添加成员,请针对要添加的每个人或应用对 Membership 资源调用 create() 方法。或者,您也可以使用 setUp() 方法来创建命名空间并同时向其中添加成员。

前提条件

Node.js

Python

Java

Apps 脚本

以用户身份创建命名空间

如需创建具有用户身份验证的命名空间,请在请求中传递以下内容:

  • 指定 chat.spaces.createchat.spaces 授权范围。
  • 调用 CreateSpace() 方法,并传递 space 作为 Space 的实例,其中包含以下字段:
    • spaceType设置成了 SPACE
    • displayName 设置为聊天室的用户可见名称。
    • 您可以选择设置其他属性,例如以下属性:
      • spaceDetails- 聊天室的用户可见说明和一组指南。
      • predefinedPermissionSettings- 聊天室的预定义权限。 例如,您可以将其配置为允许所有成员或仅允许聊天室管理员发布消息。

以下是创建命名空间的步骤:

Node.js

chat/client-libraries/cloud/create-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 create a named space 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'     }   };    // Make the request   const response = await chatClient.createSpace(request);    // Handle the response   console.log(response); }  main().catch(console.error);

Python

chat/client-libraries/cloud/create_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 create_space_with_user_cred():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.CreateSpaceRequest(         space = {             "space_type": 'SPACE',             # Replace DISPLAY_NAME here.             "display_name": 'DISPLAY_NAME'         }     )      # Make the request     response = client.create_space(request)      # Handle the response     print(response)  create_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.CreateSpaceRequest; import com.google.chat.v1.Space;  // This sample shows how to create space with user credential. public class CreateSpaceUserCred {    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))) {       CreateSpaceRequest.Builder request = CreateSpaceRequest.newBuilder()         .setSpace(Space.newBuilder()           .setSpaceType(Space.SpaceType.SPACE)           // Replace DISPLAY_NAME here.           .setDisplayName("DISPLAY_NAME"));       Space response = chatServiceClient.createSpace(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps 脚本

chat/advanced-service/Main.gs
/**  * This sample shows how to create space 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 createSpaceUserCred() {   // Initialize request argument(s)   const space = {     spaceType: 'SPACE',     // TODO(developer): Replace DISPLAY_NAME here     displayName: 'DISPLAY_NAME'   };    // Make the request   const response = Chat.Spaces.create(space);    // Handle the response   console.log(response); }

创建命名聊天室作为 Chat 应用

应用身份验证需要管理员一次性批准

如需邀请或添加用户加入具有应用身份验证的空间,请在请求中传递以下内容:

  • 指定 chat.app.spaces.createchat.app.spaces 授权范围。
  • Space 资源调用 create 方法
  • spaceType 设置为 SPACE
  • displayName 设置为聊天室的用户可见名称。在以下示例中,displayName 设置为 API-made
  • 使用 customer 字段指定 Google Workspace 网域的客户 ID。
  • (可选)设置其他聊天室属性,例如 spaceDetails(用户可见的聊天室说明和一组准则)。

编写调用 Chat API 的脚本

以下是创建命名空间的步骤:

Python

  1. 在工作目录中,创建一个名为 chat_space_create_named_app.py 的文件。
  2. chat_space_create_named_app.py 中添加以下代码:

    from google.oauth2 import service_account from apiclient.discovery import build  # Define your app's authorization scopes. # When modifying these scopes, delete the file token.json, if it exists. SCOPES = ["https://www.googleapis.com/auth/chat.app.spaces.create"]  def main():     '''     Authenticates with Chat API using app authentication,     then creates a Chat space.     '''      # Specify service account details.     creds = (         service_account.Credentials.from_service_account_file('credentials.json')         .with_scopes(SCOPES)     )      # Build a service endpoint for Chat API.     chat = build('chat', 'v1', credentials=creds)      # Use the service endpoint to call Chat API.     result = chat.spaces().create(        # Details about the space to create.       body = {          # To create a named space, set spaceType to SPACE.         'spaceType': 'SPACE',          # The user-visible name of the space.         'displayName': 'API-made',          # The customer ID of the Workspace domain.         'customer': 'CUSTOMER'       }        ).execute()      # Prints details about the created space.     print(result)  if __name__ == '__main__':     main() 
  3. 在代码中,替换以下内容:

    • CUSTOMER:相应空间所属网域的客户 ID,格式为 customer/{customer},其中 {customer}Admin SDK 客户资源中的 ID。 如需在与 Chat 应用相同的 Google Workspace 组织中创建聊天室,请使用 customers/my_customer
  4. 在工作目录中,构建并运行示例:

    python3 chat_space_create_named_app.py

在 Google Chat 中打开聊天室

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

限制和注意事项

  • 使用应用身份验证创建聊天室时,经过身份验证的 Chat 应用会添加为聊天室成员,但与用户身份验证不同的是,它不会添加为聊天室管理员。默认情况下,所有聊天室成员都可以移除 Chat 应用。如需仅允许聊天室管理员移除 Chat 应用,请将 permissionSettings.manageApps 设置为 managersAllowed